(feat): add gif picker & media saving
This commit is contained in:
parent
4a0f9e3b58
commit
87e4a158e3
8 changed files with 873 additions and 25 deletions
|
|
@ -15,16 +15,17 @@
|
|||
"build": "tsc -p tsconfig.json --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tanstack/pacer": "^0.21.1",
|
||||
"@tanstack/react-query": "^5.0.0",
|
||||
"@tanstack/react-router": "^1.0.0",
|
||||
"@tanstack/react-virtual": "^3.0.0",
|
||||
"@tensamin/crypto": "workspace:*",
|
||||
"@tensamin/ttp": "workspace:*",
|
||||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"@tensamin/markdown": "workspace:*",
|
||||
"@tensamin/shared": "workspace:*",
|
||||
"@tensamin/storage": "workspace:*",
|
||||
"@tensamin/ttp": "workspace:*",
|
||||
"@tensamin/ui": "*",
|
||||
"@tensamin/user": "workspace:*",
|
||||
"lucide-react": "^1.14.0",
|
||||
"react": "^19.2.0",
|
||||
"react-dom": "^19.2.0",
|
||||
|
|
|
|||
638
packages/chat/src/components/gifPicker.tsx
Normal file
638
packages/chat/src/components/gifPicker.tsx
Normal file
|
|
@ -0,0 +1,638 @@
|
|||
import { Debouncer } from "@tanstack/pacer";
|
||||
import { useInfiniteQuery } from "@tanstack/react-query";
|
||||
import {
|
||||
Button,
|
||||
Input,
|
||||
Tabs,
|
||||
TabsContent,
|
||||
TabsList,
|
||||
TabsTrigger,
|
||||
} from "@tensamin/ui";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { Loader2, Search } from "lucide-react";
|
||||
import MediaSaveButton from "./mediaSaveButton";
|
||||
import React, {
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
startTransition,
|
||||
} from "react";
|
||||
|
||||
const klipyApiKey =
|
||||
"KzyghnvdlaHjJuDycVx6rLIEu5eaacPyFERieoI7L8UWLt2rnJloL45UL5MVc9IG";
|
||||
const klipyBaseUrl = "https://api.klipy.com/api/v1";
|
||||
const pageSize = 24;
|
||||
const minColumnWidth = 200;
|
||||
|
||||
function getColumnCount(width: number, itemCount: number) {
|
||||
return Math.max(
|
||||
1,
|
||||
Math.min(itemCount || 1, Math.floor(width / minColumnWidth)),
|
||||
);
|
||||
}
|
||||
|
||||
type KlipyKind = "gif" | "meme";
|
||||
|
||||
type KlipyMediaFile = {
|
||||
url?: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
|
||||
type KlipyMediaFormats = Record<string, KlipyMediaFile | undefined>;
|
||||
|
||||
type KlipyItem = {
|
||||
id: number | string;
|
||||
title?: string;
|
||||
file?: Record<string, KlipyMediaFormats | undefined>;
|
||||
blur_preview?: string;
|
||||
};
|
||||
|
||||
type KlipyPage = {
|
||||
items: KlipyItem[];
|
||||
currentPage: number;
|
||||
hasNext: boolean;
|
||||
};
|
||||
|
||||
type KlipyResponse = {
|
||||
data?: {
|
||||
data?: KlipyItem[];
|
||||
current_page?: number;
|
||||
has_next?: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
type PickerMedia = {
|
||||
key: React.Key;
|
||||
url: string;
|
||||
alt: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
};
|
||||
|
||||
function distributeByHeight<T>(
|
||||
items: T[],
|
||||
columnCount: number,
|
||||
getAspectRatio: (item: T) => number,
|
||||
) {
|
||||
const columns = Array.from({ length: columnCount }, () => [] as T[]);
|
||||
const columnHeights = Array.from({ length: columnCount }, () => 0);
|
||||
|
||||
for (const item of items) {
|
||||
const shortestColumnIndex = columnHeights.indexOf(
|
||||
Math.min(...columnHeights),
|
||||
);
|
||||
|
||||
columns[shortestColumnIndex].push(item);
|
||||
columnHeights[shortestColumnIndex] += getAspectRatio(item);
|
||||
}
|
||||
|
||||
return columns;
|
||||
}
|
||||
|
||||
function getKlipyPath(kind: KlipyKind) {
|
||||
const resource = kind === "gif" ? "gifs" : "static-memes";
|
||||
|
||||
return `${resource}/search`;
|
||||
}
|
||||
|
||||
async function fetchKlipyPage({
|
||||
kind,
|
||||
page,
|
||||
search,
|
||||
}: {
|
||||
kind: KlipyKind;
|
||||
page: number;
|
||||
search: string;
|
||||
}): Promise<KlipyPage> {
|
||||
const params = new URLSearchParams({
|
||||
page: String(page),
|
||||
per_page: String(pageSize),
|
||||
content_filter: "medium",
|
||||
});
|
||||
|
||||
if (search !== "") {
|
||||
params.set("q", search);
|
||||
}
|
||||
|
||||
if (kind === "gif") {
|
||||
params.set("format_filter", "gif,webp");
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`${klipyBaseUrl}/${klipyApiKey}/${getKlipyPath(kind)}?${params}`,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Klipy request failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
const body = (await response.json()) as KlipyResponse;
|
||||
const data = body.data;
|
||||
|
||||
return {
|
||||
items: data?.data ?? [],
|
||||
currentPage: data?.current_page ?? page,
|
||||
hasNext: data?.has_next ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
function getFormat(item: KlipyItem, size: string, format: string) {
|
||||
return item.file?.[size]?.[format];
|
||||
}
|
||||
|
||||
function pickDisplayMedia(kind: KlipyKind, item: KlipyItem) {
|
||||
if (kind === "gif") {
|
||||
return (
|
||||
getFormat(item, "sm", "webp") ??
|
||||
getFormat(item, "md", "webp") ??
|
||||
getFormat(item, "sm", "gif") ??
|
||||
getFormat(item, "md", "gif") ??
|
||||
getFormat(item, "hd", "webp") ??
|
||||
getFormat(item, "hd", "gif")
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
getFormat(item, "sm", "webp") ??
|
||||
getFormat(item, "md", "webp") ??
|
||||
getFormat(item, "sm", "png") ??
|
||||
getFormat(item, "md", "png") ??
|
||||
getFormat(item, "hd", "webp") ??
|
||||
getFormat(item, "hd", "png")
|
||||
);
|
||||
}
|
||||
|
||||
function pickSelectionUrl(kind: KlipyKind, item: KlipyItem) {
|
||||
if (kind === "gif") {
|
||||
return (
|
||||
getFormat(item, "md", "gif")?.url ??
|
||||
getFormat(item, "sm", "gif")?.url ??
|
||||
getFormat(item, "hd", "gif")?.url
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
getFormat(item, "md", "png")?.url ??
|
||||
getFormat(item, "md", "webp")?.url ??
|
||||
getFormat(item, "sm", "png")?.url ??
|
||||
getFormat(item, "sm", "webp")?.url ??
|
||||
getFormat(item, "hd", "png")?.url ??
|
||||
getFormat(item, "hd", "webp")?.url
|
||||
);
|
||||
}
|
||||
|
||||
function useMeasuredWidth() {
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
const [scrollWidth, setScrollWidth] = useState(0);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const element = scrollRef.current;
|
||||
|
||||
if (!element || typeof ResizeObserver === "undefined") return;
|
||||
|
||||
const updateWidth = () => setScrollWidth(element.clientWidth);
|
||||
const observer = new ResizeObserver(updateWidth);
|
||||
|
||||
updateWidth();
|
||||
observer.observe(element);
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return [scrollRef, scrollWidth] as const;
|
||||
}
|
||||
|
||||
function useImageSizes(urls: string[]) {
|
||||
const [sizes, setSizes] = useState<
|
||||
Record<string, { width: number; height: number }>
|
||||
>({});
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
for (const url of urls) {
|
||||
if (sizes[url]) continue;
|
||||
|
||||
const image = new Image();
|
||||
|
||||
image.onload = () => {
|
||||
if (!active) return;
|
||||
|
||||
setSizes((current) => ({
|
||||
...current,
|
||||
[url]: {
|
||||
width: image.naturalWidth,
|
||||
height: image.naturalHeight,
|
||||
},
|
||||
}));
|
||||
};
|
||||
image.src = url;
|
||||
}
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
};
|
||||
}, [sizes, urls]);
|
||||
|
||||
return sizes;
|
||||
}
|
||||
|
||||
function MediaGrid({
|
||||
hasNextPage = false,
|
||||
isFetchingNextPage = false,
|
||||
items,
|
||||
onLoadMore,
|
||||
onSelect,
|
||||
resizeWidth,
|
||||
}: {
|
||||
hasNextPage?: boolean;
|
||||
isFetchingNextPage?: boolean;
|
||||
items: PickerMedia[];
|
||||
onLoadMore?: () => void;
|
||||
onSelect: (url: string) => void;
|
||||
resizeWidth?: number;
|
||||
}) {
|
||||
const [scrollRef, measuredWidth] = useMeasuredWidth();
|
||||
const columnWidth = resizeWidth ?? measuredWidth;
|
||||
const columnCount = getColumnCount(columnWidth, items.length);
|
||||
const columns = distributeByHeight(items, columnCount, (item) => {
|
||||
if (!item.width || !item.height) return 1;
|
||||
|
||||
return item.height / item.width;
|
||||
});
|
||||
|
||||
function handleScroll(event: React.UIEvent<HTMLDivElement>) {
|
||||
const element = event.currentTarget;
|
||||
const distanceFromBottom =
|
||||
element.scrollHeight - element.scrollTop - element.clientHeight;
|
||||
|
||||
if (
|
||||
distanceFromBottom > 240 ||
|
||||
!hasNextPage ||
|
||||
isFetchingNextPage ||
|
||||
!onLoadMore
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
onLoadMore();
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
const element = scrollRef.current;
|
||||
|
||||
if (!element || !hasNextPage || isFetchingNextPage || !onLoadMore) return;
|
||||
|
||||
const distanceFromBottom =
|
||||
element.scrollHeight - element.scrollTop - element.clientHeight;
|
||||
|
||||
if (distanceFromBottom <= 240) {
|
||||
onLoadMore();
|
||||
}
|
||||
}, [
|
||||
columnCount,
|
||||
hasNextPage,
|
||||
isFetchingNextPage,
|
||||
items.length,
|
||||
onLoadMore,
|
||||
scrollRef,
|
||||
]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={scrollRef}
|
||||
className="min-h-0 w-full flex-1 overflow-y-auto pr-1"
|
||||
onScroll={handleScroll}
|
||||
>
|
||||
<div className="flex w-full items-start gap-2">
|
||||
{columns.map((column, columnIndex) => (
|
||||
<div key={columnIndex} className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
{column.map((item) => (
|
||||
<button
|
||||
key={item.key}
|
||||
className="group overflow-hidden rounded-lg text-left transition hover:border-foreground/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onSelect(item.url)}
|
||||
type="button"
|
||||
>
|
||||
<img
|
||||
alt={item.alt}
|
||||
className="block h-auto w-full object-contain"
|
||||
height={item.height}
|
||||
loading="lazy"
|
||||
src={item.url}
|
||||
width={item.width}
|
||||
/>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div>
|
||||
{hasNextPage ? (
|
||||
<div className="flex h-20 items-center justify-center text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
Loading more...
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function KlipyPanel({
|
||||
kind,
|
||||
onSelect,
|
||||
resizeWidth,
|
||||
searchString,
|
||||
}: {
|
||||
kind: KlipyKind;
|
||||
onSelect: (url: string) => void;
|
||||
resizeWidth?: number;
|
||||
searchString: string;
|
||||
}) {
|
||||
const query = useInfiniteQuery({
|
||||
queryKey: ["klipy", kind, searchString],
|
||||
initialPageParam: 1,
|
||||
enabled: searchString !== "",
|
||||
queryFn: ({ pageParam }) =>
|
||||
fetchKlipyPage({
|
||||
kind,
|
||||
page: Number(pageParam),
|
||||
search: searchString,
|
||||
}),
|
||||
getNextPageParam: (lastPage) =>
|
||||
lastPage.hasNext ? lastPage.currentPage + 1 : undefined,
|
||||
});
|
||||
const items: PickerMedia[] =
|
||||
query.data?.pages.flatMap((page) =>
|
||||
page.items.flatMap((item) => {
|
||||
const displayMedia = pickDisplayMedia(kind, item);
|
||||
const selectionUrl = pickSelectionUrl(kind, item);
|
||||
|
||||
if (!displayMedia?.url || !selectionUrl) return [];
|
||||
|
||||
return [
|
||||
{
|
||||
key: item.id,
|
||||
url: selectionUrl,
|
||||
alt: item.title ?? "Klipy result",
|
||||
width: displayMedia.width,
|
||||
height: displayMedia.height,
|
||||
},
|
||||
];
|
||||
}),
|
||||
) ?? [];
|
||||
|
||||
if (searchString === "") {
|
||||
return (
|
||||
<div className="flex h-full w-full flex-col items-center justify-center gap-5 text-center text-muted-foreground">
|
||||
<Search className="size-12" />
|
||||
<p className="w-50 text-lg text-foreground">
|
||||
{kind === "gif" && 'Try searching for "Funny cat"'}
|
||||
{kind === "meme" &&
|
||||
'Try searching for "Spiderman pointing at Spiderman"'}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (query.isLoading) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-muted-foreground">
|
||||
<Loader2 className="mr-2 size-4 animate-spin" />
|
||||
Loading...
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (query.isError) {
|
||||
return (
|
||||
<div className="flex h-full flex-col items-center justify-center gap-2 text-center text-muted-foreground">
|
||||
<p>Failed to load {kind === "gif" ? "GIFs" : "memes"}.</p>
|
||||
<Button
|
||||
onClick={() => void query.refetch()}
|
||||
size="sm"
|
||||
variant="secondary"
|
||||
>
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-center text-muted-foreground">
|
||||
No {kind === "gif" ? "GIFs" : "memes"} found.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MediaGrid
|
||||
hasNextPage={query.hasNextPage}
|
||||
isFetchingNextPage={query.isFetchingNextPage}
|
||||
items={items}
|
||||
onLoadMore={() => void query.fetchNextPage()}
|
||||
onSelect={onSelect}
|
||||
resizeWidth={resizeWidth}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function SavedPanel({
|
||||
onSelect,
|
||||
onSavedMediaChange,
|
||||
resizeWidth,
|
||||
urls,
|
||||
}: {
|
||||
onSelect: (url: string) => void;
|
||||
onSavedMediaChange: (savedMedia: string[]) => void;
|
||||
resizeWidth?: number;
|
||||
urls: string[];
|
||||
}) {
|
||||
const [scrollRef, measuredWidth] = useMeasuredWidth();
|
||||
const imageSizes = useImageSizes(urls);
|
||||
const columnWidth = resizeWidth ?? measuredWidth;
|
||||
const columnCount = getColumnCount(columnWidth, urls.length);
|
||||
const columns = distributeByHeight(urls, columnCount, (url) => {
|
||||
const size = imageSizes[url];
|
||||
|
||||
if (!size?.width || !size.height) return 1;
|
||||
|
||||
return size.height / size.width;
|
||||
});
|
||||
|
||||
if (urls.length === 0) {
|
||||
return (
|
||||
<div className="flex h-full items-center justify-center text-center text-muted-foreground">
|
||||
Saved media will appear here.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div ref={scrollRef} className="min-h-0 w-full flex-1 overflow-y-auto pr-1">
|
||||
<div className="flex w-full items-start gap-2">
|
||||
{columns.map((column, columnIndex) => (
|
||||
<div key={columnIndex} className="flex min-w-0 flex-1 flex-col gap-2">
|
||||
{column.map((url) => {
|
||||
const size = imageSizes[url];
|
||||
|
||||
return (
|
||||
<div
|
||||
key={url}
|
||||
className="group relative overflow-hidden rounded-lg transition hover:border-foreground/30"
|
||||
>
|
||||
<button
|
||||
className="block w-full text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
|
||||
onClick={() => onSelect(url)}
|
||||
type="button"
|
||||
>
|
||||
<img
|
||||
alt="Saved media"
|
||||
className="block h-auto w-full object-contain"
|
||||
height={size?.height}
|
||||
loading="lazy"
|
||||
src={url}
|
||||
width={size?.width}
|
||||
/>
|
||||
</button>
|
||||
<MediaSaveButton
|
||||
ariaLabel="Unsave media"
|
||||
defaultSaved
|
||||
onSavedMediaChange={onSavedMediaChange}
|
||||
url={url}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function GifPicker({
|
||||
onSelect,
|
||||
resizeHeight,
|
||||
resizeWidth,
|
||||
}: {
|
||||
onSelect: (url: string) => void;
|
||||
resizeHeight?: number;
|
||||
resizeWidth?: number;
|
||||
}) {
|
||||
const { load, save } = useStorage();
|
||||
const [tab, setTab] = useState<KlipyKind | "saved">("gif");
|
||||
const [searchString, setSearchString] = useState("");
|
||||
const [debouncedSearchString, setDebouncedSearchString] = useState("");
|
||||
const [savedMedia, setSavedMedia] = useState<string[]>([]);
|
||||
const didLoadLastTabRef = useRef(false);
|
||||
const searchDebouncerRef = useRef<Debouncer<(value: string) => void> | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
if (searchDebouncerRef.current === null) {
|
||||
searchDebouncerRef.current = new Debouncer(
|
||||
(value) => {
|
||||
startTransition(() => {
|
||||
setDebouncedSearchString(value.trim());
|
||||
});
|
||||
},
|
||||
{ wait: 300 },
|
||||
);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
searchDebouncerRef.current?.cancel();
|
||||
};
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (tab !== "saved") return;
|
||||
|
||||
void load("chat_picker_saved_media").then(setSavedMedia);
|
||||
}, [load, tab]);
|
||||
|
||||
useEffect(() => {
|
||||
void load("chat_picker_last_tab").then((savedTab) => {
|
||||
setTab(savedTab);
|
||||
didLoadLastTabRef.current = true;
|
||||
});
|
||||
}, [load]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!didLoadLastTabRef.current) return;
|
||||
|
||||
void save("chat_picker_last_tab", tab);
|
||||
}, [save, tab]);
|
||||
|
||||
function handleTabChange(nextTab: string) {
|
||||
if (nextTab !== "gif" && nextTab !== "meme" && nextTab !== "saved") return;
|
||||
|
||||
setTab(nextTab);
|
||||
}
|
||||
|
||||
function handleSearchChange(event: React.ChangeEvent<HTMLInputElement>) {
|
||||
const nextValue = event.target.value;
|
||||
|
||||
setSearchString(nextValue);
|
||||
searchDebouncerRef.current?.maybeExecute(nextValue);
|
||||
}
|
||||
|
||||
return (
|
||||
<Tabs
|
||||
className="h-full min-h-0 w-full overflow-hidden"
|
||||
style={resizeHeight ? { height: `${resizeHeight}px` } : undefined}
|
||||
value={tab}
|
||||
onValueChange={handleTabChange}
|
||||
>
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger value="gif">GIFs</TabsTrigger>
|
||||
<TabsTrigger value="meme">Memes</TabsTrigger>
|
||||
<TabsTrigger value="saved">Saved</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="gif" className="flex min-h-0 w-full flex-col gap-2">
|
||||
<Input
|
||||
placeholder="Search Klipy..."
|
||||
value={searchString}
|
||||
onChange={handleSearchChange}
|
||||
/>
|
||||
<KlipyPanel
|
||||
kind="gif"
|
||||
onSelect={onSelect}
|
||||
resizeWidth={resizeWidth}
|
||||
searchString={debouncedSearchString}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent value="meme" className="flex min-h-0 w-full flex-col gap-2">
|
||||
<Input
|
||||
placeholder="Search Klipy..."
|
||||
value={searchString}
|
||||
onChange={handleSearchChange}
|
||||
/>
|
||||
<KlipyPanel
|
||||
kind="meme"
|
||||
onSelect={onSelect}
|
||||
resizeWidth={resizeWidth}
|
||||
searchString={debouncedSearchString}
|
||||
/>
|
||||
</TabsContent>
|
||||
<TabsContent
|
||||
value="saved"
|
||||
className="flex min-h-0 w-full flex-col overflow-hidden"
|
||||
>
|
||||
<SavedPanel
|
||||
onSelect={onSelect}
|
||||
onSavedMediaChange={setSavedMedia}
|
||||
resizeWidth={resizeWidth}
|
||||
urls={savedMedia}
|
||||
/>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,16 +1,23 @@
|
|||
import Input from "@tensamin/markdown/input";
|
||||
import { Card, CardHeader } from "@tensamin/ui";
|
||||
import {
|
||||
Card,
|
||||
CardHeader,
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from "@tensamin/ui";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import * as React from "react";
|
||||
import { Button } from "@tensamin/ui";
|
||||
|
||||
import { Plus, Laugh, Clapperboard } from "lucide-react";
|
||||
import { Plus, Laugh, FileVideo } from "lucide-react";
|
||||
import { useChat } from "../context";
|
||||
import { useTTP } from "@tensamin/ttp";
|
||||
import { log, toast } from "@tensamin/shared/log";
|
||||
import { cn, useIsMobile } from "@tensamin/ui";
|
||||
import { encryptText } from "@tensamin/crypto/worker";
|
||||
import { useSession } from "@tensamin/storage/session";
|
||||
import GifPicker from "./gifPicker";
|
||||
|
||||
export default function InputComponent({
|
||||
value,
|
||||
|
|
@ -23,8 +30,14 @@ export default function InputComponent({
|
|||
|
||||
const { send } = useTTP();
|
||||
const { addLiveMessage, sharedSecret, userId, inputBoxRef } = useChat();
|
||||
const { load } = useStorage();
|
||||
const { load, save } = useStorage();
|
||||
const { moveUserIdToTop } = useSession();
|
||||
const gifPopoverRef = React.useRef<HTMLDivElement>(null);
|
||||
const [gifPopoverOpen, setGifPopoverOpen] = React.useState(false);
|
||||
const [gifPopoverSize, setGifPopoverSize] = React.useState<{
|
||||
width: number;
|
||||
height: number;
|
||||
}>();
|
||||
|
||||
React.useEffect(() => {
|
||||
void load("settings.reverse_enter_behavior").then((shouldInvert) => {
|
||||
|
|
@ -32,16 +45,19 @@ export default function InputComponent({
|
|||
});
|
||||
}, [load]);
|
||||
|
||||
/**
|
||||
* Executes handleSubmit.
|
||||
* @param none This function has no parameters.
|
||||
* @returns unknown.
|
||||
*/
|
||||
async function handleSubmit() {
|
||||
if (value.trim() === "") return;
|
||||
React.useEffect(() => {
|
||||
void load("chat_picker_size").then((size) => {
|
||||
if (size) {
|
||||
setGifPopoverSize(size);
|
||||
}
|
||||
});
|
||||
}, [load]);
|
||||
|
||||
async function handleSubmit(content = value, preserveContent = false) {
|
||||
if (content.trim() === "") return;
|
||||
|
||||
const time = Date.now();
|
||||
const currentValue = value;
|
||||
const currentValue = content;
|
||||
|
||||
if (!Number.isSafeInteger(userId) || userId <= 0) {
|
||||
toast("error", "No conversation selected");
|
||||
|
|
@ -82,11 +98,64 @@ export default function InputComponent({
|
|||
|
||||
moveUserIdToTop(userId);
|
||||
|
||||
setValue("");
|
||||
if (!preserveContent) {
|
||||
setValue("");
|
||||
}
|
||||
}
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
|
||||
function handleGifPopoverResizeStart(
|
||||
event: React.PointerEvent<HTMLDivElement>,
|
||||
) {
|
||||
const popover = gifPopoverRef.current;
|
||||
|
||||
if (!popover) return;
|
||||
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
|
||||
const rect = popover.getBoundingClientRect();
|
||||
const startX = event.clientX;
|
||||
const startY = event.clientY;
|
||||
const startWidth = rect.width;
|
||||
const startHeight = rect.height;
|
||||
const minSize = 40;
|
||||
const maxSize = 720;
|
||||
|
||||
function clampSize(size: number) {
|
||||
return Math.min(Math.max(size, minSize), maxSize);
|
||||
}
|
||||
|
||||
function handlePointerMove(moveEvent: PointerEvent) {
|
||||
const nextSize = {
|
||||
width: clampSize(startWidth + startX - moveEvent.clientX),
|
||||
height: clampSize(startHeight + startY - moveEvent.clientY),
|
||||
};
|
||||
|
||||
setGifPopoverSize(nextSize);
|
||||
}
|
||||
|
||||
function handlePointerUp() {
|
||||
const popover = gifPopoverRef.current;
|
||||
|
||||
if (popover) {
|
||||
const rect = popover.getBoundingClientRect();
|
||||
|
||||
void save("chat_picker_size", {
|
||||
width: clampSize(rect.width),
|
||||
height: clampSize(rect.height),
|
||||
});
|
||||
}
|
||||
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
}
|
||||
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
ref={inputBoxRef}
|
||||
|
|
@ -119,9 +188,38 @@ export default function InputComponent({
|
|||
<Button className="w-9 h-9 p-0" variant="ghost">
|
||||
<Laugh size={20} />
|
||||
</Button>
|
||||
<Button className="w-9 h-9 p-0" variant="ghost">
|
||||
<Clapperboard size={20} />
|
||||
</Button>
|
||||
<Popover open={gifPopoverOpen} onOpenChange={setGifPopoverOpen}>
|
||||
<PopoverTrigger
|
||||
render={
|
||||
<Button className="w-9 h-9 p-0" variant="ghost">
|
||||
<FileVideo size={20} />
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<PopoverContent
|
||||
ref={gifPopoverRef}
|
||||
className="relative min-h-80 max-h-180 min-w-80 max-w-180 overflow-hidden"
|
||||
onTouchMoveCapture={(event) => event.stopPropagation()}
|
||||
onWheelCapture={(event) => event.stopPropagation()}
|
||||
style={{
|
||||
...gifPopoverSize,
|
||||
maxHeight: gifPopoverSize?.height,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
className="absolute left-0 top-0 z-10 h-4 w-4 cursor-nwse-resize"
|
||||
onPointerDown={handleGifPopoverResizeStart}
|
||||
/>
|
||||
<GifPicker
|
||||
resizeHeight={gifPopoverSize?.height}
|
||||
resizeWidth={gifPopoverSize?.width}
|
||||
onSelect={(url) => {
|
||||
void handleSubmit(url, true);
|
||||
setGifPopoverOpen(false);
|
||||
}}
|
||||
/>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import { useStorage } from "@tensamin/storage/context";
|
|||
import { Tooltip, TooltipContent, TooltipTrigger } from "@tensamin/ui";
|
||||
import { TriangleAlert } from "lucide-react";
|
||||
import { useState, useMemo, useEffect } from "react";
|
||||
import MediaSaveButton from "./mediaSaveButton";
|
||||
|
||||
export default function Media({ link }: { link: string }) {
|
||||
const { load } = useStorage();
|
||||
|
|
@ -16,15 +17,19 @@ export default function Media({ link }: { link: string }) {
|
|||
}, [load]);
|
||||
|
||||
return trustedDomains.includes(hostname) ? (
|
||||
<>
|
||||
{hidden && <Text value={link} />}
|
||||
<div className="group relative inline-block">
|
||||
{hidden ? (
|
||||
<Text value={link} />
|
||||
) : (
|
||||
<MediaSaveButton className="top-2" url={link} />
|
||||
)}
|
||||
<img
|
||||
src={link}
|
||||
hidden={hidden}
|
||||
onLoad={() => setHidden(false)}
|
||||
className="max-h-70 max-w-70 py-1 rounded-lg"
|
||||
/>
|
||||
</>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-1 items-center">
|
||||
<Tooltip>
|
||||
|
|
@ -32,8 +37,8 @@ export default function Media({ link }: { link: string }) {
|
|||
render={<TriangleAlert className="size-4 stroke-yellow-400" />}
|
||||
/>
|
||||
<TooltipContent>
|
||||
Link embeds can expose your ip address. You can configure trusted
|
||||
domains in the settings.
|
||||
Link embeds can get your IP-Address! You can configure trusted domains
|
||||
in the settings.
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<Text value={link} />
|
||||
|
|
|
|||
63
packages/chat/src/components/mediaSaveButton.tsx
Normal file
63
packages/chat/src/components/mediaSaveButton.tsx
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { Button, cn } from "@tensamin/ui";
|
||||
import { useStorage } from "@tensamin/storage/context";
|
||||
import { Save } from "lucide-react";
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export default function MediaSaveButton({
|
||||
ariaLabel,
|
||||
className,
|
||||
defaultSaved = false,
|
||||
onSavedMediaChange,
|
||||
url,
|
||||
}: {
|
||||
ariaLabel?: string;
|
||||
className?: string;
|
||||
defaultSaved?: boolean;
|
||||
onSavedMediaChange?: (savedMedia: string[]) => void;
|
||||
url: string;
|
||||
}) {
|
||||
const { load, save } = useStorage();
|
||||
const [savedMedia, setSavedMedia] = useState<string[] | null>(null);
|
||||
const isSaved = savedMedia ? savedMedia.includes(url) : defaultSaved;
|
||||
|
||||
useEffect(() => {
|
||||
void load("chat_picker_saved_media").then(setSavedMedia);
|
||||
}, [load]);
|
||||
|
||||
async function handleClick(event: React.MouseEvent<HTMLButtonElement>) {
|
||||
event.stopPropagation();
|
||||
|
||||
const currentSavedMedia =
|
||||
savedMedia ?? (await load("chat_picker_saved_media"));
|
||||
const nextSavedMedia = currentSavedMedia.includes(url)
|
||||
? currentSavedMedia.filter((item) => item !== url)
|
||||
: [url, ...currentSavedMedia];
|
||||
|
||||
setSavedMedia(nextSavedMedia);
|
||||
onSavedMediaChange?.(nextSavedMedia);
|
||||
void save("chat_picker_saved_media", nextSavedMedia);
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
"absolute right-1 top-1 z-10 h-9 w-9 -translate-y-2 rounded-sm bg-black opacity-0 transition-all group-hover:translate-y-0 group-hover:opacity-100",
|
||||
className,
|
||||
)}
|
||||
>
|
||||
<Button
|
||||
aria-label={ariaLabel ?? (isSaved ? "Unsave media" : "Save media")}
|
||||
className="h-full w-full rounded-sm border-0! p-0"
|
||||
onClick={handleClick}
|
||||
variant="secondary"
|
||||
>
|
||||
<Save
|
||||
className={cn(
|
||||
"size-4.5 stroke-1.5!",
|
||||
isSaved && "fill-(--primary) stroke-(--primary-foreground-alt)",
|
||||
)}
|
||||
/>
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
Reference in a new issue