Apply the auto-fixable lint rules and the formatter, and drop the Vite build artifacts.
Checks / checks (push) Successful in 2m11s
Trigger cinny-mobile / dispatch (push) Successful in 1s

This commit is contained in:
2026-11-01 04:23:53 +11:00
parent 3cd159a63e
commit a6ad8651b3
605 changed files with 11480 additions and 9125 deletions
+7 -3
View File
@@ -1,7 +1,7 @@
import { Badge, Box, IconButton, Spinner, Text, as, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import React, { ReactNode, useCallback } from 'react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Icon, Icons } from '../icons';
import { mimeTypeToExt } from '../../utils/mimeTypes';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { useMediaAuthentication } from '../../hooks/useMediaAuthentication';
@@ -33,12 +33,16 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
await saveMediaBlob(fileContent, filename);
return true;
}, [mx, url, useAuthentication, mimeType, encInfo, filename])
}, [mx, url, useAuthentication, mimeType, encInfo, filename]),
);
const downloading = downloadState.status === AsyncStatus.Loading;
+37 -32
View File
@@ -1,7 +1,7 @@
import React, { CSSProperties, ReactNode } from 'react';
import { Box, Chip, Text, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import { IContent } from 'matrix-js-sdk';
import { Icon, Icons } from '../icons';
import { JUMBO_EMOJI_REG, URL_REG } from '../../utils/regex';
import { trimReplyFromBody } from '../../utils/room';
import { MessageTextBody } from './layout';
@@ -27,7 +27,10 @@ import {
MATRIX_SPOILER_REASON_PROPERTY_NAME,
} from '../../../types/matrix/common';
import { StationeryMedia, hashStationerySeed, stationeryMediaRot } from './StationeryMedia';
import { getJumboEmojiInteractionProps, JumboEmojiClickHandler } from '../../features/room/emoji-confetti/jumboEmojiInteraction';
import {
getJumboEmojiInteractionProps,
JumboEmojiClickHandler,
} from '../../features/room/emoji-confetti/jumboEmojiInteraction';
import { FALLBACK_MIMETYPE, getBlobSafeMimeType } from '../../utils/mimeTypes';
import { parseGeoUri, scaleYDimension } from '../../utils/common';
import { resolveAttachmentBoxSize } from '../../state/mediaDimensionCache';
@@ -81,14 +84,22 @@ type MTextProps = {
style?: CSSProperties;
onJumboEmojiClick?: JumboEmojiClickHandler;
};
export function MText({ edited, content, renderBody, renderUrlsPreview, style, onJumboEmojiClick }: MTextProps) {
export function MText({
edited,
content,
renderBody,
renderUrlsPreview,
style,
onJumboEmojiClick,
}: MTextProps) {
const { body, formatted_body: customBody } = content;
if (typeof body !== 'string') return <BrokenContent />;
const trimmedBody = trimReplyFromBody(body).trim();
const trimmedCustomBody = typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const trimmedCustomBody =
typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
const isJumboEmoji = JUMBO_EMOJI_REG.test(trimmedBody);
@@ -137,9 +148,10 @@ export function MEmote({
if (typeof body !== 'string') return <BrokenContent />;
const trimmedBody = trimReplyFromBody(body).trim();
const trimmedCustomBody = typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const trimmedCustomBody =
typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
const isJumboEmoji = JUMBO_EMOJI_REG.test(trimmedBody);
@@ -151,11 +163,7 @@ export function MEmote({
return (
<>
<MessageTextBody
emote
preWrap={typeof customBody !== 'string'}
jumboEmoji={isJumboEmoji}
>
<MessageTextBody emote preWrap={typeof customBody !== 'string'} jumboEmoji={isJumboEmoji}>
<b>{`${displayName} `}</b>
<span {...jumboEmojiInteraction}>
{renderBody({
@@ -177,14 +185,21 @@ type MNoticeProps = {
renderUrlsPreview?: (urls: string[]) => ReactNode;
onJumboEmojiClick?: JumboEmojiClickHandler;
};
export function MNotice({ edited, content, renderBody, renderUrlsPreview, onJumboEmojiClick }: MNoticeProps) {
export function MNotice({
edited,
content,
renderBody,
renderUrlsPreview,
onJumboEmojiClick,
}: MNoticeProps) {
const { body, formatted_body: customBody } = content;
if (typeof body !== 'string') return <BrokenContent />;
const trimmedBody = trimReplyFromBody(body).trim();
const trimmedCustomBody = typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const trimmedCustomBody =
typeof customBody === 'string'
? customBody.trim().replace(/(<br\s*\/?>\s*)+$/gi, '')
: undefined;
const urlsMatch = renderUrlsPreview && trimmedBody.match(URL_REG);
const urls = urlsMatch ? [...new Set(urlsMatch)] : undefined;
const isJumboEmoji = JUMBO_EMOJI_REG.test(trimmedBody);
@@ -232,7 +247,7 @@ type MImageProps = {
const resolveMediaBoxSize = (
mxcUrl: string,
w?: number,
h?: number
h?: number,
): { width: number; height: number } => resolveAttachmentBoxSize(mxcUrl, w, h);
/** Extra space after media so following text stays on the 24px ruled grid — applied outside the photo chrome */
@@ -253,12 +268,7 @@ export function MImage({ content, renderImageContent, outlined }: MImageProps) {
const gridPad = snapStationeryGridPad(height);
return (
<StationeryMedia
outlined={outlined}
transparent
tiltSeed={mxcUrl}
gridPad={gridPad}
>
<StationeryMedia outlined={outlined} transparent tiltSeed={mxcUrl} gridPad={gridPad}>
<AttachmentBox
style={{
width: toRem(width),
@@ -312,17 +322,12 @@ export function MVideo({ content, renderAsFile, renderVideoContent, outlined }:
const { width, height } = resolveMediaBoxSize(
mxcUrl,
videoInfo.w ?? videoInfo.thumbnail_info?.w,
videoInfo.h ?? videoInfo.thumbnail_info?.h
videoInfo.h ?? videoInfo.thumbnail_info?.h,
);
const gridPad = snapStationeryGridPad(height);
return (
<StationeryMedia
outlined={outlined}
transparent
tiltSeed={mxcUrl}
gridPad={gridPad}
>
<StationeryMedia outlined={outlined} transparent tiltSeed={mxcUrl} gridPad={gridPad}>
<AttachmentHeader>
<FileHeader
body={filename}
+2 -2
View File
@@ -23,7 +23,7 @@ export const Reaction = as<
const stationery = isStationeryTheme(theme);
const isCustomEmoji = reaction.startsWith('mxc://');
const customSrc = isCustomEmoji
? mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction
? (mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction)
: undefined;
const emoji = isCustomEmoji ? (
@@ -130,7 +130,7 @@ export function ReactionTooltipMsg({ room, reaction, events }: ReactionTooltipMs
(ev: MatrixEvent) =>
getMemberDisplayName(room, ev.getSender() ?? 'Unknown') ??
getMxIdLocalPart(ev.getSender() ?? 'Unknown') ??
'Unknown'
'Unknown',
);
return (
+9 -8
View File
@@ -1,8 +1,8 @@
import { Box, Text, as, color, toRem } from 'folds';
import { Icon, Icons } from '../icons';
import { EventTimelineSet, Room } from 'matrix-js-sdk';
import React, { MouseEventHandler, ReactNode, useCallback, useMemo } from 'react';
import classNames from 'classnames';
import { Icon, Icons } from '../icons';
import { getMemberAvatarMxc, getMemberDisplayName, trimReplyFromBody } from '../../utils/room';
import { getMxIdLocalPart } from '../../utils/matrix';
import { LinePlaceholder } from './placeholder';
@@ -23,8 +23,8 @@ type ReplyLayoutProps = {
};
export const ReplyLayout = as<'div', ReplyLayoutProps>(
({ username, userColor, className, children, ...props }, ref) => {
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
return (
<Box
@@ -61,7 +61,7 @@ export const ReplyLayout = as<'div', ReplyLayoutProps>(
</Box>
</Box>
);
}
},
);
export const ThreadIndicator = as<'div'>(({ ...props }, ref) => (
@@ -105,12 +105,12 @@ export const Reply = as<'div', ReplyProps>(
legacyUsernameColor,
...props
},
ref
ref,
) => {
const placeholderWidth = useMemo(() => randomNumberBetween(40, 400), []);
const getFromLocalTimeline = useCallback(
() => timelineSet?.findEventById(replyEventId),
[timelineSet, replyEventId]
[timelineSet, replyEventId],
);
const replyEvent = useRoomEvent(room, replyEventId, getFromLocalTimeline);
@@ -122,7 +122,8 @@ export const Reply = as<'div', ReplyProps>(
const tagColor = powerTag?.color ? accessibleTagColors?.get(powerTag.color) : undefined;
// Priority: custom user color > tag color (non-legacy) > colorMXID (legacy)
const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(sender ?? replyEventId) : tagColor);
const usernameColor =
customUserColor ?? (legacyUsernameColor ? colorMXID(sender ?? replyEventId) : tagColor);
const fallbackBody = replyEvent?.isRedacted() ? (
<MessageDeletedContent />
@@ -171,5 +172,5 @@ export const Reply = as<'div', ReplyProps>(
</ReplyLayout>
</Box>
);
}
},
);
@@ -56,7 +56,7 @@ function cornerPeelPaths(
cy: number,
ux: number,
uy: number,
size: number
size: number,
): {
keep: string;
flap: string;
@@ -147,20 +147,21 @@ export function StationeryMedia({
const isStationery = isStationeryTheme(theme);
const peelRef = useRef<HTMLSpanElement>(null);
const tiltStyle = useMemo((): CSSProperties => {
return {
const tiltStyle = useMemo(
(): CSSProperties => ({
...(style as CSSProperties | undefined),
// Margin sits outside the paper chrome — snaps the grid without a white bar
...(isStationery && gridPad > 0 ? { marginBottom: `${gridPad}px` } : null),
['--media-rot' as string]: stationeryMediaRot(tiltSeed),
};
}, [tiltSeed, style, isStationery, gridPad]);
}),
[tiltSeed, style, isStationery, gridPad],
);
const tapeAlt = useMemo(() => hashStationerySeed(tiltSeed) % 2 === 1, [tiltSeed]);
// Default tape covers TL; alt covers TR — peel only the free top corner
const peelCorner = useMemo(
() => (tapeAlt ? CORNERS.find((c) => c.id === 'tl')! : CORNERS.find((c) => c.id === 'tr')!),
[tapeAlt]
[tapeAlt],
);
const clearPeel = useCallback((host: HTMLElement) => {
@@ -237,7 +238,7 @@ export function StationeryMedia({
cy,
ux,
uy,
size
size,
);
target.style.clipPath = keep;
peel.style.clipPath = flap;
@@ -253,7 +254,7 @@ export function StationeryMedia({
clearPeel(host);
}
},
[peelCorner, clearPeel]
[peelCorner, clearPeel],
);
const handleMove: MouseEventHandler<HTMLElement> = (evt) => {
+1 -1
View File
@@ -41,5 +41,5 @@ export const Time = as<'span', TimeProps & ComponentProps<typeof Text>>(
{time}
</Text>
);
}
},
);
@@ -12,7 +12,7 @@ export const Attachment = as<'div', css.AttachmentVariants>(
{...props}
ref={ref}
/>
)
),
);
export const AttachmentHeader = as<'div'>(({ className, ...props }, ref) => (
@@ -1,9 +1,9 @@
/* eslint-disable jsx-a11y/media-has-caption */
import React, { ReactNode, useCallback, useRef, useState } from 'react';
import { Badge, Chip, IconButton, ProgressBar, Spinner, Text, toRem } from 'folds';
import { Icon, Icons } from '../../icons';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Range } from 'react-range';
import { Icon, Icons } from '../../icons';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { IAudioInfo } from '../../../../types/matrix/common';
@@ -60,10 +60,14 @@ export function AudioContent({
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
const audioRef = useRef<HTMLAudioElement | null>(null);
@@ -84,7 +88,7 @@ export function AudioContent({
}, []);
useMediaPlayTimeCallback(
getAudioRef,
useThrottle(handlePlayTimeCallback, PLAY_TIME_THROTTLE_OPS)
useThrottle(handlePlayTimeCallback, PLAY_TIME_THROTTLE_OPS),
);
const handlePlay = () => {
@@ -152,7 +156,7 @@ export function AudioContent({
</Chip>
<Text size="T200">{`${secondsToMinutesAndSeconds(
currentTime
currentTime,
)} / ${secondsToMinutesAndSeconds(duration)}`}</Text>
</>
),
@@ -1,6 +1,6 @@
import { Box } from 'folds';
import { Icon, IconSrc } from '../../icons';
import React, { ReactNode } from 'react';
import { Icon, IconSrc } from '../../icons';
import { BubbleLayout, CompactLayout, ModernLayout } from '..';
import { MessageLayout } from '../../../state/settings';
@@ -1,6 +1,6 @@
import { Box, Text, as, color, config } from 'folds';
import { Icon, Icons } from '../../icons';
import React from 'react';
import { Icon, Icons } from '../../icons';
const warningStyle = { color: color.Warning.Main, opacity: config.opacity.P300 };
const criticalStyle = { color: color.Critical.Main, opacity: config.opacity.P300 };
@@ -15,7 +15,7 @@ export const MessageDeletedContent = as<'div', { children?: never; reason?: stri
<i>This message has been deleted</i>
)}
</Box>
)
),
);
export const MessageUnsupportedContent = as<'div', { children?: never }>(({ ...props }, ref) => (
@@ -1,9 +1,21 @@
import React, { ReactNode, useCallback, useState } from 'react';
import { Box, Button, Modal, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds';
import { Icon, Icons } from '../../icons';
import {
Box,
Button,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { saveMediaBlob } from '../../../utils/saveMedia';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../icons';
import { saveMediaBlob } from '../../../utils/saveMedia';
import { IFileInfo } from '../../../../types/matrix/common';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
@@ -78,13 +90,17 @@ export function ReadTextFile({ body, mimeType, url, encInfo, renderViewer }: Rea
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
const text = fileContent.text();
setTextViewer(true);
return text;
}, [mx, useAuthentication, mimeType, encInfo, url])
}, [mx, useAuthentication, mimeType, encInfo, url]),
);
return (
@@ -170,11 +186,15 @@ export function ReadPdfFile({ body, mimeType, url, encInfo, renderViewer }: Read
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
setPdfViewer(true);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
return (
@@ -249,12 +269,16 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) => decryptFile(encBuf, mimeType, encInfo), accessToken)
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
await saveMediaBlob(fileContent, body);
return fileContent;
}, [mx, url, useAuthentication, mimeType, encInfo, body])
}, [mx, url, useAuthentication, mimeType, encInfo, body]),
);
return downloadState.status === AsyncStatus.Error ? (
@@ -299,5 +323,5 @@ export const FileContent = as<'div', FileContentProps>(
{mimeType === 'application/pdf' && renderAsPdfFile()}
{children}
</Box>
)
),
);
@@ -1,10 +1,21 @@
import React, { ReactNode, useCallback, useEffect, useState } from 'react';
import { Badge, Box, Button, Chip, Overlay, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds';
import { Icon, Icons } from '../../icons';
import {
Badge,
Box,
Button,
Chip,
Overlay,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import classNames from 'classnames';
import { Blurhash } from 'react-blurhash';
import FocusTrap from 'focus-trap-react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Icon, Icons } from '../../icons';
import { IImageInfo, MATRIX_BLUR_HASH_PROPERTY_NAME } from '../../../../types/matrix/common';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
@@ -16,7 +27,12 @@ import { decryptFile, downloadEncryptedMedia, mxcUrlToHttp } from '../../../util
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { validBlurHash } from '../../../utils/blurHash';
import { getCurrentAccessToken } from '../../../utils/auth';
import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMediaBlurHash } from '../../../state/mediaDimensionCache';
import {
setMediaDimensions,
getMediaBlurHash,
getMediaDimensions,
rememberMediaBlurHash,
} from '../../../state/mediaDimensionCache';
/**
* Fetches media with authentication headers and returns a blob URL.
@@ -26,28 +42,36 @@ import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMedia
*/
const fetchAuthenticatedMedia = async (
url: string,
accessToken: string | null
accessToken: string | null,
): Promise<string> => {
try {
let response = await fetch(url, {
method: 'GET',
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
});
// If we got a 401 and we tried with auth, fallback to unauthenticated request
if (!response.ok && response.status === 401 && accessToken) {
console.warn('[ImageContent] Auth failed (401), attempting unauthenticated fallback for:', url);
console.warn(
'[ImageContent] Auth failed (401), attempting unauthenticated fallback for:',
url,
);
response = await fetch(url, { method: 'GET' });
}
if (!response.ok) {
console.warn(`[ImageContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`);
console.warn(
`[ImageContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`,
);
return url;
}
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (error) {
console.warn('[ImageContent] Error fetching authenticated media, falling back to original URL:', error);
console.warn(
'[ImageContent] Error fetching authenticated media, falling back to original URL:',
error,
);
return url;
}
};
@@ -101,7 +125,7 @@ export const ImageContent = as<'div', ImageContentProps>(
renderImage,
...props
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -132,7 +156,7 @@ export const ImageContent = as<'div', ImageContentProps>(
const fileContent = await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType ?? FALLBACK_MIMETYPE, encInfo),
accessToken
accessToken,
);
return URL.createObjectURL(fileContent);
}
@@ -141,7 +165,7 @@ export const ImageContent = as<'div', ImageContentProps>(
return fetchAuthenticatedMedia(mediaUrl, accessToken);
}
return mediaUrl;
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
const handleLoad = () => {
@@ -228,7 +252,7 @@ export const ImageContent = as<'div', ImageContentProps>(
css.AbsoluteContainer,
css.MediaFadeIn,
load && css.MediaFadeInLoaded,
blurred && css.Blur
blurred && css.Blur,
)}
>
{renderImage({
@@ -327,5 +351,5 @@ export const ImageContent = as<'div', ImageContentProps>(
)}
</Box>
);
}
},
);
@@ -2,7 +2,12 @@ import { ReactNode, useCallback, useEffect } from 'react';
import { IThumbnailContent } from '../../../../types/matrix/common';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { decryptFile, downloadEncryptedMedia, isAuthenticatedMediaUrl, mxcUrlToHttp } from '../../../utils/matrix';
import {
decryptFile,
downloadEncryptedMedia,
isAuthenticatedMediaUrl,
mxcUrlToHttp,
} from '../../../utils/matrix';
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { FALLBACK_MIMETYPE } from '../../../utils/mimeTypes';
import { getCurrentAccessToken } from '../../../utils/auth';
@@ -14,28 +19,36 @@ import { getCurrentAccessToken } from '../../../utils/auth';
*/
const fetchAuthenticatedMedia = async (
url: string,
accessToken: string | null
accessToken: string | null,
): Promise<string> => {
try {
let response = await fetch(url, {
method: 'GET',
headers: accessToken ? { Authorization: `Bearer ${accessToken}` } : undefined,
});
// If we got a 401 and we tried with auth, fallback to unauthenticated request
if (!response.ok && response.status === 401 && accessToken) {
console.warn('[ThumbnailContent] Auth failed (401), attempting unauthenticated fallback for:', url);
console.warn(
'[ThumbnailContent] Auth failed (401), attempting unauthenticated fallback for:',
url,
);
response = await fetch(url, { method: 'GET' });
}
if (!response.ok) {
console.warn(`[ThumbnailContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`);
console.warn(
`[ThumbnailContent] Failed to fetch authenticated media (${response.status}), falling back to original URL`,
);
return url;
}
const blob = await response.blob();
return URL.createObjectURL(blob);
} catch (error) {
console.warn('[ThumbnailContent] Error fetching authenticated media, falling back to original URL:', error);
console.warn(
'[ThumbnailContent] Error fetching authenticated media, falling back to original URL:',
error,
);
return url;
}
};
@@ -51,7 +64,8 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
// Check if we have valid thumbnail data
const thumbInfo = info.thumbnail_info;
const thumbMxcUrl = info.thumbnail_file?.url ?? info.thumbnail_url;
const hasValidThumbnail = typeof thumbMxcUrl === 'string' && typeof thumbInfo?.mimetype === 'string';
const hasValidThumbnail =
typeof thumbMxcUrl === 'string' && typeof thumbInfo?.mimetype === 'string';
const [thumbSrcState, loadThumbSrc] = useAsyncCallback(
useCallback(async () => {
@@ -64,7 +78,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
const fileContent = await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, thumbInfo.mimetype ?? FALLBACK_MIMETYPE, encInfo),
accessToken
accessToken,
);
return URL.createObjectURL(fileContent);
}
@@ -75,7 +89,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
}
return mediaUrl;
}, [mx, thumbMxcUrl, thumbInfo, info.thumbnail_file, useAuthentication])
}, [mx, thumbMxcUrl, thumbInfo, info.thumbnail_file, useAuthentication]),
);
useEffect(() => {
@@ -1,10 +1,24 @@
import React, { ReactNode, useCallback, useEffect, useState } from 'react';
import { Badge, Box, Button, Chip, Modal, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, Tooltip, TooltipProvider, as } from 'folds';
import { Icon, Icons } from '../../icons';
import {
Badge,
Box,
Button,
Chip,
Modal,
Overlay,
OverlayBackdrop,
OverlayCenter,
Spinner,
Text,
Tooltip,
TooltipProvider,
as,
} from 'folds';
import classNames from 'classnames';
import { Blurhash } from 'react-blurhash';
import FocusTrap from 'focus-trap-react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { Icon, Icons } from '../../icons';
import {
IThumbnailContent,
IVideoInfo,
@@ -25,7 +39,12 @@ import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { validBlurHash } from '../../../utils/blurHash';
import { ModalWide } from '../../../styles/Modal.css';
import { stopPropagation } from '../../../utils/keyboard';
import { setMediaDimensions, getMediaBlurHash, getMediaDimensions, rememberMediaBlurHash } from '../../../state/mediaDimensionCache';
import {
setMediaDimensions,
getMediaBlurHash,
getMediaDimensions,
rememberMediaBlurHash,
} from '../../../state/mediaDimensionCache';
type RenderViewerProps = {
src: string;
@@ -71,7 +90,7 @@ export const VideoContent = as<'div', VideoContentProps>(
renderVideo,
...props
},
ref
ref,
) => {
const mx = useMatrixClient();
const useAuthentication = useMediaAuthentication();
@@ -83,9 +102,7 @@ export const VideoContent = as<'div', VideoContentProps>(
const blurW = info.w ?? info.thumbnail_info?.w ?? cachedDims?.w;
const blurH = info.h ?? info.thumbnail_info?.h ?? cachedDims?.h;
const blurResolutionY =
blurW && blurH && blurW > 0
? Math.max(1, Math.round(blurResolutionX * (blurH / blurW)))
: 32;
blurW && blurH && blurW > 0 ? Math.max(1, Math.round(blurResolutionX * (blurH / blurW))) : 32;
const [load, setLoad] = useState(false);
const [error, setError] = useState(false);
@@ -99,12 +116,14 @@ export const VideoContent = as<'div', VideoContentProps>(
// Always use current session's token to avoid stale tokens during account switches
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) =>
decryptFile(encBuf, mimeType, encInfo), accessToken
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
const handleLoad = (video?: HTMLVideoElement) => {
@@ -207,7 +226,7 @@ export const VideoContent = as<'div', VideoContentProps>(
css.AbsoluteContainer,
css.MediaFadeIn,
load && css.MediaFadeInLoaded,
blurred && css.Blur
blurred && css.Blur,
)}
>
{renderVideo({
@@ -306,5 +325,5 @@ export const VideoContent = as<'div', VideoContentProps>(
)}
</Box>
);
}
},
);
@@ -2,13 +2,18 @@ import { ReactNode, useCallback, useEffect, useState } from 'react';
import { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '../../../utils/matrix';
import {
decryptFile,
downloadEncryptedMedia,
downloadMedia,
mxcUrlToHttp,
} from '../../../utils/matrix';
import { useMediaAuthentication } from '../../../hooks/useMediaAuthentication';
import { getCurrentAccessToken } from '../../../utils/auth';
/**
* Extracts the first frame from a video file and renders it as a thumbnail.
* This is used as a fallback when no thumbnail metadata is provided.
* This is used as a fallback when no thumbnail metadata is provided.
*/
export type VideoFrameThumbnailProps = {
mimeType: string;
@@ -31,15 +36,17 @@ export function VideoFrameThumbnail({
useCallback(async () => {
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication) ?? url;
const accessToken = getCurrentAccessToken();
const fileContent = encInfo
? await downloadEncryptedMedia(mediaUrl, (encBuf) =>
decryptFile(encBuf, mimeType, encInfo), accessToken
? await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, mimeType, encInfo),
accessToken,
)
: await downloadMedia(mediaUrl, accessToken);
return URL.createObjectURL(fileContent);
}, [mx, url, useAuthentication, mimeType, encInfo])
}, [mx, url, useAuthentication, mimeType, encInfo]),
);
useEffect(() => {
@@ -69,7 +76,7 @@ export function VideoFrameThumbnail({
const cleanup = () => {
if (isCleanedUp) return;
isCleanedUp = true;
if (handlers.loadedData) video.removeEventListener('loadeddata', handlers.loadedData);
if (handlers.seeked) video.removeEventListener('seeked', handlers.seeked);
if (handlers.error) video.removeEventListener('error', handlers.error);
@@ -90,7 +97,7 @@ export function VideoFrameThumbnail({
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
if (!ctx) {
cleanup();
@@ -98,14 +105,18 @@ export function VideoFrameThumbnail({
}
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob((blob) => {
if (blob) {
const thumbnailUrl = URL.createObjectURL(blob);
setThumbnailSrc(thumbnailUrl);
}
cleanup();
}, 'image/jpeg', 0.85);
canvas.toBlob(
(blob) => {
if (blob) {
const thumbnailUrl = URL.createObjectURL(blob);
setThumbnailSrc(thumbnailUrl);
}
cleanup();
},
'image/jpeg',
0.85,
);
} catch {
cleanup();
}
+38 -33
View File
@@ -6,17 +6,20 @@ import { isStationeryTheme, useTheme } from '../../../hooks/useTheme';
import { STATIONERY_NAME_INK } from '../../../utils/paperSafeInk';
export const MessageBase = as<'div', css.MessageBaseVariants>(
({ className, highlight, selected, collapse, autoCollapse, space, newMessage, ...props }, ref) => (
(
{ className, highlight, selected, collapse, autoCollapse, space, newMessage, ...props },
ref,
) => (
<div
className={classNames(
css.MessageBase({ highlight, selected, collapse, autoCollapse, space, newMessage }),
className
className,
)}
data-message-collapsed={collapse ? '' : undefined}
{...props}
ref={ref}
/>
)
),
);
export const AvatarBase = as<'span'>(({ className, ...props }, ref) => (
@@ -28,37 +31,39 @@ export const AvatarBase = as<'span'>(({ className, ...props }, ref) => (
/>
));
export const Username = as<'span'>(({ as: AsUsername = 'span', className, style, ...props }, ref) => {
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
const userColor =
typeof (style as CSSProperties | undefined)?.color === 'string'
? ((style as CSSProperties).color as string)
: undefined;
export const Username = as<'span'>(
({ as: AsUsername = 'span', className, style, ...props }, ref) => {
const theme = useTheme();
const isStationery = isStationeryTheme(theme);
const userColor =
typeof (style as CSSProperties | undefined)?.color === 'string'
? ((style as CSSProperties).color as string)
: undefined;
const safeStyle = useMemo((): CSSProperties | undefined => {
if (!isStationery) return style as CSSProperties | undefined;
return {
...(style as CSSProperties | undefined),
// Name in ink; keep their color as an accent underline
color: STATIONERY_NAME_INK,
...(userColor
? { ['--username-accent' as string]: userColor, textDecorationColor: userColor }
: null),
};
}, [style, isStationery, userColor]);
const safeStyle = useMemo((): CSSProperties | undefined => {
if (!isStationery) return style as CSSProperties | undefined;
return {
...(style as CSSProperties | undefined),
// Name in ink; keep their color as an accent underline
color: STATIONERY_NAME_INK,
...(userColor
? { ['--username-accent' as string]: userColor, textDecorationColor: userColor }
: null),
};
}, [style, isStationery, userColor]);
return (
<AsUsername
className={classNames(css.Username, className)}
data-message-username=""
data-username-accent={isStationery && userColor ? '' : undefined}
style={safeStyle}
{...props}
ref={ref}
/>
);
});
return (
<AsUsername
className={classNames(css.Username, className)}
data-message-username=""
data-username-accent={isStationery && userColor ? '' : undefined}
style={safeStyle}
{...props}
ref={ref}
/>
);
},
);
export const UsernameBold = as<'b'>(({ as: AsUsernameBold = 'b', className, ...props }, ref) => (
<AsUsernameBold className={classNames(css.UsernameBold, className)} {...props} ref={ref} />
@@ -77,5 +82,5 @@ export const MessageTextBody = as<'div', css.MessageTextBodyVariants & { notice?
{...props}
ref={ref}
/>
)
),
);
+1 -1
View File
@@ -59,5 +59,5 @@ export const BubbleLayout = as<'div', BubbleLayoutProps>(
)}
</Box>
</Box>
)
),
);
@@ -14,5 +14,5 @@ export const CompactLayout = as<'div', CompactLayoutProps>(
</Box>
{children}
</Box>
)
),
);
@@ -1,7 +1,7 @@
import { createVar, globalStyle, keyframes, style, styleVariants } from '@vanilla-extract/css';
import * as htmlCss from '../../../styles/CustomHtml.css';
import { recipe, RecipeVariants } from '@vanilla-extract/recipes';
import { DefaultReset, color, config, toRem } from 'folds';
import * as htmlCss from '../../../styles/CustomHtml.css';
export const StickySection = style({
position: 'sticky',
@@ -23,5 +23,5 @@ export const CompactPlaceholder = as<'div', { variant?: ContainerColor }>(
<LinePlaceholder variant={variant} style={{ maxWidth: toRem(msgSize) }} />
</CompactLayout>
);
}
},
);
@@ -35,5 +35,5 @@ export const DefaultPlaceholder = as<'div', { variant?: ContainerColor }>(
</Box>
</ModernLayout>
);
}
},
);
@@ -11,5 +11,5 @@ export const LinePlaceholder = as<'div', css.LinePlaceholderVariants>(
{...props}
ref={ref}
/>
)
),
);