mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-30 21:04:59 +00:00
feat(search): add image similarity search (#537)
* feat(search): add image similarity search * feat(search): support pasting image attachments
This commit is contained in:
@@ -25,9 +25,10 @@ import {
|
||||
ArrowRight,
|
||||
Copy,
|
||||
Layers,
|
||||
ScanSearch,
|
||||
} from 'lucide-react'
|
||||
import { CopyContextMenuSub } from './copy-submenu'
|
||||
import type { CopyKind } from './copy-options'
|
||||
import { isImageItem, type CopyKind } from './copy-options'
|
||||
|
||||
interface FileBrowserContextMenuProps {
|
||||
item: AssetInfo | null
|
||||
@@ -36,6 +37,7 @@ interface FileBrowserContextMenuProps {
|
||||
onDelete: (items: AssetInfo[]) => void
|
||||
onDownload: (items: AssetInfo[]) => void
|
||||
onCopy?: (kind: CopyKind, items: AssetInfo[]) => void
|
||||
onFindSimilar?: (item: AssetInfo) => void
|
||||
onRestore: (items: AssetInfo[]) => void
|
||||
onArchive?: (items: AssetInfo[]) => void
|
||||
onRestoreArchive?: (items: AssetInfo[]) => void
|
||||
@@ -69,6 +71,7 @@ export function FileBrowserContextMenu({
|
||||
onDelete,
|
||||
onDownload,
|
||||
onCopy,
|
||||
onFindSimilar,
|
||||
onRestore,
|
||||
onArchive,
|
||||
onRestoreArchive,
|
||||
@@ -222,6 +225,15 @@ export function FileBrowserContextMenu({
|
||||
)
|
||||
}
|
||||
|
||||
const findSimilarItem = onFindSimilar &&
|
||||
(item.type === 'file' || item.type === 'version_stack') &&
|
||||
isImageItem(item) && (
|
||||
<ContextMenuItem onSelect={() => onFindSimilar(item)}>
|
||||
<ScanSearch className="mr-2 h-4 w-4" />
|
||||
<span>{m.find_similar()}</span>
|
||||
</ContextMenuItem>
|
||||
)
|
||||
|
||||
const contextMenuContent =
|
||||
isItemSelected && selectedIds.size > 1 ? (
|
||||
<ContextMenuContent
|
||||
@@ -234,6 +246,7 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>{m.download()}</span>
|
||||
</ContextMenuItem>
|
||||
{findSimilarItem}
|
||||
<CopyContextMenuSub
|
||||
items={itemsToModify}
|
||||
context={{
|
||||
@@ -331,6 +344,7 @@ export function FileBrowserContextMenu({
|
||||
<Download className="mr-2 h-4 w-4" />
|
||||
<span>{m.download()}</span>
|
||||
</ContextMenuItem>
|
||||
{findSimilarItem}
|
||||
<CopyContextMenuSub
|
||||
items={itemsToModify}
|
||||
context={{
|
||||
|
||||
@@ -29,6 +29,8 @@ import { ManageVersionsDialog } from '../manage-versions-dialog'
|
||||
import { FilePreviewDialog } from '../file-preview-dialog'
|
||||
import { FileBrowserContentSkeleton } from '../loading-skeletons'
|
||||
import { FileBrowserContextMenu } from './context-menu'
|
||||
import { FindSimilarDialog } from '../search/find-similar-dialog'
|
||||
import { useSemanticSearchEnabled } from '../search/use-semantic-search-enabled'
|
||||
|
||||
import {
|
||||
AlertDialog,
|
||||
@@ -156,6 +158,13 @@ export function FileBrowser({
|
||||
allowDownload = true,
|
||||
}: FileBrowserProps) {
|
||||
const [contextMenuItem, setContextMenuItem] = useState<AssetInfo | null>(null)
|
||||
const [similarImage, setSimilarImage] = useState<AssetInfo | null>(null)
|
||||
const semanticSearchEnabled = useSemanticSearchEnabled(
|
||||
teamId,
|
||||
Boolean(
|
||||
rootFolderId && !isShareView && !isPublic && !isRecents && !isRecentlyDeleted && !collection,
|
||||
),
|
||||
)
|
||||
const [manageVersionsStackId, setManageVersionsStackId] = useState<string | null>(null)
|
||||
const [moveCopyMode, setMoveCopyMode] = useState<'move' | 'copy' | null>(null)
|
||||
const [itemsToMoveCopy, setItemsToMoveCopy] = useState<AssetInfo[]>([])
|
||||
@@ -1179,6 +1188,7 @@ export function FileBrowser({
|
||||
onDelete={handleDelete}
|
||||
onDownload={handleDownload}
|
||||
onCopy={handleCopy}
|
||||
onFindSimilar={semanticSearchEnabled && rootFolderId ? setSimilarImage : undefined}
|
||||
onNewFolder={handleNewFolder}
|
||||
onUploadFile={handleUploadFilesClick}
|
||||
onUploadFolder={handleUploadFolderClick}
|
||||
@@ -1239,6 +1249,16 @@ export function FileBrowser({
|
||||
)}
|
||||
{renderContent()}
|
||||
|
||||
{semanticSearchEnabled && similarImage && rootFolderId && (
|
||||
<FindSimilarDialog
|
||||
image={similarImage}
|
||||
folderId={rootFolderId}
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
onClose={() => setSimilarImage(null)}
|
||||
/>
|
||||
)}
|
||||
|
||||
{moveCopyMode && (
|
||||
<MoveCopyDialog
|
||||
isOpen={!!moveCopyMode}
|
||||
|
||||
@@ -112,8 +112,9 @@ export const FilePreview = ({ item, showDuration = false, matchDuration }: FileP
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="w-full h-full flex items-center justify-center">
|
||||
<div className="relative w-full h-full flex items-center justify-center">
|
||||
<File className="w-8 h-8 fill-primary/60 stroke-0" />
|
||||
{overlay}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
import type { AssetInfo, ImageSearchMediaType } from '@shumai/dtos'
|
||||
import { useInfiniteQuery } from '@tanstack/react-query'
|
||||
import { Loader2 } from 'lucide-react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { ScrollArea } from '@/ui/components/ui/scroll-area'
|
||||
import { ToggleGroup, ToggleGroupItem } from '@/ui/components/ui/toggle-group'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { searchByImage } from './search-by-image'
|
||||
import { SearchResultCards } from './search-result-cards'
|
||||
|
||||
type MediaFilter = ImageSearchMediaType | 'all'
|
||||
|
||||
export function FindSimilarDialog({
|
||||
image,
|
||||
folderId,
|
||||
teamId,
|
||||
projectId,
|
||||
onClose,
|
||||
}: {
|
||||
image: AssetInfo
|
||||
folderId: string
|
||||
teamId: string
|
||||
projectId: string
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [filter, setFilter] = useState<MediaFilter>('all')
|
||||
const sourceAssetId =
|
||||
image.versionStack?.versions.find((version) => version.current)?.id ?? image.id
|
||||
const { ref, inView } = useInView()
|
||||
const { data, error, isLoading, hasNextPage, isFetchingNextPage, fetchNextPage } =
|
||||
useInfiniteQuery({
|
||||
queryKey: ['find-similar', folderId, sourceAssetId, filter],
|
||||
queryFn: ({ pageParam, signal }) =>
|
||||
searchByImage(
|
||||
folderId,
|
||||
{
|
||||
sourceAssetId,
|
||||
conditions: [],
|
||||
operator: 'AND',
|
||||
mediaType: filter === 'all' ? undefined : filter,
|
||||
first: 20,
|
||||
after: pageParam,
|
||||
},
|
||||
signal,
|
||||
),
|
||||
initialPageParam: undefined as string | undefined,
|
||||
getNextPageParam: (page) => page.pageInfo.cursor,
|
||||
retry: false,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage && !error) void fetchNextPage()
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage, error])
|
||||
|
||||
const results = data?.pages.flatMap((page) => page.data) ?? []
|
||||
const total = data?.pages[0]?.pageInfo.total
|
||||
|
||||
return (
|
||||
<Dialog
|
||||
open
|
||||
onOpenChange={(open) => {
|
||||
if (!open) onClose()
|
||||
}}
|
||||
>
|
||||
<DialogContent className="flex h-[85vh] flex-col overflow-hidden p-0 sm:max-w-4xl">
|
||||
<DialogHeader className="px-6 pt-5 pr-12">
|
||||
<DialogTitle>{m.find_similar()}</DialogTitle>
|
||||
<DialogDescription className="truncate">{image.name}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="flex flex-wrap items-center justify-between gap-2 border-b px-6 pb-4">
|
||||
<ToggleGroup
|
||||
aria-label={m.image_search_media_filter()}
|
||||
type="single"
|
||||
variant="outline"
|
||||
value={filter}
|
||||
onValueChange={(value) => {
|
||||
if (value === 'all' || value === 'image' || value === 'video') setFilter(value)
|
||||
}}
|
||||
>
|
||||
<ToggleGroupItem value="all">{m.all()}</ToggleGroupItem>
|
||||
<ToggleGroupItem value="image">{m.image_search_images()}</ToggleGroupItem>
|
||||
<ToggleGroupItem value="video">{m.image_search_videos()}</ToggleGroupItem>
|
||||
</ToggleGroup>
|
||||
{total != null && (
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{m.matched_items({ count: String(total) })}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<ScrollArea className="min-h-0 flex-1 [&>div>div]:block!">
|
||||
<div className="p-6">
|
||||
{(isLoading || isFetchingNextPage) && (
|
||||
<p
|
||||
role="status"
|
||||
className="flex items-center gap-2 py-2 text-sm text-muted-foreground"
|
||||
>
|
||||
<Loader2 className="size-4 animate-spin" />
|
||||
{m.loading()}
|
||||
</p>
|
||||
)}
|
||||
{error && (
|
||||
<p role="alert" className="py-2 text-sm text-destructive">
|
||||
{error.message}
|
||||
</p>
|
||||
)}
|
||||
{!isLoading && !error && results.length === 0 && (
|
||||
<p className="py-2 text-sm text-muted-foreground">{m.no_records_matched()}</p>
|
||||
)}
|
||||
<SearchResultCards teamId={teamId} projectId={projectId} results={results} />
|
||||
{hasNextPage && !error && <div ref={ref} className="h-1" />}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import type { ImageSearchRequest } from '@shumai/dtos'
|
||||
|
||||
export async function searchByImage(
|
||||
folderId: string,
|
||||
request: ImageSearchRequest,
|
||||
signal: AbortSignal,
|
||||
) {
|
||||
const res = await client.api.folders[':folderId']['image-search'].$post(
|
||||
{ param: { folderId }, json: request },
|
||||
{ init: { signal } },
|
||||
)
|
||||
if (!res.ok) {
|
||||
if (res.status === 409) throw new Error(m.image_search_waiting_for_index())
|
||||
if (res.status === 422) throw new Error(m.enable_embedding_agent_hint())
|
||||
if (res.status === 400 || res.status === 413) throw new Error(m.image_search_invalid_image())
|
||||
throw new Error(m.search_failed())
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
@@ -9,15 +9,17 @@ import { Input } from '@/ui/components/ui/input'
|
||||
import { Label } from '@/ui/components/ui/label'
|
||||
import { Switch } from '@/ui/components/ui/switch'
|
||||
import { cn } from '@/ui/lib/utils'
|
||||
import { useInfiniteQuery, useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
|
||||
import { useInfiniteQuery, useMutation, useQueryClient } from '@tanstack/react-query'
|
||||
import { useNavigate } from '@tanstack/react-router'
|
||||
import { AlertCircle, ChevronDown, ChevronUp, Loader2, Search, X } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { useInView } from 'react-intersection-observer'
|
||||
import { toast } from 'sonner'
|
||||
import { FileCard } from '@/ui/components/file-browser/file-card'
|
||||
import { FolderCard } from '@/ui/components/file-browser/folder-card'
|
||||
import { FilterPanel } from './filter-panel'
|
||||
import { SearchImagePicker, type SearchImage } from './search-image-picker'
|
||||
import { SearchResultCards } from './search-result-cards'
|
||||
import { useSemanticSearchEnabled } from './use-semantic-search-enabled'
|
||||
import { searchByImage } from './search-by-image'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
interface SearchFilterDialogProps {
|
||||
@@ -59,22 +61,15 @@ export function SearchFilterDialog({
|
||||
const [triggerQuery, setTriggerQuery] = useState(initialKeyword)
|
||||
const [isSemantic, setIsSemantic] = useState<boolean>(false)
|
||||
|
||||
const { data: teamSettings } = useQuery({
|
||||
queryKey: ['team-settings', teamId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].settings.$get({
|
||||
param: { teamId },
|
||||
})
|
||||
if (!res.ok) throw new Error(m.failed_load_settings())
|
||||
return (await res.json()) as { semanticSearchEnabled: boolean }
|
||||
},
|
||||
enabled: open,
|
||||
})
|
||||
|
||||
const semanticSearchEnabled = teamSettings?.semanticSearchEnabled ?? false
|
||||
const [attachedImage, setAttachedImage] = useState<SearchImage | null>(null)
|
||||
const [imageSubmitted, setImageSubmitted] = useState(false)
|
||||
const submittedImage = imageSubmitted ? attachedImage : null
|
||||
const semanticSearchEnabled = useSemanticSearchEnabled(teamId, open)
|
||||
|
||||
// Sync back if changed from outside, clear on close
|
||||
useEffect(() => {
|
||||
setAttachedImage(null)
|
||||
setImageSubmitted(false)
|
||||
if (open) {
|
||||
setSearchInput(initialKeyword)
|
||||
setTriggerQuery(initialKeyword)
|
||||
@@ -101,10 +96,9 @@ export function SearchFilterDialog({
|
||||
return result
|
||||
}, [isSemantic, triggerQuery, conditions])
|
||||
|
||||
const hasActiveCriteria = useMemo(() => {
|
||||
const activeText = triggerQuery
|
||||
return activeText.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
|
||||
}, [triggerQuery, conditions])
|
||||
const hasActiveCriteria = attachedImage
|
||||
? Boolean(submittedImage && semanticSearchEnabled)
|
||||
: triggerQuery.trim() !== '' || conditions.some((c) => String(c.value || '').trim() !== '')
|
||||
|
||||
const { mutate: saveAsCollection, isPending: isSaving } = useMutation({
|
||||
mutationFn: async () => {
|
||||
@@ -157,11 +151,33 @@ export function SearchFilterDialog({
|
||||
isLoading,
|
||||
isFetchingNextPage,
|
||||
fetchNextPage,
|
||||
refetch,
|
||||
hasNextPage,
|
||||
error: searchError,
|
||||
} = useInfiniteQuery({
|
||||
queryKey: ['search-preview', teamId, assetId, combinedConditions, isSemantic, triggerQuery],
|
||||
queryFn: async ({ pageParam }) => {
|
||||
queryKey: [
|
||||
'search-preview',
|
||||
teamId,
|
||||
assetId,
|
||||
combinedConditions,
|
||||
isSemantic,
|
||||
triggerQuery,
|
||||
submittedImage?.id,
|
||||
],
|
||||
queryFn: async ({ pageParam, signal }) => {
|
||||
if (submittedImage) {
|
||||
return searchByImage(
|
||||
assetId,
|
||||
{
|
||||
image: submittedImage.base64,
|
||||
conditions: combinedConditions,
|
||||
operator: 'AND',
|
||||
first: 20,
|
||||
after: pageParam || undefined,
|
||||
},
|
||||
signal,
|
||||
)
|
||||
}
|
||||
const activeText = triggerQuery
|
||||
const res = await client.api.folders[':folderId'].search.$post({
|
||||
param: { folderId: assetId },
|
||||
@@ -186,16 +202,17 @@ export function SearchFilterDialog({
|
||||
},
|
||||
enabled: open && hasActiveCriteria,
|
||||
staleTime: 500,
|
||||
gcTime: submittedImage ? 0 : undefined,
|
||||
retry: false,
|
||||
initialPageParam: '',
|
||||
getNextPageParam: (lastPage) => lastPage.pageInfo?.cursor || undefined,
|
||||
})
|
||||
|
||||
useEffect(() => {
|
||||
if (inView && hasNextPage && !isFetchingNextPage) {
|
||||
if (inView && hasNextPage && !isFetchingNextPage && !searchError) {
|
||||
fetchNextPage()
|
||||
}
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage])
|
||||
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage, searchError])
|
||||
|
||||
const flattenedResults = useMemo(() => {
|
||||
return searchResults?.pages.flatMap((page) => page.data) || []
|
||||
@@ -217,20 +234,6 @@ export function SearchFilterDialog({
|
||||
setConditions([])
|
||||
}
|
||||
|
||||
const handleResultClick = (item: AssetInfo) => {
|
||||
if (item.type === 'folder') {
|
||||
window.open(`/projects/${projectId}/folders/${item.id}`, '_blank', 'noopener,noreferrer')
|
||||
} else {
|
||||
const fileId = item.versionStack ? item.versionStack.id : item.id!
|
||||
const searchParams = new URLSearchParams()
|
||||
if (item.startTime !== undefined && item.startTime !== null && item.startTime > 0) {
|
||||
searchParams.set('start', String(item.startTime))
|
||||
}
|
||||
const query = searchParams.toString() ? `?${searchParams.toString()}` : ''
|
||||
window.open(`/projects/${projectId}/files/${fileId}${query}`, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
}
|
||||
|
||||
const activeFiltersCount = conditions.filter((c) => c.value !== '').length
|
||||
|
||||
return (
|
||||
@@ -244,37 +247,72 @@ export function SearchFilterDialog({
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
setTriggerQuery(searchInput.trim())
|
||||
if (attachedImage) {
|
||||
if (!semanticSearchEnabled) return
|
||||
if (imageSubmitted) void refetch()
|
||||
else setImageSubmitted(true)
|
||||
} else {
|
||||
setTriggerQuery(searchInput.trim())
|
||||
}
|
||||
}}
|
||||
className="flex flex-col gap-3 mt-2"
|
||||
>
|
||||
<div className="relative">
|
||||
<Input
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
placeholder={
|
||||
isSemantic ? m.search_by_content_placeholder() : m.search_by_name_placeholder()
|
||||
}
|
||||
className="w-full pl-4 pr-24 py-3 bg-background border-border rounded-xl text-sm h-12 focus-visible:ring-2 focus-visible:ring-primary/20 shadow-sm"
|
||||
/>
|
||||
{searchInput && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
}}
|
||||
className="absolute right-20 top-1/2 -translate-y-1/2 p-1 rounded-md text-muted-foreground hover:text-foreground transition-colors"
|
||||
>
|
||||
<X className="w-4 h-4" />
|
||||
</button>
|
||||
{attachedImage ? (
|
||||
<div className="flex h-12 items-center gap-2 rounded-xl border bg-background pl-2 pr-36 shadow-sm">
|
||||
<img
|
||||
alt=""
|
||||
src={`data:image/jpeg;base64,${attachedImage.base64}`}
|
||||
className="size-8 rounded-sm object-cover"
|
||||
/>
|
||||
<span className="truncate text-sm">{attachedImage.name}</span>
|
||||
</div>
|
||||
) : (
|
||||
<Input
|
||||
value={searchInput}
|
||||
onChange={(e) => setSearchInput(e.target.value)}
|
||||
placeholder={
|
||||
isSemantic ? m.search_by_content_placeholder() : m.search_by_name_placeholder()
|
||||
}
|
||||
className={cn(
|
||||
'h-12 w-full rounded-xl border-border bg-background py-3 pl-4 text-sm shadow-sm focus-visible:ring-2 focus-visible:ring-primary/20',
|
||||
isSemantic && semanticSearchEnabled ? 'pr-36' : 'pr-28',
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className="absolute right-1.5 top-1.5 bottom-1.5 px-4 bg-primary hover:bg-primary/90 text-primary-foreground text-xs font-semibold rounded-lg flex items-center justify-center transition-colors shadow-sm"
|
||||
>
|
||||
{m.search_button()}
|
||||
</button>
|
||||
<div className="absolute inset-y-1.5 right-1.5 flex items-center gap-1">
|
||||
{(searchInput || attachedImage) && (
|
||||
<button
|
||||
type="button"
|
||||
aria-label={attachedImage ? m.image_search_remove() : m.clear_search()}
|
||||
onClick={() => {
|
||||
setAttachedImage(null)
|
||||
setImageSubmitted(false)
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
}}
|
||||
className="rounded-md p-1 text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<X className="size-4" />
|
||||
</button>
|
||||
)}
|
||||
{isSemantic && semanticSearchEnabled && (
|
||||
<SearchImagePicker
|
||||
onSelect={(image) => {
|
||||
setAttachedImage(image)
|
||||
setImageSubmitted(false)
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<button
|
||||
type="submit"
|
||||
className="flex h-full items-center justify-center rounded-lg bg-primary px-4 text-xs font-semibold text-primary-foreground transition-colors hover:bg-primary/90"
|
||||
>
|
||||
{m.search_button()}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3 py-1">
|
||||
@@ -286,6 +324,8 @@ export function SearchFilterDialog({
|
||||
setIsSemantic(checked)
|
||||
setSearchInput('')
|
||||
setTriggerQuery('')
|
||||
setAttachedImage(null)
|
||||
setImageSubmitted(false)
|
||||
setConditions([])
|
||||
}}
|
||||
disabled={!semanticSearchEnabled}
|
||||
@@ -380,9 +420,9 @@ export function SearchFilterDialog({
|
||||
<Search className="w-10 h-10 text-muted-foreground/30 mb-2" />
|
||||
<h3 className="text-sm font-semibold text-foreground/80">{m.ready_to_search()}</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
{m.type_query_instruction()}
|
||||
{attachedImage ? m.image_search_submit_instruction() : m.type_query_instruction()}
|
||||
</p>
|
||||
{isSemantic && (
|
||||
{isSemantic && !attachedImage && (
|
||||
<p className="text-xs text-muted-foreground/80 max-w-md mt-4 mx-auto border-t border-border/60 pt-3">
|
||||
{m.semantic_search_note()}
|
||||
</p>
|
||||
@@ -420,42 +460,16 @@ export function SearchFilterDialog({
|
||||
{m.no_records_matched()}
|
||||
</h3>
|
||||
<p className="text-xs text-muted-foreground max-w-sm mt-1 mx-auto">
|
||||
{m.try_adjusting_spelling()}
|
||||
{!attachedImage && m.try_adjusting_spelling()}
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{flattenedResults.map((record) => {
|
||||
const itemKey =
|
||||
record.startTime != null && record.endTime != null
|
||||
? `${record.id}-${record.startTime}-${record.endTime}`
|
||||
: record.id
|
||||
if (record.type === 'folder') {
|
||||
return (
|
||||
<FolderCard
|
||||
key={itemKey}
|
||||
item={record}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => handleResultClick(record)}
|
||||
/>
|
||||
)
|
||||
}
|
||||
return (
|
||||
<FileCard
|
||||
key={itemKey}
|
||||
teamId={teamId}
|
||||
item={record}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => handleResultClick(record)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
<SearchResultCards
|
||||
results={flattenedResults}
|
||||
teamId={teamId}
|
||||
projectId={projectId}
|
||||
/>
|
||||
{(hasNextPage || isFetchingNextPage) && (
|
||||
<div ref={ref} className="p-4 flex justify-center items-center">
|
||||
<Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import { MAX_SEARCH_IMAGE_BASE64_LENGTH } from '@shumai/dtos'
|
||||
import { ImagePlus, Loader2 } from 'lucide-react'
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ulid } from 'ulid'
|
||||
import { Button } from '@/ui/components/ui/button'
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from '@/ui/components/ui/dialog'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
|
||||
export interface SearchImage {
|
||||
id: string
|
||||
name: string
|
||||
base64: string
|
||||
}
|
||||
|
||||
async function resizeImage(file: File): Promise<SearchImage> {
|
||||
if (file.type && !file.type.startsWith('image/')) throw new Error('Invalid file type')
|
||||
|
||||
const bitmap = await createImageBitmap(file)
|
||||
try {
|
||||
const landscape = bitmap.width >= bitmap.height
|
||||
const scale = Math.min(
|
||||
1,
|
||||
(landscape ? 1280 : 720) / bitmap.width,
|
||||
(landscape ? 720 : 1280) / bitmap.height,
|
||||
)
|
||||
const canvas = document.createElement('canvas')
|
||||
canvas.width = Math.max(1, Math.round(bitmap.width * scale))
|
||||
canvas.height = Math.max(1, Math.round(bitmap.height * scale))
|
||||
const context = canvas.getContext('2d')
|
||||
if (!context) throw new Error('Unable to resize image')
|
||||
|
||||
context.fillStyle = '#fff'
|
||||
context.fillRect(0, 0, canvas.width, canvas.height)
|
||||
context.drawImage(bitmap, 0, 0, canvas.width, canvas.height)
|
||||
const dataUrl = canvas.toDataURL('image/jpeg', 0.85)
|
||||
const base64 = dataUrl.split(',')[1]
|
||||
if (!base64 || base64.length > MAX_SEARCH_IMAGE_BASE64_LENGTH) {
|
||||
throw new Error('Invalid resized image')
|
||||
}
|
||||
return { id: ulid(), name: file.name, base64 }
|
||||
} finally {
|
||||
bitmap.close()
|
||||
}
|
||||
}
|
||||
|
||||
export function SearchImagePicker({ onSelect }: { onSelect: (image: SearchImage) => void }) {
|
||||
const [open, setOpen] = useState(false)
|
||||
const [error, setError] = useState(false)
|
||||
const [processing, setProcessing] = useState(false)
|
||||
const input = useRef<HTMLInputElement>(null)
|
||||
const pending = useRef<AbortController | null>(null)
|
||||
|
||||
useEffect(() => () => pending.current?.abort(), [])
|
||||
|
||||
function setPickerOpen(next: boolean) {
|
||||
if (!next) {
|
||||
pending.current?.abort()
|
||||
pending.current = null
|
||||
setError(false)
|
||||
setProcessing(false)
|
||||
}
|
||||
setOpen(next)
|
||||
}
|
||||
|
||||
async function selectFile(file: File) {
|
||||
if (pending.current) return
|
||||
const controller = new AbortController()
|
||||
pending.current = controller
|
||||
setError(false)
|
||||
setProcessing(true)
|
||||
try {
|
||||
const image = await resizeImage(file)
|
||||
if (controller.signal.aborted) return
|
||||
onSelect(image)
|
||||
setPickerOpen(false)
|
||||
} catch {
|
||||
if (!controller.signal.aborted) setError(true)
|
||||
} finally {
|
||||
if (pending.current === controller) {
|
||||
pending.current = null
|
||||
setProcessing(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setPickerOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button type="button" variant="ghost" size="icon-sm" aria-label={m.image_search_attach()}>
|
||||
<ImagePlus className="size-4" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent
|
||||
onPaste={(event) => {
|
||||
event.stopPropagation()
|
||||
const image = Array.from(event.clipboardData.files).find((file) =>
|
||||
file.type.startsWith('image/'),
|
||||
)
|
||||
if (!image) return
|
||||
event.preventDefault()
|
||||
void selectFile(image)
|
||||
}}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{m.image_search_attach()}</DialogTitle>
|
||||
<DialogDescription>{m.image_search_select_description()}</DialogDescription>
|
||||
</DialogHeader>
|
||||
<input
|
||||
ref={input}
|
||||
type="file"
|
||||
accept="image/*"
|
||||
hidden
|
||||
onChange={(event) => {
|
||||
const file = event.currentTarget.files?.[0]
|
||||
event.currentTarget.value = ''
|
||||
if (file) void selectFile(file)
|
||||
}}
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
className="h-28 w-full border-dashed"
|
||||
disabled={processing}
|
||||
onClick={() => input.current?.click()}
|
||||
onDragOver={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
}}
|
||||
onDrop={(event) => {
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
const files = event.dataTransfer.files
|
||||
if (files.length === 1) void selectFile(files[0])
|
||||
else setError(true)
|
||||
}}
|
||||
>
|
||||
{processing && <Loader2 className="size-4 animate-spin" />}
|
||||
{m.image_search_choose_image()}
|
||||
</Button>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{m.image_search_invalid_image()}
|
||||
</p>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { AssetInfo } from '@shumai/dtos'
|
||||
import { FileCard } from '@/ui/components/file-browser/file-card'
|
||||
import { FolderCard } from '@/ui/components/file-browser/folder-card'
|
||||
|
||||
export function SearchResultCards({
|
||||
results,
|
||||
teamId,
|
||||
projectId,
|
||||
}: {
|
||||
results: AssetInfo[]
|
||||
teamId: string
|
||||
projectId: string
|
||||
}) {
|
||||
function openResult(item: AssetInfo) {
|
||||
const projectPath = `/projects/${projectId}`
|
||||
if (item.type === 'folder') {
|
||||
window.open(`${projectPath}/folders/${item.id}`, '_blank', 'noopener,noreferrer')
|
||||
return
|
||||
}
|
||||
const fileId = item.versionStack?.id ?? item.id
|
||||
const query = item.startTime != null && item.startTime > 0 ? `?start=${item.startTime}` : ''
|
||||
window.open(`${projectPath}/files/${fileId}${query}`, '_blank', 'noopener,noreferrer')
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-4 gap-4">
|
||||
{results.map((item) => {
|
||||
const key =
|
||||
item.startTime != null && item.endTime != null
|
||||
? `${item.id}-${item.startTime}-${item.endTime}`
|
||||
: item.id
|
||||
return item.type === 'folder' ? (
|
||||
<FolderCard
|
||||
key={key}
|
||||
item={item}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => openResult(item)}
|
||||
/>
|
||||
) : (
|
||||
<FileCard
|
||||
key={key}
|
||||
teamId={teamId}
|
||||
item={item}
|
||||
hideCheckbox
|
||||
hideActions
|
||||
disabled
|
||||
onSelect={() => openResult(item)}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { client } from '@/ui/api/client'
|
||||
import { m } from '@/ui/paraglide/messages.js'
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
|
||||
export function useSemanticSearchEnabled(teamId: string, enabled: boolean): boolean {
|
||||
const { data } = useQuery({
|
||||
queryKey: ['team-settings', teamId],
|
||||
queryFn: async () => {
|
||||
const res = await client.api.teams[':teamId'].settings.$get({ param: { teamId } })
|
||||
if (!res.ok) throw new Error(m.failed_load_settings())
|
||||
return await res.json()
|
||||
},
|
||||
enabled,
|
||||
})
|
||||
|
||||
return data?.semanticSearchEnabled ?? false
|
||||
}
|
||||
Reference in New Issue
Block a user