consolidate gif handling, support spoilers, add missing metadata and sable api key

This commit is contained in:
7w1 authored and niki committed 2026-06-29 17:50:42 +03:00
1 parent 9dd1d0df22
commit 53ef9d69f5
11 files changed
+177 -90

No files matched your search

+1 -1
View File
@@ -48,6 +48,6 @@
"gifs": {
"proxyUrl": "gifs.sable.moe",
"klipyApiKey": "SET_YOUR_TOKEN_HERE"
"klipyApiKey": "IfeIBlDMvq0av2BcKPDuxwRqbnYRbS90yNqFHEkK2Ja207tkR5nssh3NIlJRCr76"
}
}
+11 -4
View File
@@ -165,7 +165,11 @@ const useGroups = (
return [emojiGroupItems, stickerGroupItems, gifGroupItems];
};
const useItemRenderer = (tab: EmojiBoardTab, saveStickerEmojiBandwidth: boolean) => {
const useItemRenderer = (
tab: EmojiBoardTab,
saveStickerEmojiBandwidth: boolean,
onGifSelect?: (gif: GifData, spoiler?: boolean) => void
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -448,7 +452,7 @@ type EmojiBoardProps = {
onEmojiSelect?: (unicode: string, shortcode: string) => void;
onCustomEmojiSelect?: (mxc: string, shortcode: string) => void;
onStickerSelect?: (mxc: string, shortcode: string, label: string) => void;
onGifSelect?: (gif: GifData) => void;
onGifSelect?: (gif: GifData, spoiler?: boolean) => void;
allowTextCustomEmoji?: boolean;
addToRecentEmoji?: boolean;
isFullWidth?: boolean;
@@ -550,6 +554,7 @@ export function EmojiBoard({
preview_url: preview?.url || fullRes?.url || '',
width,
height,
size: fullRes?.size || preview?.size || 0,
};
}, []);
@@ -631,7 +636,7 @@ export function EmojiBoard({
: gifGroupItems,
};
const groups = groupsByTab[tab];
const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth);
const renderItem = useItemRenderer(tab, saveStickerEmojiBandwidth, onGifSelect);
const handleOnChange: ChangeEventHandler<HTMLInputElement> = useDebounce(
useCallback(
@@ -707,7 +712,8 @@ export function EmojiBoard({
if (emojiInfo.type === EmojiType.Gif) {
const gifDataStr = targetEl.getAttribute('data-gif-data');
const gifData = gifDataStr ? JSON.parse(gifDataStr) : null;
onGifSelect?.(gifData);
const isSpoiler = targetEl.getAttribute('data-gif-spoiler') === 'true';
onGifSelect?.(gifData, isSpoiler);
}
if (!evt.altKey && !evt.shiftKey) requestClose();
};
@@ -777,6 +783,7 @@ export function EmojiBoard({
key={tab}
query={emojiResult?.query}
onChange={handleOnChange}
tab={tab}
allowTextCustomEmoji={allowTextCustomEmoji}
onTextCustomEmojiSelect={handleTextCustomEmojiSelect}
/>
@@ -9,9 +9,11 @@ import type { CSSProperties, ReactNode } from 'react';
import { useEffect, useState } from 'react';
import * as css from './styles.css';
import { useFavoriteGifs } from '$hooks/useFavoriteGifs';
import { Star, menuIcon } from '$components/icons/phosphor';
import { Star, Eye, EyeSlash, menuIcon } from '$components/icons/phosphor';
import { MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS } from '$unstable/prefixes';
import { useMatrixClient } from '$hooks/useMatrixClient';
import { useClientConfig } from '$hooks/useClientConfig';
import { getKlipyMxcUrl } from '$utils/klipy';
const ANIMATED_MIME_TYPES = new Set(['image/gif', 'image/apng']);
@@ -165,16 +167,28 @@ export function GifItem({
children: ReactNode;
}) {
const [isHovered, setIsHovered] = useState(false);
const initialFavorited = useFavoriteGifs();
const [favoritedContent, setFavoritedContent] = useState(initialFavorited);
const favoritedContent = useFavoriteGifs();
const clientConfig = useClientConfig();
const mxcUrl = gif?.url ? getKlipyMxcUrl(gif.url, clientConfig.gifs?.proxyUrl) : '';
const [favorited, setFavorited] = useState(
favoritedContent.gifs.find((v) => v.url == gif?.url) != undefined
favoritedContent.gifs.some((v) => {
const vMxc = getKlipyMxcUrl(v.url, clientConfig.gifs?.proxyUrl);
return vMxc === mxcUrl && mxcUrl !== '';
})
);
const [isSpoiler, setIsSpoiler] = useState(false);
const mx = useMatrixClient();
useEffect(() => {
setFavoritedContent(initialFavorited);
}, [initialFavorited]);
setFavorited(
favoritedContent.gifs.some((v) => {
const vMxc = getKlipyMxcUrl(v.url, clientConfig.gifs?.proxyUrl);
return vMxc === mxcUrl && mxcUrl !== '';
})
);
}, [favoritedContent, mxcUrl, clientConfig.gifs?.proxyUrl]);
return (
<Box
@@ -190,6 +204,7 @@ export function GifItem({
data-emoji-data={data}
data-emoji-shortcode={shortcode}
data-gif-data={gif ? JSON.stringify(gif) : undefined}
data-gif-spoiler={isSpoiler ? 'true' : 'false'}
onPointerEnter={() => setIsHovered(true)}
onPointerLeave={() => setIsHovered(false)}
>
@@ -206,18 +221,19 @@ export function GifItem({
title={favorited ? 'Unfavorite gif' : 'Favorite gif'}
onClick={async (e) => {
e.preventDefault();
e.stopPropagation();
if (!favorited) {
setFavorited(true);
await mx
.setAccountData(MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS, {
gifs: [...favoritedContent.gifs, gif],
gifs: [...favoritedContent.gifs, { ...gif, url: mxcUrl }],
})
.catch(() => setFavorited(false));
} else {
setFavorited(false);
await mx
.setAccountData(MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS, {
gifs: favoritedContent.gifs.filter((v) => v.url != gif.url),
gifs: favoritedContent.gifs.filter((v) => getKlipyMxcUrl(v.url, clientConfig.gifs?.proxyUrl) !== mxcUrl),
})
.catch(() => setFavorited(true));
}
@@ -228,6 +244,23 @@ export function GifItem({
color: favorited ? color.Warning.MainHover : color.Surface.OnContainer,
})}
</MenuItem>
<MenuItem
size="300"
radii="0"
fill="Soft"
variant="Secondary"
title={isSpoiler ? 'Remove spoiler' : 'Mark as spoiler'}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setIsSpoiler(!isSpoiler);
}}
>
{menuIcon(isSpoiler ? EyeSlash : Eye, {
weight: isSpoiler ? 'fill' : 'regular',
color: color.Surface.OnContainer,
})}
</MenuItem>
</Box>
</Menu>
</Box>
@@ -10,12 +10,14 @@ type SearchInputProps = {
onChange: ChangeEventHandler<HTMLInputElement>;
allowTextCustomEmoji?: boolean;
onTextCustomEmojiSelect?: (text: string) => void;
tab?: EmojiBoardTab;
};
export function SearchInput({
query,
onChange,
allowTextCustomEmoji,
onTextCustomEmojiSelect,
tab,
}: SearchInputProps) {
const inputRef = useRef<HTMLInputElement>(null);
@@ -31,11 +33,15 @@ export function SearchInput({
variant="SurfaceVariant"
size="400"
placeholder={
allowTextCustomEmoji && !EmojiBoardTab.Gif ? 'Search or Text Reaction ' : 'Search'
tab === EmojiBoardTab.Gif
? 'Search KLIPY'
: allowTextCustomEmoji
? 'Search or Text Reaction '
: 'Search'
}
maxLength={50}
after={
allowTextCustomEmoji && query && !EmojiBoardTab.Gif ? (
allowTextCustomEmoji && query && tab !== EmojiBoardTab.Gif ? (
<Chip
variant="Primary"
radii="Pill"
+1
View File
@@ -25,4 +25,5 @@ export type GifData = {
preview_url?: string;
width?: number;
height?: number;
size?: number;
};
+35 -70
View File
@@ -169,8 +169,10 @@ import {
getFileMsgContent,
getImageMsgContent,
getVideoMsgContent,
getGifMsgContent,
} from './msgContent';
import { outgoingMessageTransforms } from './outgoingMessageTransforms';
import { getKlipyMxcUrl } from '$utils/klipy';
import { CommandAutocomplete } from './CommandAutocomplete';
import type {
AudioMessageRecorderHandle,
@@ -274,21 +276,7 @@ interface RoomInputProps {
onEditLastMessage?: () => void;
}
function toBase64Url(value: string): string {
const bytes = new TextEncoder().encode(value);
let binary = '';
for (const byte of bytes) {
binary += String.fromCodePoint(byte);
}
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll(/=+$/g, '');
}
function toMatrixID(fname: string, urlPrefix: string): string {
const base64 = toBase64Url(fname);
return urlPrefix + base64;
}
export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
({ editor, fileDropContainerRef, roomId, room, threadRootId, onEditLastMessage }, ref) => {
@@ -590,27 +578,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
handleRemoveUpload(uploads.map((upload) => upload.file));
};
const handleSendUpload = async (uploads: UploadSuccess[]) => {
const handleSendContents = async (contents: IContent[]) => {
const plainText = toPlainText(editor.children).trim();
const contentsPromises = uploads.map(async (upload) => {
const fileItem = selectedFiles.find((f) => f.file === upload.file);
if (!fileItem) throw new Error('Broken upload');
if (fileItem.file.type.startsWith('image')) {
return getImageMsgContent(mx, fileItem, upload.mxc);
}
if (fileItem.file.type.startsWith('video')) {
return getVideoMsgContent(mx, fileItem, upload.mxc);
}
if (fileItem.file.type.startsWith('audio')) {
return getAudioMsgContent(fileItem, upload.mxc);
}
return getFileMsgContent(fileItem, upload.mxc);
});
handleCancelUpload(uploads);
const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises));
/**
* the currently with the room associated per-message profile, if any, so that it can be included in the message content when sending.
* This allows the server to apply the correct profile-based transformations (e.g. font size adjustments) when processing the message,
@@ -662,11 +632,11 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
setEditingScheduledDelayId(null);
setScheduledTime(null);
} catch (error) {
debugLog.error('message', 'Failed to schedule uploaded file message', {
debugLog.error('message', 'Failed to schedule message', {
roomId,
error: error instanceof Error ? error.message : String(error),
});
log.error('failed to schedule uploaded message', { roomId }, error);
log.error('failed to schedule message', { roomId }, error);
throw error;
}
} else {
@@ -678,7 +648,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
} catch {
debugLog.error(
'message',
'Failed to cancel scheduled event before immediate file send',
'Failed to cancel scheduled event before immediate send',
{ roomId }
);
}
@@ -689,7 +659,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
mx
.sendMessage(roomId, threadRootId ?? null, content as RoomMessageEventContent)
.then((res: { event_id: string }) => {
debugLog.info('message', 'Uploaded file message sent', {
debugLog.info('message', 'Message sent', {
roomId,
eventId: res.event_id,
msgtype: content.msgtype,
@@ -697,11 +667,11 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
return res;
})
.catch((error: unknown) => {
debugLog.error('message', 'Failed to send uploaded file message', {
debugLog.error('message', 'Failed to send message', {
roomId,
error: error instanceof Error ? error.message : String(error),
});
log.error('failed to send uploaded message', { roomId }, error);
log.error('failed to send message', { roomId }, error);
throw error;
})
)
@@ -709,6 +679,28 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
}
};
const handleSendUpload = async (uploads: UploadSuccess[]) => {
const contentsPromises = uploads.map(async (upload) => {
const fileItem = selectedFiles.find((f) => f.file === upload.file);
if (!fileItem) throw new Error('Broken upload');
if (fileItem.file.type.startsWith('image')) {
return getImageMsgContent(mx, fileItem, upload.mxc);
}
if (fileItem.file.type.startsWith('video')) {
return getVideoMsgContent(mx, fileItem, upload.mxc);
}
if (fileItem.file.type.startsWith('audio')) {
return getAudioMsgContent(fileItem, upload.mxc);
}
return getFileMsgContent(fileItem, upload.mxc);
});
handleCancelUpload(uploads);
const contents = fulfilledPromiseSettledResult(await Promise.allSettled(contentsPromises));
await handleSendContents(contents);
};
const handleCloseAutocomplete = useCallback(() => {
setAutocompleteQuery(undefined);
ReactEditor.focus(editor);
@@ -1324,39 +1316,12 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
mx.sendEvent(roomId, EventType.Sticker, content);
};
const handleGifSelect = async (gif: GifData) => {
let url = gif.url.startsWith('mxc://')
? gif.url
: `mxc://${clientConfig.gifs?.proxyUrl ?? ''}/${toMatrixID(gif.url.slice('https://static.klipy.com/ii/'.length), 'klipy_')}`;
const handleGifSelect = async (gif: GifData, spoiler?: boolean) => {
const url = getKlipyMxcUrl(gif.url, clientConfig.gifs?.proxyUrl);
const content: RoomMessageEventContent & ReplyEventContent & IContent = {
body: gif.title,
url: url,
msgtype: MsgType.Image,
info: {
w: gif.width,
h: gif.height,
mimetype: 'image/gif',
},
};
const content = await getGifMsgContent(mx, gif, url, spoiler);
// Handle replies if there's a reply draft
if (replyDraft) {
content['m.relates_to'] = {
'm.in_reply_to': {
event_id: replyDraft.eventId,
},
};
if (replyDraft.relation?.rel_type === RelationType.Thread) {
content['m.relates_to'].event_id = replyDraft.relation.event_id;
content['m.relates_to'].rel_type = RelationType.Thread;
content['m.relates_to'].is_falling_back = false;
}
}
// Send the gif as sticker event.
await mx.sendEvent(roomId, EventType.RoomMessage, content);
setReplyDraft(undefined);
await handleSendContents([content]);
};
return (
+43 -1
View File
@@ -10,8 +10,9 @@ import {
loadImageElement,
loadVideoElement,
} from '$utils/dom';
import { encryptFile, getImageInfo, getThumbnailContent, getVideoInfo } from '$utils/matrix';
import { encryptFile, getImageInfo, getThumbnailContent, getVideoInfo, mxcUrlToHttp } from '$utils/matrix';
import type { TUploadItem } from '$state/room/roomInputDrafts';
import type { GifData } from '$components/emoji-board/types';
import { encodeBlurHash } from '$utils/blurHash';
import { scaleYDimension } from '$utils/common';
import { createLogger } from '$utils/debug';
@@ -237,3 +238,44 @@ export const getFileMsgContent = (item: TUploadItem, mxc: string): IContent => {
}
return content;
};
export const getGifMsgContent = async (
mx: MatrixClient,
gif: GifData,
mxcUrl: string,
spoiler?: boolean
): Promise<IContent> => {
const proxyUrl = mxcUrlToHttp(mx, mxcUrl, true);
const [imgError, imgEl] = await to(loadImageElement(proxyUrl ?? gif.url, 'anonymous'));
if (imgError) {
log.warn('Failed to load image element anonymously for blurhash, falling back to basic metadata:', imgError);
}
const content: IContent = {
msgtype: MsgType.Image,
body: gif.title,
url: mxcUrl,
info: {
w: gif.width,
h: gif.height,
mimetype: 'image/gif',
},
};
if (gif.size) {
content.info.size = gif.size;
}
if (spoiler) {
content[MATRIX_UNSTABLE_SPOILER_PROPERTY_NAME] = true;
}
if (imgEl) {
const blurHash = encodeBlurHash(imgEl, 512, scaleYDimension(imgEl.width, 512, imgEl.height));
if (blurHash) {
content.info[MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME] = blurHash;
}
}
return content;
};
+3 -1
View File
@@ -2,12 +2,14 @@ import type { AccountDataEvents } from 'matrix-js-sdk';
import { MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS } from '../../unstable/prefixes';
import { useAccountData } from './useAccountData';
const DEFAULT_FAVORITE_GIFS: AccountDataEvents[typeof MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS] = { gifs: [] };
export const useFavoriteGifs =
(): AccountDataEvents[typeof MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS] => {
const favoritedGifsData = useAccountData(MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS);
const favoritedContent = favoritedGifsData?.getContent<
AccountDataEvents[typeof MATRIX_SABLE_UNSTABLE_FAVORITE_GIFS]
>() ?? { gifs: [] };
>() ?? DEFAULT_FAVORITE_GIFS;
return favoritedContent;
};
+7 -2
View File
@@ -14,8 +14,13 @@ export const encodeBlurHash = (
if (!context) return undefined;
context.drawImage(img, 0, 0, canvas.width, canvas.height);
const data = context.getImageData(0, 0, canvas.width, canvas.height);
return encode(data.data, data.width, data.height, 4, 4);
try {
const data = context.getImageData(0, 0, canvas.width, canvas.height);
return encode(data.data, data.width, data.height, 4, 4);
} catch (err) {
console.warn('Failed to encode blurhash, possibly due to cross-origin tainted canvas:', err);
return undefined;
}
};
export const validBlurHash = (hash?: string): string | undefined => {
+2 -1
View File
@@ -99,9 +99,10 @@ export const getImageFileUrl = (fileOrBlob: File | Blob) => URL.createObjectURL(
export const getVideoFileUrl = (fileOrBlob: File | Blob) => URL.createObjectURL(fileOrBlob);
export const loadImageElement = (url: string): Promise<HTMLImageElement> =>
export const loadImageElement = (url: string, crossOrigin?: string): Promise<HTMLImageElement> =>
new Promise((resolve, reject) => {
const img = document.createElement('img');
if (crossOrigin) img.crossOrigin = crossOrigin;
img.addEventListener('load', () => resolve(img));
img.addEventListener('error', (err) => reject(err));
img.src = url;
+25
View File
@@ -0,0 +1,25 @@
export function toBase64Url(value: string): string {
const bytes = new TextEncoder().encode(value);
let binary = '';
for (const byte of bytes) {
binary += String.fromCodePoint(byte);
}
return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll(/=+$/g, '');
}
export function toMatrixID(fname: string, urlPrefix: string): string {
const base64 = toBase64Url(fname);
return urlPrefix + base64;
}
export function getKlipyMxcUrl(url: string, proxyUrl?: string): string {
if (url.startsWith('mxc://')) return url;
if (!proxyUrl) return url;
if (url.startsWith('https://static.klipy.com/ii/')) {
const id = url.slice('https://static.klipy.com/ii/'.length);
return `mxc://${proxyUrl}/${toMatrixID(id, 'klipy_')}`;
}
return url;
}