feat(chat): enhance chat functionality with song integration and UI improvements

- Updated ChatHeader and ChatMessage components to support song selection and display.
- Enhanced useContentPanel to handle both film and song content, allowing for richer interactions.
- Improved FilmCard and added SongCard components for better media representation.
- Refactored environment variables for better configuration management.
- Updated .gitignore to include development chat history.

Made-with: Cursor
This commit is contained in:
Dorian
2026-03-02 18:16:04 +00:00
parent 6f79f0860d
commit 80aeefa4bf
27 changed files with 1751 additions and 143 deletions
+2 -2
View File
@@ -11,9 +11,9 @@ VITE_ANTHROPIC_TOKEN=sk-ant-oat01-your-token-here
# Option 2: API key from console (https://console.anthropic.com/settings/keys)
VITE_ANTHROPIC_API_KEY=sk-ant-your-key-here
# TMDB API (free, for real film poster images)
# TMDB API (free, fetches posters on-demand when images fail)
# Get your key at: https://www.themoviedb.org/settings/api
VITE_TMDB_API_KEY=your-tmdb-key-here
TMDB_API_KEY=your-tmdb-key-here
# Development flags
VITE_DEV_MODE=true
+3
View File
@@ -26,6 +26,9 @@ packages/app/src-tauri/target/
.DS_Store
Thumbs.db
# Dev chat history
.dev/
# Debug
npm-debug.log*
pnpm-debug.log*
+1 -1
View File
@@ -82,7 +82,7 @@ define(['./workbox-cf23aef7'], (function (workbox) { 'use strict';
"revision": "3ca0b8505b4bec776b69afdba2768812"
}, {
"url": "index.html",
"revision": "0.5aiuhiql2u"
"revision": "0.7fp7mese2fg"
}], {});
workbox.cleanupOutdatedCaches();
workbox.registerRoute(new workbox.NavigationRoute(workbox.createHandlerBoundToURL("index.html"), {
@@ -0,0 +1,24 @@
<svg width="200" height="300" viewBox="0 0 200 300" fill="none" xmlns="http://www.w3.org/2000/svg">
<defs>
<clipPath id="clip-poster">
<rect width="200" height="300" rx="12" fill="white"/>
</clipPath>
</defs>
<g clip-path="url(#clip-poster)">
<rect width="200" height="300" fill="currentColor" fill-opacity="0.15"/>
<g fill="currentColor" fill-opacity="0.2">
<rect x="8" y="12" width="16" height="24" rx="2"/>
<rect x="40" y="12" width="16" height="24" rx="2"/>
<rect x="72" y="12" width="16" height="24" rx="2"/>
<rect x="104" y="12" width="16" height="24" rx="2"/>
<rect x="136" y="12" width="16" height="24" rx="2"/>
<rect x="168" y="12" width="16" height="24" rx="2"/>
<rect x="8" y="48" width="16" height="24" rx="2"/>
<rect x="40" y="48" width="16" height="24" rx="2"/>
<rect x="72" y="48" width="16" height="24" rx="2"/>
<rect x="104" y="48" width="16" height="24" rx="2"/>
<rect x="136" y="48" width="16" height="24" rx="2"/>
<rect x="168" y="48" width="16" height="24" rx="2"/>
</g>
</g>
</svg>

After

Width:  |  Height:  |  Size: 1.1 KiB

+89 -20
View File
@@ -1,33 +1,87 @@
<template>
<div
class="glass-strong rounded-t-2xl flex items-center justify-between px-4 py-3 relative"
:style="isDark
? 'border-bottom: 1px solid rgba(255, 255, 255, 0.08); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.22)'
: 'border-bottom: 1px solid rgba(0, 0, 0, 0.06); box-shadow: inset 0 1px 0 rgba(254, 253, 249, 1)'"
class="glass-strong rounded-t-2xl flex items-center justify-between px-4 py-3 relative z-20 border-t-0 border-x-0"
:class="isDark ? '!border-b-white/10' : '!border-b-black/8'"
>
<div class="flex items-center gap-3 min-w-0">
<div class="flex items-center gap-3 min-w-0 flex-1">
<div class="w-8 h-8 rounded-full flex items-center justify-center shrink-0"
:class="isDark ? 'bg-accent/20' : 'bg-accent/10'">
<span class="text-accent text-sm font-bold">AI</span>
</div>
<div class="min-w-0">
<h2 class="text-sm font-semibold truncate"
:class="isDark ? 'text-white/96' : 'text-gray-900'">{{ title }}</h2>
<div class="flex items-center gap-1.5">
<p class="text-[10px] truncate font-mono"
:class="isDark ? 'text-white/40' : 'text-gray-400'">{{ conversationId }}</p>
<div class="min-w-0 flex-1 relative">
<button
class="w-full text-left group/btn"
:class="conversationList.length > 0 ? 'cursor-pointer' : ''"
@click="conversationList.length > 0 && (showChatList = !showChatList)"
>
<h2 class="text-sm font-semibold truncate"
:class="isDark ? 'text-white/96' : 'text-gray-900'">{{ title }}</h2>
<div class="flex items-center gap-1.5">
<p class="text-[10px] truncate font-mono"
:class="isDark ? 'text-white/40' : 'text-gray-400'">{{ conversationId }}</p>
<span class="text-[10px]" :class="isDark ? 'text-white/20' : 'text-gray-300'">·</span>
<button
class="text-[10px] text-accent/70 hover:text-accent transition-colors truncate"
@click="showModelPicker = !showModelPicker"
<button
class="text-[10px] text-accent/70 hover:text-accent transition-colors truncate"
@click.stop="showModelPicker = !showModelPicker; showChatList = false"
>
{{ modelDisplayName }}
</button>
</div>
</button>
<Transition name="picker">
<div
v-if="showChatList && conversationList.length > 0"
class="contents"
>
{{ modelDisplayName }}
</button>
</div>
<div
class="fixed inset-0 z-40"
aria-hidden="true"
@click="showChatList = false"
/>
<div
class="absolute left-0 right-0 top-full z-50 mt-1 p-2 max-h-48 overflow-y-auto animate-fade-up-fast shadow-2xl rounded-xl"
:class="isDark ? 'bg-[#161618] border border-white/10' : 'bg-white border border-black/10'"
@click.stop
>
<p class="text-[10px] font-semibold uppercase tracking-wider mb-2 px-1"
:class="isDark ? 'text-white/40' : 'text-gray-400'">Saved chats</p>
<button
v-for="c in conversationList"
:key="c.id"
class="w-full text-left px-3 py-2 rounded-lg text-xs transition-all"
:class="c.id === activeConversationId
? 'nav-tab-active'
: isDark
? 'text-white/60 hover:text-white hover:bg-white/10'
: 'text-gray-500 hover:text-gray-900 hover:bg-black/5'"
@click="selectChat(c.id)"
>
{{ c.title || 'Untitled' }}
</button>
</div>
</div>
</Transition>
</div>
</div>
<div class="flex items-center gap-1">
<button
class="p-2 rounded-lg transition-colors"
:class="isDark
? 'text-white/70 hover:text-white hover:bg-white/10'
: 'text-gray-500 hover:text-gray-900 hover:bg-black/5'"
:title="isDark ? 'Light mode' : 'Dark mode'"
aria-label="Toggle theme"
@click="toggleTheme"
>
<svg v-if="isDark" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z" />
</svg>
<svg v-else class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z" />
</svg>
</button>
<button
class="p-2 rounded-lg transition-colors"
:class="isDark
@@ -74,7 +128,7 @@
<Transition name="picker">
<div
v-if="showModelPicker"
class="absolute left-0 right-0 top-full z-20 mx-3 mt-1 glass-card p-3 space-y-3 animate-fade-up-fast"
class="absolute left-0 right-0 top-full z-50 mx-3 mt-1 glass-card p-3 space-y-3 animate-fade-up-fast shadow-2xl"
>
<div v-for="provider in availableProviders" :key="provider.id">
<p class="text-[10px] font-semibold uppercase tracking-wider mb-1.5 px-1"
@@ -103,7 +157,8 @@
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import { ref, computed, watch } from 'vue'
import { useChatStore } from '@/stores/chat'
import { useAI } from '@/composables/useAI'
import { useTheme } from '@/composables/useTheme'
@@ -121,8 +176,22 @@ defineEmits<{
}>()
const { activeProvider, activeModel, availableProviders, setProvider, setModel } = useAI()
const { isDark } = useTheme()
const { isDark, toggleTheme } = useTheme()
const chatStore = useChatStore()
const showModelPicker = ref(false)
const showChatList = ref(false)
const conversationList = computed(() => chatStore.conversationList)
const activeConversationId = computed(() => chatStore.activeConversationId)
function selectChat(id: string) {
chatStore.setActiveConversation(id)
showChatList.value = false
}
watch(() => chatStore.conversationList.length, () => {
showChatList.value = false
})
const modelDisplayName = computed(() => {
for (const p of availableProviders.value) {
@@ -12,7 +12,7 @@
<p class="text-sm leading-relaxed whitespace-pre-wrap break-words"
:class="isDark ? 'text-white/90' : 'text-gray-800'">{{ displayText }}</p>
<div v-if="inlineFilms.length > 0" class="mt-3 space-y-1">
<div v-if="inlineFilms.length > 0" class="mt-3 space-y-1" @click.stop>
<FilmCard
v-for="film in inlineFilms"
:key="film.id"
@@ -21,16 +21,32 @@
/>
</div>
<div v-if="inlineSongs.length > 0" class="mt-3 space-y-1" @click.stop>
<SongCard
v-for="song in inlineSongs"
:key="song.id"
:song="song"
@select="handleSongSelect"
/>
</div>
<div class="flex items-center gap-2 mt-1.5">
<span class="text-[10px] select-none"
:class="isDark ? 'text-white/30' : 'text-gray-400'">{{ formattedTime }}</span>
<button
v-if="inlineFilms.length > 1"
class="text-[10px] text-accent/70 hover:text-accent transition-colors"
@click="openPanel"
@click.stop="openPanel"
>
View all {{ inlineFilms.length }} films
</button>
<button
v-else-if="inlineSongs.length > 1"
class="text-[10px] text-accent/70 hover:text-accent transition-colors"
@click.stop="openPanel"
>
View all {{ inlineSongs.length }} songs
</button>
</div>
</div>
</div>
@@ -39,10 +55,11 @@
<script setup lang="ts">
import { computed } from 'vue'
import type { Message } from '@aiui/core/types/message'
import type { Film } from '@aiui/core/types/content'
import type { Film, Song } from '@aiui/core/types/content'
import { useTheme } from '@/composables/useTheme'
import { useContentPanel } from '@/composables/useContentPanel'
import FilmCard from '@/components/content/FilmCard.vue'
import SongCard from '@/components/content/SongCard.vue'
const props = defineProps<{
message: Message
@@ -50,7 +67,7 @@ const props = defineProps<{
}>()
const { isDark } = useTheme()
const { extractFilmIds, resolveFilms, stripFilmTags, updatePanelFromText, openFilmDetail } = useContentPanel()
const { extractAllFilms, extractAllSongs, stripContentTags, updatePanelFromText, openFilmDetail, openSongDetail, closeFilmDetail, closeSongDetail } = useContentPanel()
const isUser = computed(() => props.message.role === 'user')
@@ -62,15 +79,19 @@ const bubbleClasses = computed(() =>
const inlineFilms = computed(() => {
if (isUser.value) return []
const ids = extractFilmIds(props.message.content)
return resolveFilms(ids)
return extractAllFilms(props.message.content)
})
const hasContext = computed(() => !isUser.value && inlineFilms.value.length > 0)
const inlineSongs = computed(() => {
if (isUser.value) return []
return extractAllSongs(props.message.content)
})
const hasContext = computed(() => !isUser.value && (inlineFilms.value.length > 0 || inlineSongs.value.length > 0))
const displayText = computed(() => {
if (isUser.value) return props.message.content
return stripFilmTags(props.message.content)
return stripContentTags(props.message.content)
})
const formattedTime = computed(() => {
@@ -80,10 +101,19 @@ const formattedTime = computed(() => {
function handleFilmSelect(film: Film) {
updatePanelFromText(props.message.content)
closeSongDetail()
openFilmDetail(film)
}
function handleSongSelect(song: Song) {
updatePanelFromText(props.message.content)
closeFilmDetail()
openSongDetail(song)
}
function openPanel() {
closeFilmDetail()
closeSongDetail()
updatePanelFromText(props.message.content)
}
@@ -1,5 +1,5 @@
<template>
<div class="flex flex-col h-full rounded-2xl overflow-hidden transition-all duration-300">
<div class="flex flex-col h-full rounded-2xl overflow-visible transition-all duration-300">
<ChatHeader
:title="title"
:conversation-id="displayId"
@@ -17,7 +17,7 @@
<div v-if="messages.length === 0" class="flex items-center justify-center h-full">
<div class="text-center space-y-3 animate-fade-up">
<div class="w-16 h-16 rounded-2xl glass flex items-center justify-center mx-auto">
<span class="text-2xl"></span>
<span class="text-2xl" :class="isDark ? 'text-[#fafafa]' : 'text-gray-800'"></span>
</div>
<p class="text-sm" :class="isDark ? 'text-white/30' : 'text-gray-400'">
Start a conversation
@@ -120,7 +120,7 @@ watch(
const el = messageListRef.value
if (el) el.scrollTop = el.scrollHeight
})
if (content && !isStreaming.value) {
if (content) {
updatePanelFromText(content)
}
}
@@ -0,0 +1,119 @@
<template>
<div class="relative flex-1 flex flex-col min-h-0 overflow-hidden">
<div
v-if="contextType === 'film' || contextType === 'song'"
class="flex-1 flex flex-col min-h-0"
>
<div
class="p-4 shrink-0 flex items-center justify-between"
:style="isDark
? 'border-bottom: 1px solid rgba(255, 255, 255, 0.08)'
: 'border-bottom: 1px solid rgba(0, 0, 0, 0.06)'"
>
<p class="text-sm font-medium"
:class="isDark ? 'text-white/70' : 'text-gray-600'">
{{ contextLabel }}
</p>
<p class="text-[10px] font-mono uppercase tracking-[0.2em]"
:class="isDark ? 'text-white/25' : 'text-gray-400'">
Surfacing
</p>
</div>
<LoadingFilmGrid :count="12" />
</div>
<div
v-else
class="relative flex-1 flex items-center justify-center min-h-0"
>
<div
class="absolute inset-0 opacity-[0.04] pointer-events-none"
:class="isDark ? 'bg-white' : 'bg-black'"
style="background-image: url(&quot;data:image/svg+xml,%3Csvg viewBox='0 0 256 256' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='4'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E&quot;)"
/>
<div class="relative flex flex-col items-center gap-8">
<div class="flex items-center gap-2">
<div
v-for="(_, i) in 5"
:key="i"
class="w-12 h-16 rounded-lg overflow-hidden relative animate-cell-pulse"
:class="isDark
? 'bg-white/8 border border-white/15 shadow-xl shadow-accent/5'
: 'bg-black/6 border border-black/8 shadow-xl shadow-accent/10'"
:style="{ animationDelay: `${i * 100}ms` }"
>
<div class="absolute inset-0 pointer-events-none overflow-hidden">
<div
class="absolute inset-0 w-1/2 animate-shimmer-sweep"
:class="isDark
? 'bg-gradient-to-r from-transparent via-accent/25 to-transparent'
: 'bg-gradient-to-r from-transparent via-accent/35 to-transparent'"
/>
</div>
</div>
</div>
<p class="text-sm font-medium"
:class="isDark ? 'text-white/70' : 'text-gray-600'">
{{ contextLabel }}
</p>
<div class="w-40 h-px rounded-full overflow-hidden"
:class="isDark ? 'bg-white/8' : 'bg-black/8'">
<div class="h-full bg-accent/90 rounded-full animate-progress-sweep" />
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useTheme } from '@/composables/useTheme'
import LoadingFilmGrid from './LoadingFilmGrid.vue'
const props = withDefaults(
defineProps<{
contextType?: 'film' | 'song' | 'generic'
}>(),
{ contextType: 'film' }
)
const { isDark } = useTheme()
const contextLabel = computed(() => {
if (props.contextType === 'film') return 'Film recommendations'
if (props.contextType === 'song') return 'Song recommendations'
return 'Content'
})
</script>
<style scoped>
.animate-cell-pulse {
animation: cell-pulse 1.8s cubic-bezier(0.4, 0, 0.2, 1) infinite;
}
.animate-shimmer-sweep {
animation: shimmer-sweep 2.2s cubic-bezier(0.4, 0, 0.2, 1) infinite;
}
.animate-progress-sweep {
animation: progress-sweep 1.6s cubic-bezier(0.4, 0, 0.2, 1) infinite;
}
@keyframes cell-pulse {
0%, 100% { opacity: 0.6; transform: scale(0.96); }
50% { opacity: 1; transform: scale(1.02); }
}
@keyframes shimmer-sweep {
0% { transform: translateX(-100%); }
60% { transform: translateX(200%); }
100% { transform: translateX(200%); }
}
@keyframes progress-sweep {
0% { width: 0; margin-left: 0; }
45% { width: 60%; margin-left: 20%; }
90% { width: 0; margin-left: 100%; }
100% { width: 0; margin-left: 0; }
}
</style>
@@ -1,25 +1,25 @@
<template>
<button
class="flex gap-3 p-2 rounded-xl transition-all duration-200 text-left w-full group"
class="flex gap-3 p-2 rounded-xl transition-all duration-200 text-left w-full group overflow-hidden"
:class="isDark
? 'hover:bg-white/5 active:bg-white/10'
: 'hover:bg-black/3 active:bg-black/5'"
: 'hover:bg-black/[0.03] active:bg-black/5'"
@click="$emit('select', film)"
>
<img
v-if="film.posterUrl"
:src="film.posterUrl"
:alt="film.title"
class="w-12 h-[72px] rounded-lg object-cover shrink-0 shadow-md"
loading="lazy"
@error="(e) => handleImgError(e, film.title, film.year)"
/>
<div
v-else
class="w-12 h-[72px] rounded-lg shrink-0 flex items-center justify-center text-lg"
:class="isDark ? 'bg-white/10' : 'bg-black/5'"
>
🎬
<div class="poster-card-sm shrink-0 w-12 aspect-[2/3] rounded-lg overflow-hidden">
<img
v-if="film.posterUrl"
:src="film.posterUrl"
:alt="film.title"
class="w-full h-full object-cover rounded-[6px] transition-transform duration-300 group-hover:scale-105"
loading="lazy"
@error="(e) => handleImgError(e, film.title, film.year)"
/>
<div
v-else
class="w-full h-full rounded-[6px]"
:class="isDark ? 'bg-white/10' : 'bg-black/5'"
/>
</div>
<div class="min-w-0 flex-1 py-0.5">
@@ -27,13 +27,19 @@
:class="isDark ? 'text-white/90' : 'text-gray-900'">{{ film.title }}</p>
<p class="text-[11px] mt-0.5"
:class="isDark ? 'text-white/40' : 'text-gray-500'">
{{ film.year }} · {{ film.director }}
{{ film.year }}<template v-if="film.director"> · {{ film.director }}</template>
</p>
<div class="flex items-center gap-1.5 mt-1.5">
<span class="text-[10px] font-semibold px-1.5 py-0.5 rounded"
<span v-if="film.rating > 0"
class="text-[10px] font-semibold px-1.5 py-0.5 rounded"
:class="ratingClass">
{{ film.rating }}
</span>
<span v-if="isExternal"
class="text-[9px] px-1.5 py-0.5 rounded font-medium"
:class="isDark ? 'bg-info/15 text-info/70' : 'bg-info/10 text-blue-600'">
not in library
</span>
<span
v-for="src in film.sources.slice(0, 3)"
:key="src.type"
@@ -58,6 +64,8 @@ defineEmits<{ select: [film: Film] }>()
const { isDark } = useTheme()
const isExternal = computed(() => props.film.id.startsWith('ext-'))
const ratingClass = computed(() => {
const r = props.film.rating
if (r >= 8.5) return isDark.value ? 'bg-success/20 text-success' : 'bg-success/10 text-green-700'
@@ -1,18 +1,22 @@
<template>
<div class="h-full overflow-y-auto custom-scrollbar">
<div class="relative">
<div class="film-detail h-full overflow-y-auto overflow-x-hidden scrollbar-hide">
<div class="relative w-full overflow-hidden">
<img
v-if="film.backdropUrl"
:src="film.backdropUrl"
v-if="bannerSrc"
:src="bannerSrc"
:alt="film.title"
class="w-full aspect-video object-cover"
@error="(e) => handleImgError(e, film.title, film.year)"
class="w-full aspect-[16/7] object-cover block"
@error="onBannerError"
/>
<div class="absolute inset-0 bg-gradient-to-t from-black/90 via-black/40 to-transparent" />
<div
v-else
class="w-full aspect-[16/7]"
:style="{ background: fallbackGradient }"
/>
<div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent pointer-events-none" />
<button
class="absolute top-3 left-3 p-2 rounded-lg backdrop-blur-md transition-colors"
:class="'bg-black/30 text-white/80 hover:bg-black/50'"
class="absolute top-3 left-3 p-2 rounded-lg backdrop-blur-md transition-colors bg-black/30 text-white/80 hover:bg-black/50"
@click="$emit('back')"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
@@ -92,15 +96,53 @@
</template>
<script setup lang="ts">
import { ref, computed } from 'vue'
import type { Film } from '@aiui/core/types/content'
import { useTheme } from '@/composables/useTheme'
import { handleImgError } from '@/composables/useImageFallback'
import { fetchTmdbPoster } from '@/composables/useImageFallback'
defineProps<{ film: Film }>()
const props = defineProps<{ film: Film }>()
defineEmits<{ back: [] }>()
const { isDark } = useTheme()
// Fallback order: backdrop (mock) → TMDB API → poster (mock) → gradient
const bannerTry = ref<'backdrop' | 'tmdb' | 'poster' | 'done'>('backdrop')
const tmdbBannerUrl = ref<string | null>(null)
const bannerSrc = computed(() => {
if (bannerTry.value === 'done') return null
if (bannerTry.value === 'backdrop' && props.film.backdropUrl) return props.film.backdropUrl
if (bannerTry.value === 'tmdb' && tmdbBannerUrl.value) return tmdbBannerUrl.value
if (bannerTry.value === 'poster' && props.film.posterUrl) return props.film.posterUrl
if (bannerTry.value === 'backdrop' && !props.film.backdropUrl) return props.film.posterUrl || null
return null
})
const fallbackGradient = computed(() => {
const hue = [...props.film.title].reduce((acc, c) => acc + c.charCodeAt(0), 0) % 360
return `linear-gradient(135deg, hsl(${hue}, 25%, 12%) 0%, hsl(${(hue + 40) % 360}, 20%, 8%) 100%)`
})
async function onBannerError() {
if (bannerTry.value === 'backdrop') {
const { backdropUrl, posterUrl } = await fetchTmdbPoster(props.film.title, props.film.year)
const url = backdropUrl ?? posterUrl
if (url) {
tmdbBannerUrl.value = url
bannerTry.value = 'tmdb'
return
}
bannerTry.value = props.film.posterUrl ? 'poster' : 'done'
return
}
if (bannerTry.value === 'tmdb') {
bannerTry.value = props.film.posterUrl ? 'poster' : 'done'
return
}
bannerTry.value = 'done'
}
function sourceIcon(type: string): string {
const icons: Record<string, string> = {
plex: '🟧',
@@ -41,44 +41,49 @@
</div>
<div class="flex-1 overflow-y-auto custom-scrollbar p-3">
<div class="grid grid-cols-2 sm:grid-cols-3 gap-3">
<div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
<button
v-for="film in filteredFilms"
:key="film.id"
class="group rounded-xl overflow-hidden transition-all duration-200"
:class="isDark ? 'hover:ring-1 hover:ring-white/20' : 'hover:ring-1 hover:ring-black/10'"
class="group flex flex-col items-stretch text-left w-full"
@click="$emit('selectFilm', film)"
>
<div class="aspect-[2/3] relative">
<img
:src="film.posterUrl"
:alt="film.title"
class="w-full h-full object-cover"
loading="lazy"
@error="(e) => handleImgError(e, film.title, film.year)"
/>
<div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent" />
<div class="poster-card flex-1 min-h-0">
<div class="aspect-[2/3] relative w-full overflow-hidden rounded-[10px]">
<img
:src="film.posterUrl"
:alt="film.title"
class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
loading="lazy"
@error="(e) => handleImgError(e, film.title, film.year)"
/>
<div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent pointer-events-none" />
<div class="absolute bottom-0 left-0 right-0 p-2">
<p class="text-[11px] font-semibold text-white/90 leading-tight truncate">
{{ film.title }}
</p>
<div class="flex items-center gap-1 mt-0.5">
<span class="text-[9px] text-accent font-bold"> {{ film.rating }}</span>
<span class="text-[9px] text-white/40">{{ film.year }}</span>
<div class="absolute bottom-0 left-0 right-0 p-2">
<p class="text-[11px] font-semibold text-white/90 leading-tight truncate">
{{ film.title }}
</p>
<div class="flex items-center gap-1 mt-0.5">
<span class="text-[9px] text-accent font-bold"> {{ film.rating }}</span>
<span class="text-[9px] text-white/40">{{ film.year }}</span>
</div>
</div>
<div class="absolute top-1.5 right-1.5 flex gap-0.5">
<span
v-for="src in film.sources.slice(0, 2)"
:key="src.type"
class="text-[8px] px-1 py-0.5 rounded bg-black/60 text-white/70 backdrop-blur-sm"
>
{{ src.type }}
</span>
</div>
</div>
<div class="absolute top-1.5 right-1.5 flex gap-0.5">
<span
v-for="src in film.sources.slice(0, 2)"
:key="src.type"
class="text-[8px] px-1 py-0.5 rounded bg-black/60 text-white/70 backdrop-blur-sm"
>
{{ src.type }}
</span>
</div>
</div>
<p class="text-xs font-semibold mt-2 truncate px-0.5"
:class="isDark ? 'text-white/90' : 'text-gray-900'">
{{ film.title }}
</p>
</button>
</div>
@@ -0,0 +1,68 @@
<template>
<div class="flex w-full animate-pulse flex-col space-y-3">
<div
class="aspect-[2/3] rounded-xl overflow-hidden relative"
:class="isDark ? 'text-white/20' : 'text-gray-400'"
>
<svg
viewBox="0 0 200 300"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="w-full h-full object-cover"
>
<defs>
<clipPath :id="clipId">
<rect width="200" height="300" rx="12" fill="white"/>
</clipPath>
</defs>
<g :clip-path="`url(#${clipId})`">
<rect width="200" height="300" fill="currentColor" fill-opacity="0.4"/>
<g fill="currentColor" fill-opacity="0.5">
<rect x="12" y="16" width="24" height="36" rx="3"/>
<rect x="52" y="16" width="24" height="36" rx="3"/>
<rect x="92" y="16" width="24" height="36" rx="3"/>
<rect x="132" y="16" width="24" height="36" rx="3"/>
<rect x="12" y="64" width="24" height="36" rx="3"/>
<rect x="52" y="64" width="24" height="36" rx="3"/>
<rect x="92" y="64" width="24" height="36" rx="3"/>
<rect x="132" y="64" width="24" height="36" rx="3"/>
</g>
</g>
</svg>
</div>
<div v-if="hasText" class="space-y-2">
<div
class="h-5 w-24 rounded-full"
:class="isDark ? 'bg-white/20' : 'bg-gray-300'"
/>
<div class="flex items-center gap-2">
<div
class="h-4 w-16 rounded-full"
:class="isDark ? 'bg-white/15' : 'bg-gray-200'"
/>
<div
class="size-1.5 rounded-full shrink-0"
:class="isDark ? 'bg-white/15' : 'bg-gray-300'"
/>
<div
class="h-4 w-14 rounded-full"
:class="isDark ? 'bg-white/15' : 'bg-gray-200'"
/>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { useTheme } from '@/composables/useTheme'
withDefaults(
defineProps<{
hasText?: boolean
}>(),
{ hasText: true }
)
const { isDark } = useTheme()
const clipId = `loading-poster-${Math.random().toString(36).slice(2, 10)}`
</script>
@@ -0,0 +1,23 @@
<template>
<div class="flex-1 overflow-y-auto p-4">
<div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 gap-4">
<LoadingFilmCard
v-for="i in count"
:key="i"
:has-text="hasText"
/>
</div>
</div>
</template>
<script setup lang="ts">
import LoadingFilmCard from './LoadingFilmCard.vue'
withDefaults(
defineProps<{
count?: number
hasText?: boolean
}>(),
{ count: 12, hasText: true }
)
</script>
@@ -0,0 +1,81 @@
<template>
<button
class="flex gap-3 p-2 rounded-xl transition-all duration-200 text-left w-full group overflow-hidden"
:class="isDark
? 'hover:bg-white/5 active:bg-white/10'
: 'hover:bg-black/[0.03] active:bg-black/5'"
@click="$emit('select', song)"
>
<div class="cover-card-sm shrink-0 w-12 h-12 rounded-lg overflow-hidden">
<img
v-if="coverSrc"
:src="coverSrc"
:alt="song.title"
class="w-full h-full object-cover rounded-[6px] transition-transform duration-300 group-hover:scale-105"
loading="lazy"
@error="coverFailed = true"
/>
<div
v-else
class="w-full h-full rounded-[6px] bg-cover bg-center"
:style="{ backgroundImage: `url(${fallbackCover})` }"
/>
</div>
<div class="min-w-0 flex-1 py-0.5">
<p class="text-sm font-semibold truncate"
:class="isDark ? 'text-white/90' : 'text-gray-900'">{{ song.title }}</p>
<p class="text-[11px] mt-0.5"
:class="isDark ? 'text-white/40' : 'text-gray-500'">
{{ song.artist }}<template v-if="song.year"> · {{ song.year }}</template>
</p>
<div class="flex items-center gap-1.5 mt-1.5">
<span v-if="isExternal"
class="text-[9px] px-1.5 py-0.5 rounded font-medium"
:class="isDark ? 'bg-info/15 text-info/70' : 'bg-info/10 text-blue-600'">
not in library
</span>
<span
v-for="src in (song.sources ?? []).slice(0, 3)"
:key="src.type"
class="text-[9px] px-1.5 py-0.5 rounded font-medium"
:class="isDark ? 'bg-white/8 text-white/50' : 'bg-black/5 text-gray-500'"
>
{{ src.type }}
</span>
</div>
</div>
</button>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { Song } from '@aiui/core/types/content'
import { useTheme } from '@/composables/useTheme'
import { generateSongCoverFallback, fetchMusicCover } from '@/composables/useImageFallback'
const props = defineProps<{ song: Song }>()
defineEmits<{ select: [song: Song] }>()
const { isDark } = useTheme()
const coverFailed = ref(false)
const fetchedCover = ref<string | null>(null)
const coverSrc = computed(() => {
if (coverFailed.value) return null
return props.song.coverUrl || fetchedCover.value
})
const fallbackCover = computed(() =>
generateSongCoverFallback(props.song.title, props.song.artist)
)
const isExternal = computed(() => props.song.id.startsWith('ext-'))
onMounted(() => {
if (props.song.coverUrl) return
fetchMusicCover(props.song.title, props.song.artist, props.song.album).then((url) => {
if (url) fetchedCover.value = url
})
})
</script>
@@ -0,0 +1,156 @@
<template>
<div class="song-detail h-full overflow-y-auto overflow-x-hidden scrollbar-hide">
<div class="relative w-full overflow-hidden">
<div class="w-full aspect-[16/7] flex items-center justify-center overflow-hidden bg-black/20">
<img
v-if="coverSrc"
:src="coverSrc"
:alt="song.title"
class="w-full h-full object-cover object-center block"
@error="coverFailed = true"
/>
<div
v-else
class="w-full h-full bg-cover bg-center"
:style="{ backgroundImage: `url(${fallbackCover})` }"
/>
</div>
<div class="absolute inset-0 bg-gradient-to-t from-black/80 via-black/30 to-transparent pointer-events-none" />
<button
class="absolute top-3 left-3 p-2 rounded-lg backdrop-blur-md transition-colors bg-black/30 text-white/80 hover:bg-black/50"
@click="$emit('back')"
>
<svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
</svg>
</button>
<div class="absolute bottom-0 left-0 right-0 p-4">
<h2 class="text-lg font-bold text-white">{{ song.title }}</h2>
<div class="flex items-center gap-2 mt-1 text-xs text-white/60">
<span>{{ song.artist }}</span>
<span v-if="song.album">{{ song.album }}</span>
<span v-if="song.year">{{ song.year }}</span>
<span v-if="song.duration">{{ formatDuration(song.duration) }}</span>
</div>
</div>
</div>
<div class="p-4 space-y-4">
<div v-if="song.genres?.length" class="flex flex-wrap gap-1.5">
<span
v-for="genre in song.genres"
:key="genre"
class="text-[10px] px-2 py-1 rounded-md font-medium"
:class="isDark ? 'bg-white/10 text-white/60' : 'bg-black/5 text-gray-600'"
>
{{ genre }}
</span>
</div>
<div>
<h4 class="text-xs font-semibold mb-2"
:class="isDark ? 'text-white/50' : 'text-gray-500'">Listen on</h4>
<div class="space-y-2">
<a
v-if="youtubeSearchUrl"
:href="youtubeSearchUrl"
target="_blank"
rel="noopener"
class="flex items-center justify-between p-3 rounded-xl transition-colors"
:class="isDark
? 'bg-white/5 hover:bg-white/10'
: 'bg-black/3 hover:bg-black/5'"
>
<div class="flex items-center gap-2.5">
<span class="text-sm"></span>
<div>
<p class="text-xs font-medium"
:class="isDark ? 'text-white/80' : 'text-gray-800'">YouTube (free)</p>
<p class="text-[10px]"
:class="isDark ? 'text-white/30' : 'text-gray-400'">Search for this song</p>
</div>
</div>
<svg class="w-4 h-4" :class="isDark ? 'text-white/30' : 'text-gray-400'"
fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
<a
v-for="src in song.sources ?? []"
:key="src.url"
:href="src.url"
target="_blank"
rel="noopener"
class="flex items-center justify-between p-3 rounded-xl transition-colors"
:class="isDark
? 'bg-white/5 hover:bg-white/10'
: 'bg-black/3 hover:bg-black/5'"
>
<div class="flex items-center gap-2.5">
<span class="text-sm">{{ sourceIcon(src.type) }}</span>
<p class="text-xs font-medium"
:class="isDark ? 'text-white/80' : 'text-gray-800'">{{ src.name }}</p>
</div>
<svg class="w-4 h-4" :class="isDark ? 'text-white/30' : 'text-gray-400'"
fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
</svg>
</a>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import type { Song } from '@aiui/core/types/content'
import { useTheme } from '@/composables/useTheme'
import { generateSongCoverFallback, fetchMusicCover } from '@/composables/useImageFallback'
const props = defineProps<{ song: Song }>()
defineEmits<{ back: [] }>()
const { isDark } = useTheme()
const coverFailed = ref(false)
const fetchedCover = ref<string | null>(null)
const coverSrc = computed(() => {
if (coverFailed.value) return null
return props.song.coverUrl || fetchedCover.value
})
const fallbackCover = computed(() =>
generateSongCoverFallback(props.song.title, props.song.artist)
)
const youtubeSearchUrl = computed(() => {
const q = `${props.song.title} ${props.song.artist}`.trim()
return q ? `https://www.youtube.com/results?search_query=${encodeURIComponent(q)}` : null
})
function formatDuration(sec: number): string {
const m = Math.floor(sec / 60)
const s = sec % 60
return `${m}:${s.toString().padStart(2, '0')}`
}
function sourceIcon(type: string): string {
const icons: Record<string, string> = {
spotify: '🟢',
youtube: '▶️',
'apple-music': '🍎',
bandcamp: '📦',
}
return icons[type] ?? '🎵'
}
onMounted(() => {
if (props.song.coverUrl) return
fetchMusicCover(props.song.title, props.song.artist, props.song.album).then((url) => {
if (url) fetchedCover.value = url
})
})
</script>
@@ -0,0 +1,179 @@
<template>
<div class="h-full flex flex-col">
<div class="p-4 space-y-3" :style="isDark
? 'border-bottom: 1px solid rgba(255, 255, 255, 0.08)'
: 'border-bottom: 1px solid rgba(0, 0, 0, 0.06)'"
>
<div class="flex items-center justify-between">
<h3 class="text-sm font-bold" :class="isDark ? 'text-white/90' : 'text-gray-900'">
{{ title }}
</h3>
<span class="text-[10px] font-mono" :class="isDark ? 'text-white/30' : 'text-gray-400'">
{{ filteredSongs.length }} songs
</span>
</div>
<input
v-model="search"
type="text"
placeholder="Search songs..."
class="w-full px-3 py-2 rounded-lg text-xs outline-none transition-colors"
:class="isDark
? 'bg-white/5 text-white/80 placeholder:text-white/25 focus:bg-white/10'
: 'bg-black/3 text-gray-800 placeholder:text-gray-400 focus:bg-black/5'"
/>
<div class="flex flex-wrap gap-1.5">
<button
v-for="genre in topGenres"
:key="genre"
class="text-[10px] px-2 py-1 rounded-md transition-all duration-150"
:class="activeGenre === genre
? 'nav-tab-active'
: isDark
? 'text-white/40 hover:text-white/70 hover:bg-white/5'
: 'text-gray-500 hover:text-gray-800 hover:bg-black/5'"
@click="activeGenre = activeGenre === genre ? null : genre"
>
{{ genre }}
</button>
</div>
</div>
<div class="flex-1 overflow-y-auto custom-scrollbar p-3">
<div class="grid grid-cols-2 sm:grid-cols-3 gap-4">
<button
v-for="song in filteredSongs"
:key="song.id"
class="group flex flex-col items-stretch text-left w-full"
@click="$emit('selectSong', song)"
>
<div class="cover-card flex-1 min-h-0">
<div class="aspect-square relative w-full overflow-hidden rounded-[10px]">
<img
v-if="coverSrc(song)"
:src="coverSrc(song)!"
:alt="song.title"
class="w-full h-full object-cover transition-transform duration-300 group-hover:scale-110"
loading="lazy"
@error="onCoverError(song)"
/>
<div
v-else
class="w-full h-full bg-cover bg-center"
:style="{ backgroundImage: `url(${fallbackFor(song)})` }"
/>
<div class="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent pointer-events-none" />
<div class="absolute bottom-0 left-0 right-0 p-2">
<p class="text-[11px] font-semibold text-white/90 leading-tight truncate">
{{ song.title }}
</p>
<p class="text-[9px] text-white/40 truncate mt-0.5">{{ song.artist }}</p>
</div>
<div class="absolute top-1.5 right-1.5 flex gap-0.5 flex-wrap justify-end max-w-[60%]">
<span
v-for="src in (song.sources ?? []).slice(0, 2)"
:key="src.type"
class="text-[8px] px-1 py-0.5 rounded bg-black/60 text-white/70 backdrop-blur-sm"
>
{{ src.type }}
</span>
</div>
</div>
</div>
<p class="text-xs font-semibold mt-2 truncate px-0.5"
:class="isDark ? 'text-white/90' : 'text-gray-900'">
{{ song.title }}
</p>
</button>
</div>
<div v-if="filteredSongs.length === 0" class="flex items-center justify-center py-12">
<p class="text-sm" :class="isDark ? 'text-white/30' : 'text-gray-400'">
No songs match your search
</p>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { ref, computed, reactive, onMounted, watch } from 'vue'
import type { Song } from '@aiui/core/types/content'
import { useTheme } from '@/composables/useTheme'
import { generateSongCoverFallback, fetchMusicCover } from '@/composables/useImageFallback'
const props = withDefaults(defineProps<{
songs: Song[]
title?: string
}>(), {
title: 'Recommended Songs',
})
defineEmits<{ selectSong: [song: Song] }>()
const { isDark } = useTheme()
const search = ref('')
const activeGenre = ref<string | null>(null)
const failedCovers = ref<Set<string>>(new Set())
const fetchedCovers = reactive<Map<string, string>>(new Map())
function coverSrc(song: Song): string | null {
if (failedCovers.value.has(song.id)) return null
const url = song.coverUrl || fetchedCovers.get(song.id)
return url || null
}
function fallbackFor(song: Song): string {
return generateSongCoverFallback(song.title, song.artist)
}
function onCoverError(song: Song) {
failedCovers.value.add(song.id)
failedCovers.value = new Set(failedCovers.value)
}
function fetchCoversFor(songs: Song[]) {
for (const song of songs) {
if (song.coverUrl || fetchedCovers.has(song.id)) continue
fetchMusicCover(song.title, song.artist, song.album).then((url) => {
if (url) fetchedCovers.set(song.id, url)
})
}
}
onMounted(() => fetchCoversFor(props.songs))
watch(() => props.songs, (songs) => fetchCoversFor(songs), { immediate: false })
const topGenres = computed(() => {
const counts = new Map<string, number>()
for (const s of props.songs) {
for (const g of s.genres ?? []) {
counts.set(g, (counts.get(g) ?? 0) + 1)
}
}
return [...counts.entries()]
.sort((a, b) => b[1] - a[1])
.slice(0, 8)
.map(([g]) => g)
})
const filteredSongs = computed(() => {
let result = props.songs
if (search.value) {
const q = search.value.toLowerCase()
result = result.filter(
(s) =>
s.title.toLowerCase().includes(q) ||
s.artist.toLowerCase().includes(q) ||
(s.album ?? '').toLowerCase().includes(q)
)
}
if (activeGenre.value) {
result = result.filter((s) => (s.genres ?? []).includes(activeGenre.value!))
}
return result
})
</script>
+13 -3
View File
@@ -7,19 +7,29 @@ const CLAUDE_PATH = '/api/claude/v1/messages'
const OPENROUTER_PATH = '/api/openrouter/api/v1/chat/completions'
import { mockFilms } from '@/mocks/films'
import { mockSongs } from '@/mocks/songs'
const filmContext = mockFilms.map((f) =>
`- [${f.id}] "${f.title}" (${f.year}) dir. ${f.director} | ${f.genres.join(', ')} | ${f.rating}/10 | On: ${f.sources.map(s => s.type).join(', ')}`
).join('\n')
const SYSTEM_PROMPT = `You are AIUI, a helpful AI assistant with access to the user's media library.
const songContext = mockSongs.map((s) =>
`- [${s.id}] "${s.title}" by ${s.artist}${s.album ? ` (${s.album})` : ''}${s.year ? ` (${s.year})` : ''} | ${(s.genres ?? []).join(', ')} | On: ${(s.sources ?? []).map(x => x.type).join(', ')}`
).join('\n')
When recommending or discussing films, reference films from the user's library using the tag format [[film:ID]] where ID is the film's id from their collection. Always include these tags so the UI can render rich film cards. You may recommend multiple films. Write a brief reason why each film is worth watching alongside its tag.
const SYSTEM_PROMPT = `You are AIUI, a helpful AI assistant with access to the user's media library (films and songs).
**Films:** When recommending or discussing films from the user's library, use [[film:ID]] where ID is the film's id. For films NOT in the library, use [[film_ext:Title|Year|Director]], e.g. [[film_ext:Brokeback Mountain|2005|Ang Lee]].
**Songs:** When recommending or discussing songs from the user's library, use [[song:ID]] where ID is the song's id. For songs NOT in the library, use [[song_ext:Title|Artist|Year]] (year optional), e.g. [[song_ext:Never Meant|American Football|1999]].
Always include these tags so the UI can render rich cards. You may recommend multiple items. Write a brief reason why each is worth checking out.
The user's film library:
${filmContext}
If a user asks about a film NOT in their library, discuss it normally but note it's not in their collection.`
The user's song library:
${songContext}`
const openrouterApiKey = import.meta.env.VITE_OPENROUTER_API_KEY ?? ''
const hasOpenRouter = !!openrouterApiKey
+188 -13
View File
@@ -1,13 +1,21 @@
import { ref, computed } from 'vue'
import type { Film } from '@aiui/core/types/content'
import { ref } from 'vue'
import type { Film, Song } from '@aiui/core/types/content'
import { mockFilms } from '@/mocks/films'
import { mockSongs } from '@/mocks/songs'
import { generatePosterFallback } from '@/composables/useImageFallback'
const panelOpen = ref(false)
const panelFilms = ref<Film[]>([])
const panelSongs = ref<Song[]>([])
const selectedFilm = ref<Film | null>(null)
const selectedSong = ref<Song | null>(null)
const panelTitle = ref('Recommended Films')
const contentType = ref<'film' | 'song'>('film')
const FILM_TAG_RE = /\[\[film:(f?\d+)\]\]/gi
const FILM_EXT_RE = /\[\[film_ext:([^|]+)\|(\d{4})\|([^\]]+)\]\]/gi
const SONG_TAG_RE = /\[\[song:(s?\d+)\]\]/gi
const SONG_EXT_RE = /\[\[song_ext:([^|]+)\|([^|]+)(?:\|(\d{4}))?\]\]/gi
export function useContentPanel() {
function normalizeFilmId(raw: string): string {
@@ -31,56 +39,223 @@ export function useContentPanel() {
.filter((f): f is Film => !!f)
}
function updatePanelFromText(text: string) {
const ids = extractFilmIds(text)
if (ids.length > 0) {
const films = resolveFilms(ids)
if (films.length > 0) {
panelFilms.value = films
panelOpen.value = true
panelTitle.value = films.length === 1
? films[0].title
: `${films.length} Recommended Films`
function extractExternalFilms(text: string): Film[] {
const films: Film[] = []
const seen = new Set<string>()
let match: RegExpExecArray | null
const re = new RegExp(FILM_EXT_RE.source, 'gi')
while ((match = re.exec(text)) !== null) {
const title = match[1].trim()
const year = parseInt(match[2], 10)
const director = match[3].trim()
const key = `${title.toLowerCase()}|${year}`
if (seen.has(key)) continue
seen.add(key)
films.push({
id: `ext-${key.replace(/\W/g, '-')}`,
title,
year,
posterUrl: generatePosterFallback(title, year),
synopsis: '',
genres: [],
rating: 0,
runtime: 0,
director,
cast: [],
sources: [],
})
}
return films
}
function extractAllFilms(text: string): Film[] {
const libraryFilms = resolveFilms(extractFilmIds(text))
const externalFilms = extractExternalFilms(text)
return [...libraryFilms, ...externalFilms]
}
function normalizeSongId(raw: string): string {
return raw.startsWith('s') ? raw : `s${raw}`
}
function extractSongIds(text: string): string[] {
const ids: string[] = []
let match: RegExpExecArray | null
const re = new RegExp(SONG_TAG_RE.source, 'gi')
while ((match = re.exec(text)) !== null) {
const id = normalizeSongId(match[1])
if (!ids.includes(id)) ids.push(id)
}
return ids
}
function resolveSongs(ids: string[]): Song[] {
return ids
.map((id) => mockSongs.find((s) => s.id === id))
.filter((s): s is Song => !!s)
}
function extractExternalSongs(text: string): Song[] {
const songs: Song[] = []
const seen = new Set<string>()
let match: RegExpExecArray | null
const re = new RegExp(SONG_EXT_RE.source, 'gi')
while ((match = re.exec(text)) !== null) {
const title = match[1].trim()
const artist = match[2].trim()
const year = match[3] ? parseInt(match[3], 10) : undefined
const key = `${title.toLowerCase()}|${artist.toLowerCase()}`
if (seen.has(key)) continue
seen.add(key)
songs.push({
id: `ext-${key.replace(/\W/g, '-')}`,
title,
artist,
year,
sources: [],
})
}
return songs
}
/** Infer songs from plain text when no tags present (e.g. old chats) */
function extractSongsFromPlainText(text: string): Song[] {
const lower = text.toLowerCase()
const found: Song[] = []
const seen = new Set<string>()
for (const song of mockSongs) {
const key = song.id
if (seen.has(key)) continue
if (lower.includes(song.title.toLowerCase()) && lower.includes(song.artist.toLowerCase())) {
seen.add(key)
found.push(song)
}
}
return found
}
function extractAllSongs(text: string): Song[] {
const librarySongs = resolveSongs(extractSongIds(text))
const externalSongs = extractExternalSongs(text)
if (librarySongs.length > 0 || externalSongs.length > 0) {
return [...librarySongs, ...externalSongs]
}
return extractSongsFromPlainText(text)
}
function updatePanelFromText(text: string) {
const songs = extractAllSongs(text)
const films = extractAllFilms(text)
if (songs.length > 0) {
panelSongs.value = songs
panelFilms.value = []
selectedFilm.value = null
contentType.value = 'song'
panelTitle.value = songs.length === 1
? songs[0].title
: `${songs.length} Recommended Songs`
panelOpen.value = true
} else if (films.length > 0) {
panelFilms.value = films
panelSongs.value = []
selectedSong.value = null
contentType.value = 'film'
panelTitle.value = films.length === 1
? films[0].title
: `${films.length} Recommended Films`
panelOpen.value = true
}
}
function stripFilmTags(text: string): string {
return text.replace(FILM_TAG_RE, '').replace(/\n{3,}/g, '\n\n').trim()
return text
.replace(FILM_TAG_RE, '')
.replace(FILM_EXT_RE, '')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
function stripSongTags(text: string): string {
return text
.replace(SONG_TAG_RE, '')
.replace(SONG_EXT_RE, '')
.replace(/\n{3,}/g, '\n\n')
.trim()
}
function stripContentTags(text: string): string {
return stripFilmTags(stripSongTags(text))
}
function openFilmDetail(film: Film) {
selectedFilm.value = film
selectedSong.value = null
}
function closeFilmDetail() {
selectedFilm.value = null
}
function openSongDetail(song: Song) {
selectedSong.value = song
selectedFilm.value = null
}
function closeSongDetail() {
selectedSong.value = null
}
function closePanel() {
panelOpen.value = false
selectedFilm.value = null
selectedSong.value = null
}
function showAllFilms() {
panelFilms.value = [...mockFilms]
panelSongs.value = []
panelTitle.value = 'Your Film Library'
contentType.value = 'film'
panelOpen.value = true
selectedFilm.value = null
selectedSong.value = null
}
function showAllSongs() {
panelFilms.value = []
panelSongs.value = [...mockSongs]
panelTitle.value = 'Your Song Library'
contentType.value = 'song'
panelOpen.value = true
selectedFilm.value = null
selectedSong.value = null
}
return {
panelOpen,
panelFilms,
panelSongs,
selectedFilm,
selectedSong,
panelTitle,
contentType,
extractFilmIds,
resolveFilms,
extractAllFilms,
extractSongIds,
resolveSongs,
extractAllSongs,
updatePanelFromText,
stripFilmTags,
stripSongTags,
stripContentTags,
openFilmDetail,
closeFilmDetail,
openSongDetail,
closeSongDetail,
closePanel,
showAllFilms,
showAllSongs,
}
}
@@ -1,3 +1,69 @@
type TmdbResult = { posterUrl: string | null; backdropUrl: string | null }
const memoryCache = new Map<string, TmdbResult>()
const SESSION_KEY = 'aiui-poster-cache'
const failedUrls = new Set<string>()
const musicCoverCache = new Map<string, string>()
const SESSION_MUSIC_KEY = 'aiui-music-cover-cache'
function musicCacheKey(artist: string, title: string): string {
return `${artist.toLowerCase().trim()}|${title.toLowerCase().trim()}`
}
function loadMusicCache(): void {
try {
const raw = sessionStorage.getItem(SESSION_MUSIC_KEY)
if (raw) {
const parsed = JSON.parse(raw) as Record<string, string>
Object.entries(parsed).forEach(([k, v]) => musicCoverCache.set(k, v))
}
} catch { /* ignore */ }
}
function saveMusicCache(): void {
try {
const entries = [...musicCoverCache.entries()].slice(-300)
sessionStorage.setItem(SESSION_MUSIC_KEY, JSON.stringify(Object.fromEntries(entries)))
} catch { /* ignore */ }
}
loadMusicCache()
function cacheKey(t: string, y?: number): string {
return `${t.toLowerCase().trim()}|${y ?? ''}`
}
function loadSessionCache(): void {
try {
const raw = sessionStorage.getItem(SESSION_KEY)
if (raw) {
const parsed = JSON.parse(raw) as Record<string, TmdbResult>
Object.entries(parsed).forEach(([k, v]) => memoryCache.set(k, v))
}
} catch { /* ignore */ }
}
function saveSessionCache(): void {
try {
const entries = [...memoryCache.entries()].slice(-200)
sessionStorage.setItem(SESSION_KEY, JSON.stringify(Object.fromEntries(entries)))
} catch { /* ignore */ }
}
loadSessionCache()
export function generateSongCoverFallback(title: string, artist?: string): string {
const hue = [...(title + (artist ?? ''))].reduce((acc, c) => acc + c.charCodeAt(0), 0) % 360
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 200">
<rect width="200" height="200" fill="hsl(${hue}, 30%, 14%)"/>
<rect x="2" y="2" width="196" height="196" rx="8" fill="none" stroke="hsl(${hue}, 40%, 25%)" stroke-width="2"/>
<path d="M100 50 v100 M70 70 q30-20 60 0 M70 130 q30 20 60 0" fill="none" stroke="hsl(${hue}, 50%, 60%)" stroke-width="4" stroke-linecap="round"/>
<text x="100" y="115" text-anchor="middle" fill="hsl(${hue}, 50%, 70%)" font-family="system-ui" font-size="14" font-weight="600">${escapeXml(title.length > 12 ? title.slice(0, 10) + '…' : title)}</text>
${artist ? `<text x="100" y="135" text-anchor="middle" fill="hsl(${hue}, 30%, 50%)" font-family="system-ui" font-size="10">${escapeXml(artist.length > 14 ? artist.slice(0, 12) + '…' : artist)}</text>` : ''}
</svg>`
return `data:image/svg+xml,${encodeURIComponent(svg)}`
}
export function generatePosterFallback(title: string, year?: number): string {
const hue = [...title].reduce((acc, c) => acc + c.charCodeAt(0), 0) % 360
const svg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 342 513">
@@ -7,7 +73,6 @@ export function generatePosterFallback(title: string, year?: number): string {
${escapeXml(title.length > 20 ? title.slice(0, 18) + '…' : title)}
</text>
${year ? `<text x="171" y="260" text-anchor="middle" fill="hsl(${hue}, 30%, 50%)" font-family="system-ui" font-size="14">${year}</text>` : ''}
<text x="171" y="290" text-anchor="middle" fill="hsl(${hue}, 20%, 35%)" font-size="40">🎬</text>
</svg>`
return `data:image/svg+xml,${encodeURIComponent(svg)}`
}
@@ -16,10 +81,96 @@ function escapeXml(s: string): string {
return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
}
export function handleImgError(e: Event, title: string, year?: number) {
export async function fetchTmdbPoster(
title: string,
year?: number,
): Promise<TmdbResult> {
const key = cacheKey(title, year)
const cached = memoryCache.get(key)
if (cached) return cached
const empty: TmdbResult = { posterUrl: null, backdropUrl: null }
try {
const params = new URLSearchParams({ q: title.trim() })
if (year && year > 0) params.set('y', String(year))
const res = await fetch(`/api/tmdb/search?${params}`)
if (!res.ok) return empty
const data = (await res.json()) as { posterUrl?: string | null; backdropUrl?: string | null }
const result: TmdbResult = {
posterUrl: data.posterUrl ?? null,
backdropUrl: data.backdropUrl ?? null,
}
if (result.posterUrl || result.backdropUrl) {
memoryCache.set(key, result)
saveSessionCache()
}
return result
} catch {
return empty
}
}
export async function handleImgError(
e: Event,
title: string,
year?: number,
): Promise<void> {
const img = e.target as HTMLImageElement
if (!img.dataset.fallback) {
img.dataset.fallback = '1'
img.src = generatePosterFallback(title, year)
if (img.dataset.fallback === 'done') return
const originalSrc = img.src
failedUrls.add(originalSrc)
const key = cacheKey(title, year)
const cached = memoryCache.get(key)
if (cached?.posterUrl && cached.posterUrl !== originalSrc) {
img.dataset.fallback = 'tmdb'
img.src = cached.posterUrl
return
}
if (img.dataset.fallback !== 'tmdb') {
const { posterUrl } = await fetchTmdbPoster(title, year)
if (posterUrl && posterUrl !== originalSrc) {
img.dataset.fallback = 'tmdb'
img.src = posterUrl
return
}
}
img.dataset.fallback = 'done'
img.src = generatePosterFallback(title, year)
}
export function isUrlFailed(url: string | undefined): boolean {
return !!url && failedUrls.has(url)
}
/** Fetch album artwork from iTunes Search API (free, no key). Returns hi-res URL (600x600). */
export async function fetchMusicCover(
title: string,
artist: string,
album?: string,
): Promise<string | null> {
const key = musicCacheKey(artist, title)
const cached = musicCoverCache.get(key)
if (cached) return cached
try {
const term = `${artist} ${title}`.trim().replace(/\s+/g, '+')
const res = await fetch(
`https://itunes.apple.com/search?term=${encodeURIComponent(term)}&media=music&limit=3`,
)
if (!res.ok) return null
const data = (await res.json()) as { results?: { artworkUrl100?: string }[] }
const first = data.results?.[0]
const url = first?.artworkUrl100
if (!url) return null
const hiRes = url.replace(/100x100/g, '600x600')
musicCoverCache.set(key, hiRes)
saveMusicCache()
return hiRes
} catch {
return null
}
}
+106
View File
@@ -0,0 +1,106 @@
import type { Song } from '@aiui/core/types/content'
export const mockSongs: Song[] = [
{
id: 's1',
title: 'Never Meant',
artist: 'American Football',
album: 'American Football',
year: 1999,
coverUrl: undefined,
duration: 269,
genres: ['Math Rock', 'Emo', 'Indie'],
sources: [
{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example', icon: 'spotify' },
{ type: 'youtube', name: 'YouTube', url: 'https://youtube.com/watch?v=example', icon: 'youtube' },
],
},
{
id: 's2',
title: 'The Kill',
artist: 'Toe',
album: 'The Book About My Idle Plot on a Vague Anxiety',
year: 2005,
coverUrl: undefined,
duration: 248,
genres: ['Math Rock', 'Post-Rock'],
sources: [{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example2', icon: 'spotify' }],
},
{
id: 's3',
title: 'Caraphernelia',
artist: 'Pierce the Veil',
album: 'Selfish Machines',
year: 2010,
coverUrl: undefined,
duration: 234,
genres: ['Post-Hardcore', 'Math Rock'],
sources: [{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example3', icon: 'spotify' }],
},
{
id: 's4',
title: 'Ghosts',
artist: 'Clever Girl',
album: 'No Drum and Bass in the Jazz Room',
year: 2016,
coverUrl: undefined,
duration: 312,
genres: ['Math Rock', 'Instrumental'],
sources: [{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example4', icon: 'spotify' }],
},
{
id: 's5',
title: 'pon ponpon',
artist: 'TTNG',
album: 'Animals',
year: 2008,
coverUrl: undefined,
duration: 198,
genres: ['Math Rock', 'Indie'],
sources: [{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example5', icon: 'spotify' }],
},
{
id: 's6',
title: 'Kié la, tricotées',
artist: 'Battles',
album: 'Mirrored',
year: 2007,
coverUrl: undefined,
duration: 427,
genres: ['Math Rock', 'Experimental'],
sources: [{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example6', icon: 'spotify' }],
},
{
id: 's7',
title: 'Delivering the Groceries at 138 Beats Per Minute',
artist: 'Don Caballero',
album: 'American Don',
year: 2000,
coverUrl: undefined,
duration: 334,
genres: ['Math Rock', 'Instrumental'],
sources: [{ type: 'bandcamp', name: 'Bandcamp', url: 'https://doncaballero.bandcamp.com', icon: 'bandcamp' }],
},
{
id: 's8',
title: 'Frozen Zoo',
artist: 'Tera Melos',
album: 'Untitled',
year: 2005,
coverUrl: undefined,
duration: 189,
genres: ['Math Rock', 'Noise Rock'],
sources: [{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example8', icon: 'spotify' }],
},
{
id: 's9',
title: 'Solid Ground',
artist: 'Maps & Atlases',
album: 'Trees, Swallows, Houses',
year: 2006,
coverUrl: undefined,
duration: 256,
genres: ['Math Rock', 'Indie'],
sources: [{ type: 'spotify', name: 'Spotify', url: 'https://open.spotify.com/track/example9', icon: 'spotify' }],
},
]
+90 -30
View File
@@ -13,44 +13,66 @@
<!-- Content surface (main area) -->
<main
class="flex-1 min-w-0 glass-card overflow-hidden flex flex-col"
:class="panelSide === 'left' ? 'order-last' : 'order-first'"
:class="[
panelSide === 'left' ? 'order-last' : 'order-first',
(selectedFilm || selectedSong) && 'detail-active'
]"
>
<div v-if="panelOpen" class="flex-1 min-h-0">
<FilmDetail
v-if="selectedFilm"
:film="selectedFilm"
@back="closeFilmDetail"
/>
<FilmGrid
v-else
:films="panelFilms"
:title="panelTitle"
@select-film="openFilmDetail"
/>
</div>
<Transition name="content-fade" mode="out-in">
<div v-if="panelOpen" key="content" class="flex-1 min-h-0 flex flex-col">
<FilmDetail
v-if="selectedFilm"
:film="selectedFilm"
@back="closeFilmDetail"
/>
<SongDetail
v-else-if="selectedSong"
:song="selectedSong"
@back="closeSongDetail"
/>
<FilmGrid
v-else-if="contentType === 'film'"
:films="panelFilms"
:title="panelTitle"
@select-film="openFilmDetail"
/>
<SongGrid
v-else
:songs="panelSongs"
:title="panelTitle"
@select-song="openSongDetail"
/>
</div>
<div v-else class="flex-1 flex items-center justify-center">
<div class="text-center space-y-4 animate-fade-up max-w-sm px-6">
<div class="w-20 h-20 rounded-2xl glass flex items-center justify-center mx-auto">
<span class="text-3xl"></span>
</div>
<div>
<h2 class="text-lg font-bold mb-1"
:class="isDark ? 'text-white/80' : 'text-gray-800'">
Content Surface
</h2>
<p class="text-sm leading-relaxed"
:class="isDark ? 'text-white/30' : 'text-gray-400'">
Ask about films in the chat to see rich content here.
</p>
<ContextLoader
v-else-if="chatStore.isStreaming"
key="loader"
:context-type="loaderContextType"
/>
<div v-else key="empty" class="flex-1 flex items-center justify-center">
<div class="text-center space-y-4 animate-fade-up max-w-sm px-6">
<div class="w-20 h-20 rounded-2xl glass flex items-center justify-center mx-auto">
<span class="text-3xl" :class="isDark ? 'text-[#fafafa]' : 'text-gray-800'"></span>
</div>
<div>
<h2 class="text-lg font-bold mb-1"
:class="isDark ? 'text-white/80' : 'text-gray-800'">
Content Surface
</h2>
<p class="text-sm leading-relaxed"
:class="isDark ? 'text-white/30' : 'text-gray-400'">
Ask about films or songs in the chat to see rich content here.
</p>
</div>
</div>
</div>
</div>
</Transition>
</main>
<!-- Chat panel -->
<aside
class="w-80 xl:w-96 shrink-0 flex flex-col glass-card overflow-hidden"
class="w-80 xl:w-96 shrink-0 flex flex-col glass-card overflow-visible"
:class="panelSide === 'left' ? 'order-first' : 'order-last'"
>
<ChatWindow
@@ -72,6 +94,9 @@ import { useContentPanel } from '@/composables/useContentPanel'
import ChatWindow from '@/components/chat/ChatWindow.vue'
import FilmGrid from '@/components/content/FilmGrid.vue'
import FilmDetail from '@/components/content/FilmDetail.vue'
import SongGrid from '@/components/content/SongGrid.vue'
import SongDetail from '@/components/content/SongDetail.vue'
import ContextLoader from '@/components/content/ContextLoader.vue'
const chatStore = useChatStore()
const { isDark } = useTheme()
@@ -81,11 +106,46 @@ useAI()
const {
panelOpen,
panelFilms,
panelSongs,
panelTitle,
contentType,
selectedFilm,
selectedSong,
openFilmDetail,
closeFilmDetail,
openSongDetail,
closeSongDetail,
} = useContentPanel()
const panelSide = computed(() => chatStore.panelSide)
// Infer loader type from last user message when streaming (before tags are parsed)
const loaderContextType = computed(() => {
if (panelOpen.value) return contentType.value
const lastUser = [...chatStore.messages].reverse().find((m) => m.role === 'user')
const q = (lastUser?.content ?? '').toLowerCase()
if (/\b(song|music|track|album|band|artist|listen)\b/.test(q)) return 'song'
return contentType.value
})
</script>
<style scoped>
.content-fade-enter-active,
.content-fade-leave-active {
transition: opacity 0.2s ease;
}
.content-fade-enter-from,
.content-fade-leave-to {
opacity: 0;
}
/*
* When film detail is active, hide the border so the hero image
* fills edge-to-edge with no visible seam lines.
* The card keeps its border-radius and overflow:hidden,
* so the image is still clipped to rounded corners.
*/
.detail-active {
border-color: transparent !important;
}
</style>
+70
View File
@@ -2,18 +2,87 @@ import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import type { Message, Conversation } from '@aiui/core/types/message'
const isDev = import.meta.env.DEV
let saveTimer: ReturnType<typeof setTimeout> | null = null
const SAVE_DEBOUNCE = 800
// Server-side persistence via Vite dev middleware
async function loadServerChats(): Promise<{ conversations: Map<string, Conversation>; activeId: string | null }> {
const empty = { conversations: new Map<string, Conversation>(), activeId: null }
if (!isDev) return empty
try {
const res = await fetch('/api/dev-chats')
if (!res.ok) return empty
const data = await res.json() as {
conversations?: Record<string, Conversation>
activeConversationId?: string | null
}
if (!data.conversations) return empty
const conversations = new Map(Object.entries(data.conversations))
return {
conversations,
activeId: data.activeConversationId ?? null,
}
} catch {
return empty
}
}
let _loaded = false
function saveServerChats(conversations: Map<string, Conversation>, activeId: string | null) {
if (!isDev || !_loaded) return
if (saveTimer) clearTimeout(saveTimer)
saveTimer = setTimeout(() => {
const obj = Object.fromEntries(conversations)
fetch('/api/dev-chats', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ conversations: obj, activeConversationId: activeId }),
}).catch(() => {})
}, SAVE_DEBOUNCE)
}
export const useChatStore = defineStore('chat', () => {
const conversations = ref<Map<string, Conversation>>(new Map())
const activeConversationId = ref<string | null>(null)
const isStreaming = ref(false)
const loaded = ref(false)
const savedSide = localStorage.getItem('aiui-panel-side') as 'left' | 'right' | null
const panelSide = ref<'left' | 'right'>(savedSide ?? 'right')
// Load chats from server on startup — _loaded gate prevents the watcher
// from overwriting the file with empty data before the load completes
if (isDev) {
loadServerChats().then((data) => {
if (data.conversations.size > 0) {
conversations.value = data.conversations
activeConversationId.value =
data.activeId && data.conversations.has(data.activeId)
? data.activeId
: [...data.conversations.keys()][0] ?? null
}
loaded.value = true
_loaded = true
})
} else {
loaded.value = true
_loaded = true
}
watch(panelSide, (val) => {
localStorage.setItem('aiui-panel-side', val)
})
watch(
[conversations, activeConversationId],
([conv, active]) => {
saveServerChats(conv as Map<string, Conversation>, active as string | null)
},
{ deep: true }
)
const activeConversation = computed(() => {
if (!activeConversationId.value) return null
return conversations.value.get(activeConversationId.value) ?? null
@@ -90,6 +159,7 @@ export const useChatStore = defineStore('chat', () => {
messages,
conversationList,
isStreaming,
loaded,
panelSide,
createConversation,
addMessage,
+71
View File
@@ -354,6 +354,77 @@ input:focus-visible {
50% { opacity: 1; }
}
/* ===== POSTER CARD — Indeehub-style gradient border ===== */
.poster-card {
margin: 2px;
padding: 2px;
border-radius: 0.75rem;
background: linear-gradient(127deg, var(--color-accent) 0%, var(--color-info) 100%);
transition: margin 0.2s ease, padding 0.2s ease;
}
.poster-card:hover {
margin: 0;
padding: 4px;
}
.light .poster-card {
background: linear-gradient(127deg, rgba(247, 147, 26, 0.4) 0%, rgba(59, 130, 246, 0.35) 100%);
}
.poster-card-sm {
margin: 1px;
padding: 1px;
border-radius: 0.5rem;
background: linear-gradient(127deg, var(--color-accent) 0%, var(--color-info) 100%);
transition: margin 0.2s ease, padding 0.2s ease;
}
.poster-card-sm:hover {
margin: 0;
padding: 2px;
}
.light .poster-card-sm {
background: linear-gradient(127deg, rgba(247, 147, 26, 0.35) 0%, rgba(59, 130, 246, 0.3) 100%);
}
/* Cover card — same as poster-card, for square album art */
.cover-card {
margin: 2px;
padding: 2px;
border-radius: 0.75rem;
background: linear-gradient(127deg, var(--color-accent) 0%, var(--color-info) 100%);
transition: margin 0.2s ease, padding 0.2s ease;
}
.cover-card:hover {
margin: 0;
padding: 4px;
}
.light .cover-card {
background: linear-gradient(127deg, rgba(247, 147, 26, 0.4) 0%, rgba(59, 130, 246, 0.35) 100%);
}
.cover-card-sm {
margin: 1px;
padding: 1px;
border-radius: 0.5rem;
background: linear-gradient(127deg, var(--color-accent) 0%, var(--color-info) 100%);
transition: margin 0.2s ease, padding 0.2s ease;
}
.cover-card-sm:hover {
margin: 0;
padding: 2px;
}
.light .cover-card-sm {
background: linear-gradient(127deg, rgba(247, 147, 26, 0.35) 0%, rgba(59, 130, 246, 0.3) 100%);
}
.animate-fade-up {
animation: fadeUpIn 900ms cubic-bezier(0.22, 1, 0.36, 1) 120ms both;
}
+68
View File
@@ -0,0 +1,68 @@
import type { Plugin, Connect } from 'vite'
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
import { resolve, dirname } from 'path'
const CHATS_DIR = '.dev'
const CHATS_FILE = 'chats.json'
function getChatsPath(root: string): string {
const dir = resolve(root, CHATS_DIR)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
return resolve(dir, CHATS_FILE)
}
function readChats(filePath: string): string {
if (!existsSync(filePath)) return '{}'
try {
return readFileSync(filePath, 'utf-8')
} catch {
return '{}'
}
}
function writeChats(filePath: string, data: string): void {
const dir = dirname(filePath)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
writeFileSync(filePath, data, 'utf-8')
}
export function devChatsPlugin(): Plugin {
let chatsPath = ''
return {
name: 'aiui-dev-chats',
apply: 'serve',
configResolved(config) {
chatsPath = getChatsPath(config.root)
},
configureServer(server) {
server.middlewares.use('/api/dev-chats', (req: Connect.IncomingMessage, res: any, next: () => void) => {
if (req.method === 'GET') {
const data = readChats(chatsPath)
res.setHeader('Content-Type', 'application/json')
res.end(data)
return
}
if (req.method === 'PUT') {
let body = ''
req.on('data', (chunk: Buffer) => { body += chunk.toString() })
req.on('end', () => {
try {
JSON.parse(body)
writeChats(chatsPath, body)
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ ok: true }))
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Invalid JSON' }))
}
})
return
}
next()
})
},
}
}
+67
View File
@@ -0,0 +1,67 @@
import type { Plugin } from 'vite'
import type { Connect } from 'vite'
import { loadEnv } from 'vite'
const TMDB_POSTER = 'https://image.tmdb.org/t/p/w342'
const TMDB_BACKDROP = 'https://image.tmdb.org/t/p/w780'
function createTmdbMiddleware(tmdbKey: string | undefined) {
return async (req: Connect.IncomingMessage, res: any, next: () => void) => {
if (req.method !== 'GET') return next()
const url = new URL(req.url ?? '', `http://${req.headers?.host ?? 'localhost'}`)
const q = url.searchParams.get('q')?.trim()
const y = url.searchParams.get('y')
if (!q) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Missing q (query)' }))
return
}
if (!tmdbKey) {
res.writeHead(503, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'TMDB_API_KEY not configured' }))
return
}
try {
const params = new URLSearchParams({
api_key: tmdbKey,
query: q,
...(y ? { primary_release_year: y } : {}),
})
const tmdbRes = await fetch(
`https://api.themoviedb.org/3/search/movie?${params}`
)
const data = (await tmdbRes.json()) as {
results?: { poster_path?: string; backdrop_path?: string }[]
}
const first = data.results?.[0]
const posterUrl = first?.poster_path ? `${TMDB_POSTER}${first.poster_path}` : null
const backdropUrl = first?.backdrop_path ? `${TMDB_BACKDROP}${first.backdrop_path}` : null
res.setHeader('Content-Type', 'application/json')
res.setHeader('Access-Control-Allow-Origin', '*')
res.setHeader('Cache-Control', 'public, max-age=86400')
res.end(JSON.stringify({ posterUrl, backdropUrl }))
} catch (err) {
console.error('[tmdb]', err)
res.writeHead(502, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: String(err) }))
}
}
}
export function tmdbPlugin(): Plugin {
let tmdbKey: string | undefined
return {
name: 'aiui-tmdb-proxy',
configResolved(config) {
const env = loadEnv(config.mode, process.cwd(), '')
tmdbKey = env.TMDB_API_KEY ?? env.VITE_TMDB_API_KEY
},
configureServer(server) {
server.middlewares.use('/api/tmdb/search', createTmdbMiddleware(tmdbKey))
},
configurePreviewServer(server) {
server.middlewares.use('/api/tmdb/search', createTmdbMiddleware(tmdbKey))
},
}
}
+4
View File
@@ -3,11 +3,15 @@ import vue from '@vitejs/plugin-vue'
import tailwindcss from '@tailwindcss/vite'
import { VitePWA } from 'vite-plugin-pwa'
import { resolve } from 'path'
import { tmdbPlugin } from './vite-tmdb'
import { devChatsPlugin } from './vite-dev-chats'
export default defineConfig({
plugins: [
vue(),
tailwindcss(),
tmdbPlugin(),
devChatsPlugin(),
VitePWA({
registerType: 'autoUpdate',
includeAssets: ['favicon.svg', 'icon.svg', 'apple-touch-icon-180x180.png'],
+19
View File
@@ -33,3 +33,22 @@ export interface FilmRendererData {
query?: string
totalResults?: number
}
export interface SongSource {
type: 'plex' | 'spotify' | 'youtube' | 'apple-music' | 'bandcamp'
name: string
url: string
icon?: string
}
export interface Song {
id: string
title: string
artist: string
album?: string
year?: number
coverUrl?: string
duration?: number
genres?: string[]
sources?: SongSource[]
}