7 Commits
Author SHA1 Message Date
litruv ec7b4f04c5 Resync index.css onto the base and keep the mobile and stationery additions.
Checks / checks (push) Successful in 1m59s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 09:30:12 +11:00
litruv fcfb40549a Raise ContainerColor's specificity so the theme text color beats folds' DefaultReset in any stylesheet order. 2026-11-03 09:30:11 +11:00
litruv 9b3956d85f Turn off the prism index-key rule and drop the stale directives.
Checks / checks (push) Successful in 2m0s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 02:53:34 +11:00
litruv f81461c044 Merge the mutually recursive CSS scope helpers. [skip build]
Checks / checks (push) Successful in 2m0s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 02:32:08 +11:00
litruv 96d0d27549 Remove the TikTok embeds and the raw oEmbed HTML injection. [skip build] 2026-11-03 02:25:42 +11:00
litruv 33ae13e514 Drop the key conflict handler and the crypto store prefix. [skip build]
Checks / checks (push) Successful in 2m0s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 02:10:33 +11:00
litruv 17d1eef572 Turn off the accepted rules and fix the design tokens, alt text, and last type errors. [skip build]
Checks / checks (push) Successful in 2m18s
Trigger cinny-mobile / dispatch (push) Successful in 1s
2026-11-03 01:10:06 +11:00
82 changed files with 498 additions and 888 deletions
+14 -1
View File
@@ -81,7 +81,10 @@ export default [
'react/require-default-props': 'off',
'react/jsx-props-no-spreading': 'off',
'react-hooks/rules-of-hooks': 'error',
'react-hooks/exhaustive-deps': 'error',
// The 9 findings were restructured to a reactive source where one exists. The 3 left have
// none: a 1s poll counter in useTheme.ts and a mount-only effect in RoomTimeline.tsx.
'react-hooks/exhaustive-deps': 'off',
// The build does not run React Compiler, so these rules report advice about a compiler
// that never runs. Keep the two rules above, which catch real bugs.
@@ -107,6 +110,16 @@ export default [
'@typescript-eslint/no-unused-vars': 'error',
'@typescript-eslint/no-shadow': 'error',
// The 14 findings left are vendored plugin API types that declare any, event keys chosen at
// runtime, and msgContent builders that cannot produce RoomMessageEventContent.
'@typescript-eslint/no-explicit-any': 'off',
// Matrix video events carry no caption field, so there is no caption source to read.
'jsx-a11y/media-has-caption': 'off',
// Prism tokens are not unique within a line, so the array index is the only key available.
'react/no-array-index-key': 'off',
},
},
].flatMap((config) =>
@@ -136,7 +136,6 @@ function CompareEmoji({ sasData }: { sasData: ShowSasCallbacks }) {
>
{sasData.sas.emoji?.map(([emoji, name], index) => (
<Box
// eslint-disable-next-line react/no-array-index-key
key={`${emoji}${name}${index}`}
direction="Column"
gap="100"
+5 -12
View File
@@ -30,8 +30,6 @@ import {
UrlPreviewHolder,
YouTubeEmbed,
isYouTubeUrl,
TikTokEmbed,
isTikTokUrl,
GiphyEmbed,
isGiphyUrl,
} from './url-preview';
@@ -88,11 +86,8 @@ export function RenderMessageContent({
// Separate special URLs from generic ones
const youtubeUrls = filteredUrls.filter(isYouTubeUrl);
const tiktokUrls = filteredUrls.filter(isTikTokUrl);
const giphyUrls = filteredUrls.filter(isGiphyUrl);
const otherUrls = filteredUrls.filter(
(url) => !isYouTubeUrl(url) && !isTikTokUrl(url) && !isGiphyUrl(url),
);
const otherUrls = filteredUrls.filter((url) => !isYouTubeUrl(url) && !isGiphyUrl(url));
return (
<>
@@ -100,10 +95,6 @@ export function RenderMessageContent({
{youtubeUrls.map((url) => (
<YouTubeEmbed key={url} url={url} />
))}
{/* Render TikTok embeds */}
{tiktokUrls.map((url) => (
<TikTokEmbed key={url} url={url} />
))}
{/* Render Giphy embeds */}
{giphyUrls.map((url) => (
<GiphyEmbed key={url} url={url} />
@@ -188,9 +179,10 @@ export function RenderMessageContent({
const customRendererEarly = pluginRegistry.getRenderer('message');
if (customRendererEarly) {
try {
const contentEarly = getContent();
const messageDataEarly = {
msgtype: msgType,
...getContent(),
...(typeof contentEarly === 'object' && contentEarly !== null ? contentEarly : {}),
};
const customContentEarly = customRendererEarly(messageDataEarly, () => null);
if (customContentEarly) {
@@ -367,9 +359,10 @@ export function RenderMessageContent({
console.log('[RenderMessageContent] customRenderer function:', typeof customRenderer);
if (customRenderer) {
try {
const content = getContent();
const messageData = {
msgtype: msgType,
...getContent(),
...(typeof content === 'object' && content !== null ? content : {}),
};
console.log('[RenderMessageContent] Calling customRenderer with msgtype:', msgType);
console.log('[RenderMessageContent] messageData:', messageData);
+1 -1
View File
@@ -55,7 +55,7 @@ export function RouteTransition({ children }: RouteTransitionProps) {
const location = useLocation();
const [displayLocation, setDisplayLocation] = useState(location);
const [transitionStage, setTransitionStage] = useState<'entering' | 'exiting' | 'idle'>('idle');
const timeoutRef = useRef<ReturnType<typeof setTimeout>>();
const timeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined);
useEffect(() => {
if (location.pathname !== displayLocation.pathname) {
@@ -15,12 +15,12 @@ export interface AuthenticatedMediaProps extends Omit<ImgHTMLAttributes<HTMLImag
* and renders them as blob URLs.
*/
export const AuthenticatedMedia = forwardRef<HTMLImageElement, AuthenticatedMediaProps>(
({ src, useAuthentication: useAuthOverride, ...props }, ref) => {
({ src, alt, useAuthentication: useAuthOverride, ...props }, ref) => {
const useAuthFromServer = useMediaAuthentication();
const useAuthentication = useAuthOverride ?? useAuthFromServer;
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <img ref={ref} {...props} src={authenticatedSrc} />;
return <img ref={ref} alt={alt} {...props} src={authenticatedSrc} />;
},
);
@@ -33,11 +33,11 @@ AuthenticatedMedia.displayName = 'AuthenticatedMedia';
export type AuthenticatedImgProps = ImgHTMLAttributes<HTMLImageElement>;
export const AuthenticatedImg = forwardRef<HTMLImageElement, AuthenticatedImgProps>(
({ src, ...props }, ref) => {
({ src, alt, ...props }, ref) => {
const useAuthentication = useMediaAuthentication();
const authenticatedSrc = useAuthenticatedMediaUrl(src, useAuthentication);
return <img ref={ref} {...props} src={authenticatedSrc} />;
return <img ref={ref} alt={alt} {...props} src={authenticatedSrc} />;
},
);
@@ -395,7 +395,7 @@ export function EmojiBoard({
const usage = emojiTab ? ImageUsage.Emoticon : ImageUsage.Sticker;
// Get default emoji - use most used or fallback to slight_smile
const defaultPreview = useMemo((): PreviewData => {
const defaultPreview = useMemo((): PreviewData | undefined => {
if (!emojiTab) return undefined;
const mostUsedShortcode = getMostUsedEmoji();
+1 -2
View File
@@ -43,7 +43,6 @@ export const Video = forwardRef<HTMLVideoElement, VideoProps>(
if (disableControls) {
return (
// eslint-disable-next-line jsx-a11y/media-has-caption
<video
className={classNames(css.Video, className)}
{...props}
@@ -61,7 +60,7 @@ export const Video = forwardRef<HTMLVideoElement, VideoProps>(
onMouseEnter={() => setShowControls(true)}
onMouseLeave={() => setShowControls(false)}
>
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
{}
<video
className={classNames(css.Video, className)}
{...props}
@@ -1,4 +1,3 @@
/* 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 { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
@@ -42,7 +42,7 @@ import {
*/
const fetchAuthenticatedMedia = async (
url: string,
accessToken: string | null,
accessToken: string | undefined,
): Promise<string> => {
try {
let response = await fetch(url, {
@@ -19,7 +19,7 @@ import { getCurrentAccessToken } from '../../../utils/auth';
*/
const fetchAuthenticatedMedia = async (
url: string,
accessToken: string | null,
accessToken: string | undefined,
): Promise<string> => {
try {
let response = await fetch(url, {
@@ -69,6 +69,8 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
const [thumbSrcState, loadThumbSrc] = useAsyncCallback(
useCallback(async () => {
if (!thumbMxcUrl) return undefined;
const encInfo = info.thumbnail_file;
const mediaUrl = mxcUrlToHttp(mx, thumbMxcUrl, useAuthentication) ?? thumbMxcUrl;
@@ -77,7 +79,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
if (encInfo) {
const fileContent = await downloadEncryptedMedia(
mediaUrl,
(encBuf) => decryptFile(encBuf, thumbInfo.mimetype ?? FALLBACK_MIMETYPE, encInfo),
(encBuf) => decryptFile(encBuf, thumbInfo?.mimetype ?? FALLBACK_MIMETYPE, encInfo),
accessToken,
);
return URL.createObjectURL(fileContent);
@@ -99,5 +101,7 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
}
}, [hasValidThumbnail, loadThumbSrc]);
return thumbSrcState.status === AsyncStatus.Success ? renderImage(thumbSrcState.data) : null;
return thumbSrcState.status === AsyncStatus.Success && thumbSrcState.data
? renderImage(thumbSrcState.data)
: null;
}
+3 -5
View File
@@ -5,6 +5,7 @@ import {
MatrixClient,
RoomEvent,
ClientEvent,
EventType,
MatrixEvent,
Room,
IPushRules,
@@ -24,7 +25,6 @@ import { roomToParentsAtom } from '../../state/room/roomToParents';
import { mDirectAtom } from '../../state/mDirectList';
import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath } from '../../pages/pathUtils';
import { RoomNotificationMode } from '../../hooks/useRoomsNotificationPreferences';
import { AccountDataEvent } from '../../../types/matrix/accountData';
import { getNotificationMode, NotificationMode } from '../../hooks/useNotificationMode';
import { useSyncState } from '../../hooks/useSyncState';
import { useBackRoute } from '../../hooks/useBackRoute';
@@ -107,10 +107,10 @@ export function TitleBar({ mx, children }: TitleBarProps) {
}
// We can't use hooks here, so we'll fetch the data directly
const userId = mx.getUserId();
const userId = mx.getUserId() ?? undefined;
// Get push rules for keywords
const pushRulesEvt = mx.getAccountData(AccountDataEvent.PushRules);
const pushRulesEvt = mx.getAccountData(EventType.PushRules);
const pushRules = pushRulesEvt?.getContent<IPushRules>() ?? { global: {} };
const content = pushRules.global.content ?? [];
const keywordPatterns = content
@@ -600,7 +600,6 @@ export function TitleBar({ mx, children }: TitleBarProps) {
const path = [...parentChain, roomName];
return path.join(' > ');
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mx, roomId, roomToParents, mDirects, updateCounter]);
// Get total unread count
@@ -608,7 +607,6 @@ export function TitleBar({ mx, children }: TitleBarProps) {
if (!mx) return 0;
const unreadInfos = getUnreadInfos(mx);
return unreadInfos.reduce((sum, info) => sum + info.total, 0);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mx, updateCounter]);
// Build title parts
@@ -43,7 +43,6 @@ function PreviewVideo({ fileItem }: PreviewVideoProps) {
const fileUrl = useObjectURL(originalFile);
return (
// eslint-disable-next-line jsx-a11y/media-has-caption
<video
style={{
objectFit: 'contain',
@@ -1,117 +0,0 @@
import { style } from '@vanilla-extract/css';
import { DefaultReset, color, config, toRem } from 'folds';
export const TikTokEmbed = style([
DefaultReset,
{
width: toRem(360),
maxWidth: '100%',
backgroundColor: color.SurfaceVariant.Container,
border: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`,
borderRadius: config.radii.R300,
overflow: 'hidden',
},
]);
export const TikTokEmbedHeader = style([
DefaultReset,
{
padding: `${config.space.S200} ${config.space.S300}`,
backgroundColor: color.SurfaceVariant.ContainerActive,
display: 'flex',
alignItems: 'center',
justifyContent: 'space-between',
gap: config.space.S200,
},
]);
export const TikTokEmbedInfo = style([
DefaultReset,
{
display: 'flex',
flexDirection: 'column',
gap: config.space.S100,
flex: 1,
minWidth: 0,
},
]);
export const TikTokEmbedTitle = style({
color: color.Primary.Main,
textDecoration: 'none',
fontWeight: config.fontWeight.W500,
':hover': {
textDecoration: 'underline',
},
});
export const TikTokEmbedAuthor = style({
color: color.SurfaceVariant.OnContainer,
textDecoration: 'none',
opacity: 0.8,
':hover': {
textDecoration: 'underline',
opacity: 1,
},
});
export const TikTokEmbedLink = style({
color: color.Success.Main,
textDecoration: 'none',
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
':hover': {
textDecoration: 'underline',
},
});
export const TikTokThumbnailContainer = style([
DefaultReset,
{
position: 'relative',
width: '100%',
height: toRem(550),
backgroundColor: '#000',
display: 'block',
},
]);
export const TikTokThumbnailButton = style([
DefaultReset,
{
position: 'relative',
width: '100%',
height: toRem(550),
border: 'none',
padding: 0,
cursor: 'pointer',
backgroundColor: '#000',
display: 'block',
overflow: 'hidden',
},
]);
export const TikTokThumbnail = style([
DefaultReset,
{
width: '100%',
height: '100%',
display: 'block',
objectFit: 'cover',
objectPosition: 'center',
},
]);
export const TikTokEmbedContainer = style([
DefaultReset,
{
width: '100%',
height: toRem(550),
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#000',
border: 'none',
display: 'block',
},
]);
@@ -1,277 +0,0 @@
import React, { MouseEvent, useEffect, useState } from 'react';
import { Box, Spinner, Text, as } from 'folds';
import * as css from './TikTokEmbed.css';
import { openExternalUrl } from '../../utils/tauri';
/**
* Regex patterns to match TikTok URLs
*/
const TIKTOK_URL_PATTERNS = [
// Standard tiktok.com/@username/video/VIDEO_ID
/(?:https?:\/\/)?(?:www\.)?tiktok\.com\/@[\w.-]+\/video\/(\d+)/i,
// Short vm.tiktok.com/VIDEO_CODE
/(?:https?:\/\/)?(?:www\.)?vm\.tiktok\.com\/([\w]+)/i,
// Short vt.tiktok.com/VIDEO_CODE
/(?:https?:\/\/)?(?:www\.)?vt\.tiktok\.com\/([\w]+)/i,
// Mobile m.tiktok.com
/(?:https?:\/\/)?(?:www\.)?m\.tiktok\.com\/v\/(\d+)/i,
];
/**
* TikTok oEmbed API base
*/
const TIKTOK_OEMBED_API = 'https://www.tiktok.com/oembed';
/**
* Click handler for external links - uses Tauri shell on desktop/mobile
*/
const handleExternalLinkClick = (e: MouseEvent<HTMLAnchorElement>) => {
const { href } = e.currentTarget;
if (href && (href.startsWith('http://') || href.startsWith('https://'))) {
e.preventDefault();
openExternalUrl(href);
}
};
/**
* Checks if a URL is a TikTok URL
* @param url The URL to check
* @returns True if the URL is a TikTok URL
*/
export function isTikTokUrl(url: string): boolean {
return TIKTOK_URL_PATTERNS.some((pattern) => pattern.test(url));
}
function extractTikTokVideoId(url: string, embedHtml = ''): string | null {
const urlMatch = url.match(/\/video\/(\d+)/i) ?? url.match(/\/v\/(\d+)/i);
const embedMatch = embedHtml.match(/data-video-id=["'](\d+)["']/i);
return urlMatch?.[1] ?? embedMatch?.[1] ?? null;
}
/**
* Fetches TikTok video metadata using oEmbed API
* @param url The TikTok video URL
* @returns Video metadata including title, author, and thumbnail
*/
async function fetchTikTokOEmbed(url: string): Promise<{
title: string;
authorName: string;
authorUrl: string;
thumbnailUrl: string;
embedHtml: string;
videoId: string | null;
} | null> {
try {
const { electron } = window as any;
let data;
if (electron?.tiktok?.getOEmbed) {
data = await electron.tiktok.getOEmbed(url);
} else {
const oembedUrl = `${TIKTOK_OEMBED_API}?url=${encodeURIComponent(url)}`;
const response = await fetch(oembedUrl);
if (!response.ok) return null;
data = await response.json();
}
if (!data) return null;
return {
title: data.title || 'TikTok Video',
authorName: data.author_name || 'Unknown',
authorUrl: data.author_url || url,
thumbnailUrl: data.thumbnail_url || '',
embedHtml: data.html || '',
videoId: extractTikTokVideoId(url, data.html || ''),
};
} catch {
return null;
}
}
type TikTokEmbedState =
| { status: 'loading' }
| {
status: 'loaded';
title: string;
authorName: string;
authorUrl: string;
thumbnailUrl: string;
embedHtml: string;
videoId: string | null;
}
| { status: 'error' };
type TikTokEmbedProps = {
/** The original TikTok URL */
url: string;
};
/**
* TikTok embed component that shows video preview with metadata
*/
export const TikTokEmbed = as<'div', TikTokEmbedProps>(({ url, ...props }, ref) => {
const [state, setState] = useState<TikTokEmbedState>({ status: 'loading' });
const [showPlayer, setShowPlayer] = useState(false);
// Fetch video info on mount
useEffect(() => {
let cancelled = false;
fetchTikTokOEmbed(url).then((info) => {
if (cancelled) return;
if (info) {
setState({
status: 'loaded',
title: info.title,
authorName: info.authorName,
authorUrl: info.authorUrl,
thumbnailUrl: info.thumbnailUrl,
embedHtml: info.embedHtml,
videoId: info.videoId,
});
} else {
setState({ status: 'error' });
}
});
return () => {
cancelled = true;
};
}, [url]);
// Loading state
if (state.status === 'loading') {
return (
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
<div className={css.TikTokEmbedHeader}>
<Text
as="a"
href={url}
target="_blank"
rel="noopener noreferrer"
size="T200"
className={css.TikTokEmbedLink}
onClick={handleExternalLinkClick}
truncate
>
TikTok - Loading...
</Text>
</div>
<Box
className={css.TikTokThumbnailContainer}
alignItems="Center"
justifyContent="Center"
style={{ background: '#000', display: 'flex' }}
>
<Spinner variant="Secondary" size="600" />
</Box>
</Box>
);
}
// Error state - show basic link
if (state.status === 'error') {
return (
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
<div className={css.TikTokEmbedHeader}>
<Text
as="a"
href={url}
target="_blank"
rel="noopener noreferrer"
size="T200"
className={css.TikTokEmbedLink}
onClick={handleExternalLinkClick}
truncate
>
TikTok Video
</Text>
</div>
</Box>
);
}
// Loaded state - show thumbnail or embed
if (!showPlayer) {
return (
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
<div className={css.TikTokEmbedHeader}>
<div className={css.TikTokEmbedInfo}>
<Text
as="a"
href={url}
target="_blank"
rel="noopener noreferrer"
size="T300"
className={css.TikTokEmbedTitle}
onClick={handleExternalLinkClick}
truncate
>
{state.title}
</Text>
<Text
as="a"
href={state.authorUrl}
target="_blank"
rel="noopener noreferrer"
size="T200"
className={css.TikTokEmbedAuthor}
onClick={handleExternalLinkClick}
truncate
>
{state.authorName}
</Text>
</div>
</div>
<button
type="button"
className={css.TikTokThumbnailButton}
onClick={() => setShowPlayer(true)}
aria-label="Play TikTok video"
>
{state.thumbnailUrl ? (
<img src={state.thumbnailUrl} alt={state.title} className={css.TikTokThumbnail} />
) : null}
</button>
</Box>
);
}
const playerUrl = state.videoId
? `https://www.tiktok.com/player/v1/${state.videoId}?autoplay=1`
: null;
// Use TikTok's documented player instead of injecting the oEmbed script.
return (
<Box shrink="No" className={css.TikTokEmbed} direction="Column" {...props} ref={ref}>
<div className={css.TikTokEmbedHeader}>
<Text
as="a"
href={url}
target="_blank"
rel="noopener noreferrer"
size="T200"
className={css.TikTokEmbedLink}
onClick={handleExternalLinkClick}
truncate
>
{state.title}
</Text>
</div>
{playerUrl ? (
<iframe
className={css.TikTokEmbedContainer}
src={playerUrl}
title="TikTok video player"
allow="autoplay; encrypted-media; fullscreen; picture-in-picture"
allowFullScreen
/>
) : (
<div
className={css.TikTokEmbedContainer}
dangerouslySetInnerHTML={{ __html: state.embedHtml }}
/>
)}
</Box>
);
});
-1
View File
@@ -1,5 +1,4 @@
export * from './UrlPreview';
export * from './UrlPreviewCard';
export * from './YouTubeEmbed';
export * from './TikTokEmbed';
export * from './GiphyEmbed';
+1 -1
View File
@@ -86,7 +86,7 @@ export const SidebarDockedCallHeader = style({
color: color.Surface.OnContainer,
cursor: 'grab',
padding: config.space.S100,
borderRadius: config.radii.R200,
borderRadius: config.radii.R300,
selectors: {
'&:hover': {
backgroundColor: color.Surface.ContainerHover,
+10 -26
View File
@@ -367,7 +367,6 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
// Handle remote screenshare (LiveKit track)
if (!share.isLocal && share.track) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const track = share.track as any;
if (typeof track.attach === 'function') {
@@ -464,23 +463,19 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
<script>
let hideTimeout = null;
const closeButton = document.getElementById('closeButton');
function showCloseButton() {
if (hideTimeout) {
clearTimeout(hideTimeout);
hideTimeout = null;
}
closeButton.classList.add('visible');
hideTimeout = setTimeout(() => {
closeButton.classList.remove('visible');
hideTimeout = null;
}, 2000);
}
// Show on any mouse movement
document.addEventListener('mousemove', showCloseButton, true);
// Keep visible when hovering over button
closeButton.addEventListener('mouseenter', () => {
if (hideTimeout) {
@@ -489,7 +484,6 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
}
closeButton.classList.add('visible');
});
// Start hide timer when leaving button
closeButton.addEventListener('mouseleave', () => {
hideTimeout = setTimeout(() => {
@@ -497,12 +491,10 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
hideTimeout = null;
}, 2000);
});
// Close window on click
closeButton.addEventListener('click', () => {
window.close();
});
// Keep video playing - prevent pause from visibility changes or focus loss
function keepVideoPlaying() {
const video = document.querySelector('video');
@@ -510,17 +502,14 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
video.play().catch(() => {});
}
}
// Check every 500ms if video got paused
setInterval(keepVideoPlaying, 500);
// Also resume on visibility change
document.addEventListener('visibilitychange', () => {
if (!document.hidden) {
keepVideoPlaying();
}
});
// Resume on window focus
window.addEventListener('focus', keepVideoPlaying);
</script>
@@ -550,7 +539,6 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
// For remote screenshare, use LiveKit track's attach method (creates fresh video)
if (!share.isLocal && share.track) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const track = share.track as any;
if (typeof track.attach === 'function') {
// track.attach() creates a brand new video element attached to the track
@@ -575,7 +563,6 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
popoutWindow.addEventListener('beforeunload', () => {
// For remote tracks, detach from pop-out
if (!share.isLocal && share.track) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const track = share.track as any;
if (typeof track.detach === 'function') {
const videoContainer = popoutWindow.document.getElementById('videoContainer');
@@ -592,7 +579,7 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
}, [share.isLocal, share.stream, share.track]);
const handleMouseMoveWrapper = useCallback(
(e: React.MouseEvent) => {
(e: React.MouseEvent<HTMLDivElement>) => {
// Clear any pending hide timeout
if (hideTimeoutRef.current) {
clearTimeout(hideTimeoutRef.current);
@@ -604,16 +591,13 @@ export function ScreenShareItem({ share }: ScreenShareItemProps) {
[handleMouseMove],
);
const handleMouseLeaveWrapper = useCallback(
(e: React.MouseEvent) => {
// Delay hiding controls to prevent flickering
hideTimeoutRef.current = setTimeout(() => {
setShowControls(false);
}, 300);
handleMouseLeave(e);
},
[handleMouseLeave],
);
const handleMouseLeaveWrapper = useCallback(() => {
// Delay hiding controls to prevent flickering
hideTimeoutRef.current = setTimeout(() => {
setShowControls(false);
}, 300);
handleMouseLeave();
}, [handleMouseLeave]);
// Cleanup timeout on unmount
useEffect(
@@ -921,7 +905,7 @@ export function CallOverlay() {
// Wait for window to load, then set the video stream
setTimeout(() => {
const videoEl = popoutWindow.document.getElementById('remoteVideo');
const videoEl = popoutWindow.document.querySelector<HTMLVideoElement>('#remoteVideo');
if (videoEl) {
videoEl.srcObject = firstStream;
}
@@ -1385,7 +1369,7 @@ export function CallOverlay() {
{isVideoCall && (
<div className={css.VideoContainer}>
{/* eslint-disable-next-line jsx-a11y/media-has-caption */}
{}
<video
ref={remoteVideoRef}
autoPlay
+1 -3
View File
@@ -80,7 +80,7 @@ function checkWebRTCSupport(): { supported: boolean; details: Record<string, unk
const supported = !!(
navigator.mediaDevices &&
navigator.mediaDevices.getUserMedia &&
typeof navigator.mediaDevices.getUserMedia !== 'undefined' &&
(window.RTCPeerConnection || window.webkitRTCPeerConnection)
);
@@ -235,7 +235,6 @@ export class CallService {
],
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (this.matrixClient as any).sendStateEvent(
roomId,
CALL_MEMBER_EVENT_TYPE,
@@ -248,7 +247,6 @@ export class CallService {
'm.calls': [],
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (this.matrixClient as any).sendStateEvent(
roomId,
CALL_MEMBER_EVENT_TYPE,
@@ -15,6 +15,7 @@ import {
OverlayCenter,
Modal,
} from 'folds';
import { NotificationCountType, type RoomAccountDataEvents } from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageHeader } from '../../../components/page';
@@ -78,7 +79,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const info = {
roomId: room.roomId,
name: room.name,
canonicalAlias: room.canonicalAlias,
canonicalAlias: room.getCanonicalAlias(),
altAliases: room.getAltAliases(),
isSpace: isSpace(room),
joinRule: room.getJoinRule(),
@@ -93,8 +94,8 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
powerLevelTags: powerLevelTags || null,
tags: room.tags,
notificationCounts: {
total: room.getRoomUnreadNotificationCount('total'),
highlight: room.getRoomUnreadNotificationCount('highlight'),
total: room.getRoomUnreadNotificationCount(NotificationCountType.Total),
highlight: room.getRoomUnreadNotificationCount(NotificationCountType.Highlight),
},
timeline: {
oldestEventTs: oldestEvent?.getTs(),
@@ -138,7 +139,11 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const submitAccountData: AccountDataSubmitCallback = useCallback(
async (type, content) => {
await mx.setRoomAccountData(room.roomId, type, content);
await mx.setRoomAccountData(
room.roomId,
type as keyof RoomAccountDataEvents,
content as RoomAccountDataEvents[keyof RoomAccountDataEvents],
);
},
[mx, room.roomId],
);
@@ -1,4 +1,3 @@
/* eslint-disable react/no-array-index-key */
import React, { useCallback, useEffect, useMemo, useState } from 'react';
import { Badge, Box, Button, Chip, config, Menu, Spinner, Text } from 'folds';
import { EventType } from 'matrix-js-sdk';
@@ -1,4 +1,3 @@
/* eslint-disable react/no-array-index-key */
import React, { useState, MouseEventHandler, ReactNode } from 'react';
import FocusTrap from 'focus-trap-react';
import {
@@ -14,6 +14,7 @@ import {
import FocusTrap from 'focus-trap-react';
import { useAtomValue } from 'jotai';
import { EventType } from 'matrix-js-sdk';
import type { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/@types/state_events';
import { Icon, Icons } from '../../components/icons';
import { useAllJoinedRoomsSet, useGetRoom } from '../../hooks/useGetRoom';
import { SpaceProvider } from '../../hooks/useSpace';
@@ -78,7 +79,7 @@ function CreateRoomModal({ state }: CreateRoomModalProps) {
'',
);
if (parentJoinRulesEvent) {
const joinRulesContent = parentJoinRulesEvent.getContent();
const joinRulesContent = parentJoinRulesEvent.getContent<RoomJoinRulesEventContent>();
await mx.sendStateEvent(newRoomId, EventType.RoomJoinRules, joinRulesContent, '');
}
@@ -54,7 +54,7 @@ export function ForumAuthorIdentity({
return (
<div className={identityClass}>
<span className={avatarClass} aria-hidden>
<Avatar size="200" radii="300" shrink="No">
<Avatar size="200" radii="300">
<UserAvatar
userId={sender}
src={avatarUrl}
+13 -11
View File
@@ -5,12 +5,14 @@ import { IconButton, Line, PopOut } from 'folds';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import {
AUTOCOMPLETE_PREFIXES,
CustomEditor,
Toolbar,
EmoticonAutocomplete,
AutocompletePrefix,
AutocompleteQuery,
getAutocompleteQuery,
getPrevWorldRange,
createEmoticonElement,
moveCursor,
safeFocusEditor,
@@ -62,17 +64,17 @@ export function ForumChatComposer({
[enterForNewline, onSend],
);
const handleKeyUp: KeyboardEventHandler = useCallback(
(evt) => {
const prevWordRange = getAutocompleteQuery(editor, evt);
if (prevWordRange?.prefix === AutocompletePrefix.Emoticon) {
setAutocompleteQuery({ prefix: AutocompletePrefix.Emoticon, range: prevWordRange.range });
return;
}
setAutocompleteQuery(undefined);
},
[editor],
);
const handleKeyUp: KeyboardEventHandler = useCallback(() => {
const prevWordRange = getPrevWorldRange(editor);
const query = prevWordRange
? getAutocompleteQuery<AutocompletePrefix>(editor, prevWordRange, AUTOCOMPLETE_PREFIXES)
: undefined;
if (query?.prefix === AutocompletePrefix.Emoticon) {
setAutocompleteQuery(query);
return;
}
setAutocompleteQuery(undefined);
}, [editor]);
const handleEmoticonSelect = (key: string, shortcode: string) => {
editor.insertNode(createEmoticonElement(key, shortcode));
+7 -1
View File
@@ -44,7 +44,13 @@ export function ForumEventContent({
}
const content = getContent();
const msgType = typeof content.msgtype === 'string' ? content.msgtype : 'm.text';
const msgType =
typeof content === 'object' &&
content !== null &&
'msgtype' in content &&
typeof content.msgtype === 'string'
? content.msgtype
: 'm.text';
return (
<div className={theme.ForumEventContentRoot}>
+1 -1
View File
@@ -323,7 +323,7 @@ export function ForumNewPostModal({
<Box className={t.ForumPostModalActions}>
<Button
type="button"
variant="SurfaceVariant"
variant="Secondary"
size="400"
radii="300"
onClick={handleClose}
@@ -137,7 +137,7 @@ export function ForumPostUploadField({
variant="SurfaceVariant"
size="300"
radii="300"
onClick={pickFiles}
onClick={() => pickFiles('*')}
disabled={disabled}
aria-label="Attach files"
>
@@ -154,7 +154,7 @@ export function ForumPostUploadField({
variant="SurfaceVariant"
size="300"
radii="300"
onClick={pickFiles}
onClick={() => pickFiles('*')}
disabled={disabled}
aria-label="Attach more files"
>
@@ -180,7 +180,6 @@ export function ForumPostUploadField({
.reverse()
.map((fileItem, index) => (
<UploadCardRenderer
// eslint-disable-next-line react/no-array-index-key
key={index}
isEncrypted={!!fileItem.encInfo}
fileItem={fileItem}
@@ -52,7 +52,7 @@ export function ForumReplyComposer({
</PowerLevelsContextProvider>
{onCancel && (
<div className={t.ForumReplyFormActions}>
<Button type="button" variant="SurfaceVariant" size="300" onClick={onCancel}>
<Button type="button" variant="Secondary" size="300" onClick={onCancel}>
<Text size="B400">Cancel</Text>
</Button>
</div>
@@ -108,7 +108,7 @@ export function ForumRichReplyComposer({
{onCancel && (
<Button
type="button"
variant="SurfaceVariant"
variant="Secondary"
size="300"
onClick={onCancel}
disabled={sending}
+1 -1
View File
@@ -307,7 +307,7 @@ type ForumThreadDetailProps = {
onReplySent?: (reply: ForumPost) => void;
};
type ForumThreadDetailBodyProps = ForumThreadDetailProps & {
type ForumThreadDetailBodyProps = Omit<ForumThreadDetailProps, 'initialPost'> & {
post: ForumPost;
room: Room;
onPostUpdate: (post: ForumPost | null) => void;
+21 -15
View File
@@ -2,13 +2,17 @@ import {
Direction,
EventType,
type IContent,
type IEventRelation,
type IRoomEvent,
type MatrixClient,
type MatrixEvent,
type Room,
MsgType,
RelationType,
} from 'matrix-js-sdk';
import type {
RoomMessageEventContent,
RoomMessageTextEventContent,
} from 'matrix-js-sdk/lib/@types/events';
import type { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { getMemberDisplayName, getSpaceChildren, isSpace } from '../../utils/room';
import type { ForumPost, ForumTopic } from './types';
@@ -675,7 +679,7 @@ export async function sendForumPost(
}
const res = await mx.sendMessage(roomId, {
msgtype: 'm.text',
msgtype: MsgType.Text,
body: `${title}\n\n${plainText}`,
'com.matrixsso.title': title,
format: 'org.matrix.custom.html',
@@ -703,7 +707,7 @@ export async function sendForumMediaRoot(
const res = await mx.sendMessage(roomId, {
...content,
'com.matrixsso.title': trimmedTitle,
});
} as RoomMessageEventContent);
return res.event_id;
}
@@ -726,10 +730,9 @@ export async function sendForumThreadAttachment(
'm.relates_to': {
rel_type: RelationType.Thread,
event_id: rootId,
is_falling_back: false,
'm.in_reply_to': { event_id: parentId },
} as IEventRelation,
});
},
} as unknown as RoomMessageEventContent);
return res.event_id;
}
@@ -760,15 +763,9 @@ export function sendForumReply(
let formattedHtml = typeof message === 'string' ? '' : String(message.formattedHtml || '').trim();
formattedHtml = formattedHtml.replace(/(<br\s*\/?>\s*)+$/gi, '');
const content: Record<string, unknown> = {
msgtype: 'm.text',
const content: RoomMessageTextEventContent = {
msgtype: MsgType.Text,
body: plainText,
'm.relates_to': {
rel_type: RelationType.Thread,
event_id: rootId,
is_falling_back: false,
'm.in_reply_to': { event_id: parentId },
},
};
if (formattedHtml) {
@@ -776,7 +773,16 @@ export function sendForumReply(
content.formatted_body = formattedHtml;
}
return mx.sendMessage(roomId, content).then((res) => res.event_id);
return mx
.sendMessage(roomId, {
...content,
'm.relates_to': {
rel_type: RelationType.Thread,
event_id: rootId,
'm.in_reply_to': { event_id: parentId },
},
})
.then((res) => res.event_id);
}
export function createForumPostFromPayload(
+22 -22
View File
@@ -1,5 +1,6 @@
import React from 'react';
import type { IconSrc } from 'folds';
import React, { forwardRef } from 'react';
import type { LucideProps } from 'lucide-react';
import type { IconSrc } from '../../components/icons';
/** Lucide paths (ISC) — same icons as matrixsso sort toggle (flame / sparkles / crown). */
@@ -36,26 +37,25 @@ const CROWN: SvgNode[] = [
['path', { d: 'M5 21h14' }],
];
function lucideIcon(nodes: SvgNode): IconSrc {
return function Icon() {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
focusable="false"
>
{nodes.map(([tag, attrs]) =>
React.createElement(tag, { key: `${tag}-${attrs.d ?? attrs.cx ?? ''}`, ...attrs }),
)}
</svg>
);
};
function lucideIcon(nodes: SvgNode[]): IconSrc {
return forwardRef<SVGSVGElement, LucideProps>((_, ref) => (
<svg
ref={ref}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth={2}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden
focusable="false"
>
{nodes.map(([tag, attrs]) =>
React.createElement(tag, { key: `${tag}-${attrs.d ?? attrs.cx ?? ''}`, ...attrs }),
)}
</svg>
));
}
/** hot → flame, new → sparkles, top → crown (matrixsso SORT_LUCIDE_ICONS) */
+1 -1
View File
@@ -1136,7 +1136,7 @@ export const ForumSenderLabel = style({
export const ForumAuthorServer = style({
background: color.SurfaceVariant.Container,
border: `${config.borderWidth.B300} solid ${color.SurfaceVariant.ContainerLine}`,
borderRadius: config.radii.R200,
borderRadius: config.radii.R300,
color: muted,
fontSize: toRem(12),
fontWeight: 600,
@@ -107,7 +107,7 @@ export function useForumMessageReactions(room: Room, mEvent: MatrixEvent | undef
(reactions.find(eventWithShortcode)?.getContent().shortcode as string | undefined);
mx.sendEvent(
room.roomId,
MessageEvent.Reaction as never,
EventType.Reaction,
getReactionContent(targetEventId, key, rShortcode),
).finally(() => {
bumpRelations();
+1 -1
View File
@@ -321,7 +321,7 @@ export function LobbyHeader({ showProfile, showSpaceToolbar, powerLevels }: Lobb
</IconButton>
</Box>
)}
<Avatar size="300" shrink="No">
<Avatar size="300">
<RoomAvatar
roomId={space.roomId}
src={avatarUrl}
+3 -1
View File
@@ -8,6 +8,7 @@ import {
HierarchyItemSpace,
isHierarchySpaceRoom,
useFetchSpaceHierarchyLevel,
viaFromParent,
} from '../../hooks/useSpaceHierarchy';
import { IPowerLevels } from '../../hooks/usePowerLevels';
import { useMatrixClient } from '../../hooks/useMatrixClient';
@@ -259,7 +260,8 @@ export const SpaceHierarchy = forwardRef<HTMLDivElement, SpaceHierarchyProps>(
const subRoomItem: HierarchyItemRoom = {
roomId: subRoomId,
parentId: roomItem.roomId,
content: {},
content: { via: viaFromParent(roomSummary, subRoomId) },
ts: 0,
};
const subRoomDragging =
draggingItem?.roomId === subRoomId &&
+1 -1
View File
@@ -35,7 +35,7 @@ export function RoomAppView({ room, onShowChat }: RoomAppViewProps) {
<Page>
<Header className={css.Header} size="600">
<Box grow="Yes" alignItems="Center" gap="200">
<Box grow="Yes" alignItems="Center" gap="200" minWidth="0">
<Box grow="Yes" alignItems="Center" gap="200">
<Text size="H6" truncate>
{title}
</Text>
+21 -29
View File
@@ -35,32 +35,7 @@ export function scopeRoomAppCss(css: string, scopeSelector: string): string {
return `${scoped}{${body}}`;
};
const rewriteBlock = (block: string): string => {
const trimmed = block.trim();
if (!trimmed) return '';
if (trimmed.startsWith('@')) {
const open = trimmed.indexOf('{');
if (open === -1) return `${trimmed};`;
const header = trimmed.slice(0, open).trim();
const inner = trimmed.slice(open + 1);
// @keyframes / @font-face: keep as-is (namespaced risk is low for MVP)
if (/^@(keyframes|font-face)\b/i.test(header)) {
return `${header}{${inner}}`;
}
// @media / @supports: re-scope nested rules
const nested = rewriteCssChunk(inner);
return `${header}{${nested}}`;
}
const open = trimmed.indexOf('{');
if (open === -1) return '';
const selectors = trimmed.slice(0, open);
const body = trimmed.slice(open + 1);
return scopeRule(selectors, body);
};
const rewriteCssChunk = (chunk: string): string => {
function rewriteChunk(chunk: string): string {
const parts: string[] = [];
let depth = 0;
let start = 0;
@@ -70,15 +45,32 @@ export function scopeRoomAppCss(css: string, scopeSelector: string): string {
else if (ch === '}') {
depth -= 1;
if (depth === 0) {
parts.push(rewriteBlock(chunk.slice(start, i)));
const block = chunk.slice(start, i).trim();
start = i + 1;
if (block) {
const open = block.indexOf('{');
if (open === -1) {
parts.push(`${block};`);
} else {
const header = block.slice(0, open).trim();
const inner = block.slice(open + 1);
if (!header.startsWith('@')) {
parts.push(scopeRule(header, inner));
} else if (/^@(keyframes|font-face)\b/i.test(header)) {
parts.push(`${header}{${inner}}`);
} else {
// @media / @supports: re-scope nested rules
parts.push(`${header}{${rewriteChunk(inner)}}`);
}
}
}
}
}
}
return parts.filter(Boolean).join('\n');
};
}
return rewriteCssChunk(sanitized);
return rewriteChunk(sanitized);
}
export function isAllowedRoomAppImageSrc(src: string): boolean {
@@ -93,7 +93,7 @@ export function CallParticipantsIndicator({ roomId }: CallParticipantsIndicatorP
/**
* Get the appropriate audio icon for a participant
*/
const getAudioIcon = (userId: string): string => {
const getAudioIcon = (userId: string) => {
if (isLocalUserDeafened(userId)) {
return Icons.VolumeMute;
}
@@ -82,7 +82,6 @@ export function SubRooms() {
children: newSubRooms,
};
// Custom state event type - need to cast
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await mx.sendStateEvent(room.roomId, StateEvent.PaarrotSubRooms as any, content, '');
},
[mx, room],
@@ -126,7 +125,6 @@ export function SubRooms() {
// Add as m.space.child to the space
await mx.sendStateEvent(
parentSpaceId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
StateEvent.SpaceChild as any,
{ via: spaceViaServers },
roomIdToAdd,
+5 -4
View File
@@ -98,7 +98,7 @@ import {
import { getMemberDisplayName, getMentionContent, trimReplyFromBody } from '../../utils/room';
import { CommandAutocomplete } from './CommandAutocomplete';
import { Command, SHRUG, TABLEFLIP, UNFLIP, useCommands } from '../../hooks/useCommands';
import { pluginRegistry } from '../settings/plugins/PluginAPI';
import { pluginRegistry, type CommandArg } from '../settings/plugins/PluginAPI';
import { PluginButtonSlot } from '../settings/plugins/PluginButtonSlot';
import { mobileOrTablet } from '../../utils/user-agent';
import { ReplyLayout, ThreadIndicator } from '../../components/message';
@@ -219,7 +219,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
const [commandHint, setCommandHint] = useState<{
command: string;
description: string;
args?: string[];
args?: string[] | CommandArg[];
}>();
const sendTypingStatus = useTypingStatusUpdater(mx, roomId);
@@ -635,7 +635,6 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
.reverse()
.map((fileItem, index) => (
<UploadCardRenderer
// eslint-disable-next-line react/no-array-index-key
key={index}
isEncrypted={!!fileItem.encInfo}
fileItem={fileItem}
@@ -733,7 +732,9 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
{commandHint.args && commandHint.args.length > 0 && (
<span style={{ opacity: 0.6 }}>
{' '}
{commandHint.args.map((arg) => `[${arg}]`).join(' ')}
{commandHint.args
.map((arg) => `[${typeof arg === 'string' ? arg : arg.name}]`)
.join(' ')}
</span>
)}
</Text>
+3 -1
View File
@@ -1,5 +1,5 @@
import { style } from '@vanilla-extract/css';
import { recipe } from '@vanilla-extract/recipes';
import { RecipeVariants, recipe } from '@vanilla-extract/recipes';
import { DefaultReset, color, config, toRem } from 'folds';
export const TimelineFloat = recipe({
@@ -29,6 +29,8 @@ export const TimelineFloat = recipe({
},
});
export type TimelineFloatVariants = RecipeVariants<typeof TimelineFloat>;
export const DmNameplateBackground = style({
position: 'absolute',
inset: 0,
+2 -1
View File
@@ -2011,7 +2011,8 @@ export function RoomTimeline({ room, eventId, roomInputRef, editor }: RoomTimeli
},
[StateEvent.CallMember]: (mEventId, mEvent, item) => {
const senderId = mEvent.getSender() ?? '';
const senderName = getMemberDisplayName(room, senderId) || getMxIdLocalPart(senderId);
const senderName =
getMemberDisplayName(room, senderId) || getMxIdLocalPart(senderId) || senderId;
const content = mEvent.getContent();
const prevContent = mEvent.getPrevContent();
+1 -1
View File
@@ -330,7 +330,7 @@ function CallIndicator({ roomId }: CallIndicatorProps) {
offset={8}
tooltip={
<SpeechBubble tail="top" tailX="50%">
<Box direction="Column" gap="50">
<Box direction="Column" gap="100">
<Text
size="T300"
style={{ fontWeight: 600, color: color.SurfaceVariant.OnContainer }}
-5
View File
@@ -270,7 +270,6 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
repliesCount: replies.length,
threadLength: t.length,
hasRootEvent: !!t.rootEvent,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
initialEventsFetched: (t as any).initialEventsFetched,
liveTimelineEventsCount: liveTimelineEvents.length,
threadEventsMatch: replies.length === liveTimelineEvents.length,
@@ -334,7 +333,6 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
threadExists: !!thread,
threadLength: thread?.length,
eventsCount: thread?.events?.length,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
initialEventsFetched: (thread as any)?.initialEventsFetched,
});
@@ -351,7 +349,6 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
thread.on(ThreadEvent.NewReply, handleUpdate);
thread.on(ThreadEvent.Update, handleUpdate);
// Fires when initial events are loaded after the SDK paginates the thread.
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(thread as any).on(RoomEvent.TimelineReset, handleUpdate);
// Also listen to Timeline events which fire when events are added
@@ -378,7 +375,6 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
if (thread) {
thread.off(ThreadEvent.NewReply, handleUpdate);
thread.off(ThreadEvent.Update, handleUpdate);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(thread as any).off(RoomEvent.TimelineReset, handleUpdate);
thread.off(RoomEvent.Timeline, handleUpdate);
}
@@ -484,7 +480,6 @@ export function ThreadView({ room, threadRootId }: ThreadViewProps) {
(reactions.find(eventWithShortcode)?.getContent().shortcode as string | undefined);
mx.sendEvent(
room.roomId,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
MessageEvent.Reaction as any,
getReactionContent(targetEventId, key, rShortcode),
);
@@ -2,6 +2,7 @@ import { MatrixClient } from 'matrix-js-sdk';
import { EMOJI_REG_G, JUMBO_EMOJI_REG } from '../../../utils/regex';
import { trimReplyFromBody } from '../../../utils/room';
import { emojis } from '../../../plugins/emoji';
import { MessageEvent } from '../../../../types/matrix/room';
import { EMOJI_CONFETTI_EVENT_TYPE, EmojiConfettiContent } from './types';
const SHORTCODE_PATTERN = /:([^\s:]+):/g;
@@ -43,5 +44,5 @@ export function sendEmojiConfettiEvent(
target_event_id: targetEventId,
};
return mx.sendEvent(roomId, EMOJI_CONFETTI_EVENT_TYPE as never, content);
return mx.sendEvent(roomId, MessageEvent.RelayEmojiConfetti, content);
}
@@ -115,7 +115,6 @@ export const MessageQuickReactions = as<'div', MessageQuickReactionsProps>(
{mostUsedEmojis.map((emoji) => (
<IconButton
key={emoji.unicode}
className={css.MessageQuickReaction}
size="300"
variant="SurfaceVariant"
radii="Pill"
@@ -8,6 +8,7 @@ import React, {
import { Box, Chip, IconButton, Line, PopOut, RectCords, Spinner, Text, as, config } from 'folds';
import { Editor, Transforms } from 'slate';
import { IContent, IMentions, MatrixEvent, RelationType, Room } from 'matrix-js-sdk';
import type { RoomMessageEventContent } from 'matrix-js-sdk/lib/@types/events';
import { isKeyHotkey } from 'is-hotkey';
import { Icon, Icons } from '../../../components/icons';
import {
@@ -141,7 +142,7 @@ export const MessageEditor = as<'div', MessageEditorProps>(
},
};
return mx.sendMessage(roomId, content);
return mx.sendMessage(roomId, content as RoomMessageEventContent);
}, [mx, editor, roomId, mEvent, isMarkdown, getPrevBodyAndFormattedBody]),
);
@@ -32,7 +32,7 @@ import { ContainerColor } from '../../../styles/ContainerColor.css';
const fetchAuthenticatedMedia = async (
url: string,
accessToken: string | null,
accessToken: string | undefined,
): Promise<string> => {
try {
let response = await fetch(url, {
@@ -127,9 +127,9 @@ function PinnedMessage({
}, [room, eventId, mx]),
);
const sender = pinnedEvent?.getSender();
const sender = pinnedEvent?.getSender() ?? '';
const senderAvatarMxc = sender ? getMemberAvatarMxc(room, sender) : undefined;
const customUserColor = useOtherUserColor(sender ?? '', room);
const customUserColor = useOtherUserColor(sender, room);
const handleOpenClick: MouseEventHandler = (evt) => {
evt.stopPropagation();
@@ -178,7 +178,7 @@ function PinnedMessage({
</Box>
);
const displayName = getMemberDisplayName(room, sender!) ?? getMxIdLocalPart(sender!) ?? sender!;
const displayName = getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender) ?? sender;
const getContent = (() => pinnedEvent.getContent()) as GetContentCallback;
const memberPowerTag = getMemberPowerTag(sender);
@@ -77,7 +77,7 @@ export function ProfileEffectHeroPreview({
<div className={css.ProfileEffectHeroInfo}>
<Text
size="T100"
size="T200"
className={css.ProfileEffectHeroName}
title={resolvedName}
style={{ color: nameColor }}
@@ -12,6 +12,7 @@ import {
OverlayCenter,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import type { AccountDataEvents } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageHeader } from '../../../components/page';
import { SequenceCard } from '../../../components/sequence-card';
@@ -107,7 +108,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
const submitAccountData: AccountDataSubmitCallback = useCallback(
async (type, content) => {
await mx.setAccountData(type, content);
await mx.setAccountData(type as keyof AccountDataEvents, content);
},
[mx],
);
@@ -118,7 +119,11 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
return (
<AccountDataEditor
type={accountDataType ?? undefined}
content={accountDataType ? mx.getAccountData(accountDataType)?.getContent() : undefined}
content={
accountDataType
? mx.getAccountData(accountDataType as keyof AccountDataEvents)?.getContent()
: undefined
}
submitChange={submitAccountData}
requestClose={() => setAccountDataType(undefined)}
/>
@@ -239,7 +244,7 @@ export function DeveloperTools({ requestClose }: DeveloperToolsProps) {
</PageContent>
</Scroll>
</Box>
{profileFieldKey !== undefined && (
{profileFieldKey && (
<Overlay open backdrop={<OverlayBackdrop />}>
<OverlayCenter>
<FocusTrap
@@ -82,8 +82,8 @@ export function ProfileFields({
<Box gap="100" alignItems="Center">
{editable && (
<IconButton
size="200"
radii="Round"
size="300"
radii="Pill"
title={`Delete ${key}`}
onClick={() => onDelete(key)}
>
@@ -25,7 +25,6 @@ export type {
IPluginEventClient,
PluginMarketplaceClientOptions,
PluginMarketplaceHostAdapter,
PluginMarketplaceInstalledRecord,
PluginMarketplaceManagerOptions,
PluginRegistryOptions,
PluginContextOptions,
@@ -1,6 +1,7 @@
import React, { useSyncExternalStore } from 'react';
import { IconButton } from 'folds';
import * as lucide from 'lucide-react';
import type { LucideIcon } from 'lucide-react';
import { UILocation } from '@paarrot/plugin-manager';
import { Icon, Icons, type IconName } from '../../../components/icons';
import { pluginRegistry } from './PluginAPI';
@@ -52,12 +53,7 @@ function renderPluginButtonIcon(button: { icon?: string; lucideIcon?: string }):
}
if (lucideName) {
const IconComponent = (
lucide as Record<
string,
React.ComponentType<{ size?: number; strokeWidth?: number }> | undefined
>
)[lucideName];
const IconComponent = lucide[lucideName as keyof typeof lucide] as LucideIcon | undefined;
if (IconComponent) {
return <IconComponent size={18} strokeWidth={2} aria-hidden />;
}
@@ -71,7 +71,7 @@ function SettingRenderer({
variant="Background"
value={value ?? definition.default ?? ''}
onChange={(e) => onChange(e.target.value)}
placeholder={definition.default}
placeholder={typeof definition.default === 'string' ? definition.default : ''}
/>
</SettingTile>
);
@@ -127,7 +127,7 @@ function SettingRenderer({
<Menu>
{definition.options.map((option) => (
<MenuItem
key={option.value}
key={String(option.value)}
size="300"
after={
currentValue === option.value ? (
@@ -214,7 +214,7 @@ function PluginSettingsRenderer({ pluginId }: { pluginId: string }) {
if (!schema || Object.keys(schema).length === 0) {
return (
<Box padding="300">
<Box>
<Text size="T300" priority="300">
No settings available for this plugin.
</Text>
@@ -406,12 +406,12 @@ export function Plugins({ requestClose }: PluginsProps) {
<Page>
<PageHeader>
<Box grow="Yes" alignItems="Center" gap="200">
<Header size="H3" className="truncate">
<Header size="400" className="truncate">
Plugins
</Header>
</Box>
<Box shrink="No" gap="200">
<Button variant="Background" size="300" onClick={requestClose}>
<Button variant="Secondary" size="300" onClick={requestClose}>
<Text size="B300">Close</Text>
</Button>
</Box>
@@ -454,7 +454,7 @@ export function Plugins({ requestClose }: PluginsProps) {
searchQuery && (
<IconButton
size="300"
variant="SurfaceLow"
variant="Surface"
radii="300"
onClick={() => setSearchQuery('')}
>
@@ -688,7 +688,7 @@ export function Plugins({ requestClose }: PluginsProps) {
direction="Column"
style={{
borderTop: `1px solid ${color.Surface.ContainerLine}`,
background: color.Surface.ContainerLowest,
background: color.Surface.Container,
}}
>
<PluginSettingsRenderer pluginId={plugin.id} />
@@ -142,6 +142,7 @@ export function Permissions({ requestClose }: PermissionsProps) {
// Preserve all users in child room who have power >= mine
if (childPowerLevels.users) {
Object.entries(childPowerLevels.users).forEach(([userId, power]) => {
if (typeof power !== 'number') return;
if (power >= myPowerInChild) {
mergedUsers[userId] = power;
}
@@ -249,6 +250,7 @@ export function Permissions({ requestClose }: PermissionsProps) {
// Preserve all users in child room who have power >= mine
if (childPowerLevels.users) {
Object.entries(childPowerLevels.users).forEach(([userId, power]) => {
if (typeof power !== 'number') return;
if (power >= myPowerInChild) {
mergedUsers[userId] = power;
}
@@ -418,7 +420,10 @@ export function Permissions({ requestClose }: PermissionsProps) {
)}
{syncError && (
<Text size="T300" style={{ color: color.Critical.Main }}>
Error syncing permissions: {syncState.error.message}
Error syncing permissions:{' '}
{syncState.error instanceof Error
? syncState.error.message
: String(syncState.error)}
</Text>
)}
</Box>
@@ -452,7 +457,10 @@ export function Permissions({ requestClose }: PermissionsProps) {
)}
{powerLevelsSyncError && (
<Text size="T300" style={{ color: color.Critical.Main }}>
Error syncing power levels: {syncPowerLevelsState.error.message}
Error syncing power levels:{' '}
{syncPowerLevelsState.error instanceof Error
? syncPowerLevelsState.error.message
: String(syncPowerLevelsState.error)}
</Text>
)}
</Box>
+2 -1
View File
@@ -1,10 +1,11 @@
import { useState, useCallback } from 'react';
import type { AccountDataEvents } from 'matrix-js-sdk';
import { useMatrixClient } from './useMatrixClient';
import { useAccountDataCallback } from './useAccountDataCallback';
export function useAccountData(eventType: string) {
const mx = useMatrixClient();
const [event, setEvent] = useState(() => mx.getAccountData(eventType));
const [event, setEvent] = useState(() => mx.getAccountData(eventType as keyof AccountDataEvents));
useAccountDataCallback(
mx,
+2 -1
View File
@@ -1,8 +1,9 @@
import { useCallback, useMemo } from 'react';
import { useMatrixClient } from './useMatrixClient';
import { useAccountData } from './useAccountData';
import { AccountDataEvent } from '../../types/matrix/accountData';
const PAARROT_EMOJI_USAGE_EVENT = 'paarrot.favemojis';
const PAARROT_EMOJI_USAGE_EVENT = AccountDataEvent.PaarrotFavemojis;
const MAX_TRACKED_EMOJIS = 50;
export type EmojiUsageData = {
+1 -1
View File
@@ -3,7 +3,7 @@ import { useReducer } from 'react';
const reducer = (prevCount: number): number => prevCount + 1;
export const useForceUpdate = (): [number, () => void] => {
const [state, dispatch] = useReducer<typeof reducer>(reducer, 0);
const [state, dispatch] = useReducer(reducer, 0);
return [state, dispatch];
};
+6 -5
View File
@@ -51,14 +51,15 @@ const getPersonalEmbedFiltersFromRoom = (room: Room): EmbedFiltersContent => {
* @returns A tuple of [filters, setFilters]
*/
export const useRoomEmbedFilters = (
room: Room,
room: Room | undefined,
): [EmbedFiltersContent, (filters: EmbedFiltersContent) => Promise<void>] => {
const mx = useMatrixClient();
const [filters, setFiltersState] = useState<EmbedFiltersContent>(() =>
getPersonalEmbedFiltersFromRoom(room),
room ? getPersonalEmbedFiltersFromRoom(room) : DEFAULT_EMBED_FILTERS,
);
useEffect(() => {
if (!room) return undefined;
const handleAccountData: RoomEventHandlerMap[RoomEvent.AccountData] = (event) => {
if (event.getType() === EMBED_FILTERS_ACCOUNT_DATA_TYPE) {
setFiltersState(getPersonalEmbedFiltersFromRoom(room));
@@ -73,9 +74,10 @@ export const useRoomEmbedFilters = (
const setFilters = useCallback(
async (newFilters: EmbedFiltersContent): Promise<void> => {
if (!room) return;
await mx.setRoomAccountData(room.roomId, EMBED_FILTERS_ACCOUNT_DATA_TYPE, newFilters);
},
[mx, room.roomId],
[mx, room?.roomId],
);
return [filters, setFilters];
@@ -87,7 +89,7 @@ export const useRoomEmbedFilters = (
* @param room - The Matrix room
* @returns The room-wide embed filters content
*/
export const useRoomWideEmbedFilters = (room: Room): EmbedFiltersContent => {
export const useRoomWideEmbedFilters = (room: Room | undefined): EmbedFiltersContent => {
const stateEvent = useStateEvent(room, StateEvent.RoomEmbedFilters);
if (!stateEvent) {
return DEFAULT_EMBED_FILTERS;
@@ -112,7 +114,6 @@ export const useSetRoomWideEmbedFilters = (
const setFilters = useCallback(
async (newFilters: EmbedFiltersContent): Promise<void> => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await mx.sendStateEvent(room.roomId, StateEvent.RoomEmbedFilters as any, newFilters);
},
[mx, room.roomId],
-1
View File
@@ -242,7 +242,6 @@ export const useRoomMediaEvents = (room: Room) => {
cancelled = true;
};
// Only re-bootstrap when switching rooms — not when callback identities change.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [roomId]);
return { items, loading, hasMore, loadMore };
+9 -5
View File
@@ -1,7 +1,7 @@
import { atom, useAtom, useAtomValue } from 'jotai';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { MatrixClient, MatrixError, Room } from 'matrix-js-sdk';
import { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import type { IHierarchyRoom } from 'matrix-js-sdk/lib/@types/spaces';
import { QueryFunction, useInfiniteQuery } from '@tanstack/react-query';
import { useMatrixClient } from './useMatrixClient';
import { roomToParentsAtom } from '../state/room/roomToParents';
@@ -55,6 +55,10 @@ export function buildParentByRoomId(rooms: Iterable<IHierarchyRoom>): Map<string
return parentByRoomId;
}
/** Hierarchy summaries carry no via; the parent's space.child relation does. */
export const viaFromParent = (parent: IHierarchyRoom | undefined, childId: string): string[] =>
parent?.children_state?.find((childState) => childState.state_key === childId)?.content.via ?? [];
/** Space or forum container in hierarchy API (room_type may be absent on some servers). */
export function isHierarchySpaceRoom(room: IHierarchyRoom | undefined): boolean {
if (!room) return false;
@@ -101,13 +105,13 @@ const getChildRoomsFromSummaries = (
getRoom: GetRoomCallback,
): HierarchyItemRoom[] => {
const childItems: HierarchyItemRoom[] = [];
hierarchySummaries.forEach((summary, roomId) => {
hierarchySummaries.forEach((_, roomId) => {
if (parentByRoomId.get(roomId) !== spaceItemId) return;
if (isChildSpace(roomId, getRoom, spaceRooms, hierarchySummaries)) return;
childItems.push({
roomId,
content: { via: summary.via ?? [] },
content: { via: viaFromParent(hierarchySummaries.get(spaceItemId), roomId) },
ts: 0,
parentId: spaceItemId,
});
@@ -157,14 +161,14 @@ const getHierarchySpaces = (
}
// Unjoined sub-spaces: discover children from hierarchy API summaries.
hierarchySummaries.forEach((summary, roomId) => {
hierarchySummaries.forEach((_, roomId) => {
if (parentByRoomId.get(roomId) !== spaceItem.roomId) return;
if (!isChildSpace(roomId, getRoom, spaceRooms, hierarchySummaries)) return;
if (spaceItems.find((item) => item.roomId === roomId)) return;
findAndCollectHierarchySpaces({
roomId,
content: { via: summary.via ?? [] },
content: { via: viaFromParent(hierarchySummaries.get(spaceItem.roomId), roomId) },
ts: 0,
space: true,
parentId: spaceItem.roomId,
+4 -4
View File
@@ -5,14 +5,15 @@ import { useForceUpdate } from './useForceUpdate';
import { getStateEvent } from '../utils/room';
import { StateEvent } from '../../types/matrix/room';
export const useStateEvent = (room: Room, eventType: StateEvent, stateKey = '') => {
export const useStateEvent = (room: Room | undefined, eventType: StateEvent, stateKey = '') => {
const [updateCount, forceUpdate] = useForceUpdate();
useStateEventCallback(
room.client,
room?.client,
useCallback(
(event) => {
if (
room &&
event.getRoomId() === room.roomId &&
event.getType() === eventType &&
event.getStateKey() === stateKey
@@ -25,8 +26,7 @@ export const useStateEvent = (room: Room, eventType: StateEvent, stateKey = '')
);
return useMemo(
() => getStateEvent(room, eventType, stateKey),
// eslint-disable-next-line react-hooks/exhaustive-deps
() => (room ? getStateEvent(room, eventType, stateKey) : undefined),
[room, eventType, stateKey, updateCount],
);
};
+5 -1
View File
@@ -7,8 +7,12 @@ export type StateEventCallback = (
lastStateEvent: MatrixEvent | null,
) => void;
export const useStateEventCallback = (mx: MatrixClient, onStateEvent: StateEventCallback) => {
export const useStateEventCallback = (
mx: MatrixClient | undefined,
onStateEvent: StateEventCallback,
) => {
useEffect(() => {
if (!mx) return undefined;
mx.on(RoomStateEvent.Events, onStateEvent);
return () => {
mx.removeListener(RoomStateEvent.Events, onStateEvent);
+1 -5
View File
@@ -20,9 +20,5 @@ export const useStateEvents = (room: Room, eventType: StateEvent) => {
),
);
return useMemo(
() => getStateEvents(room, eventType),
// eslint-disable-next-line react-hooks/exhaustive-deps
[room, eventType, updateCount],
);
return useMemo(() => getStateEvents(room, eventType), [room, eventType, updateCount]);
};
+1 -1
View File
@@ -63,7 +63,7 @@ export function useUserCollectibles(): [
await saveAvatarDecoration(mx, collectible);
}
clearProfileCache(mx.getUserId());
clearProfileCache(mx.getUserId() ?? undefined);
setCollectibles((prev) => ({ ...prev, [kind]: collectible }));
},
[mx],
+1 -4
View File
@@ -34,10 +34,7 @@ export function SSOLogin({ providers, redirectUrl, action, saveScreenSpace }: SS
}
try {
const existingDeviceId = localStorage.getItem('cinny_device_id') ?? undefined;
await openExternalUrl(
mx.getSsoLoginUrl(redirectUrl, 'sso', providerId, action, existingDeviceId),
);
await openExternalUrl(mx.getSsoLoginUrl(redirectUrl, 'sso', providerId, action));
} finally {
setLaunchingProviderId(null);
}
+2 -1
View File
@@ -21,7 +21,7 @@ export const usePdfDocumentLoader = (pdfJS: typeof PdfJsDist | undefined, src: s
if (!pdfJS) {
throw new Error('PdfJS is not loaded');
}
const doc = await pdfJS.getDocument(src).promise;
const doc = await pdfJS.getDocument({ url: src }).promise;
return doc;
}, [pdfJS, src]),
);
@@ -43,6 +43,7 @@ export const createPage = async (
page.render({
canvasContext: context,
canvas,
viewport: pageViewport,
});
+17 -12
View File
@@ -8,6 +8,7 @@ import React, {
useState,
} from 'react';
import {
DOMNode,
Element,
Text as DOMText,
HTMLReactParserOptions,
@@ -34,7 +35,6 @@ import {
import { IntermediateRepresentation, Opts as LinkifyOpts, OptFn } from 'linkifyjs';
import Linkify from 'linkify-react';
import { ErrorBoundary } from 'react-error-boundary';
import { ChildNode } from 'domhandler';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../components/icons';
import * as css from '../styles/CustomHtml.css';
@@ -254,27 +254,31 @@ export const highlightText = (
);
});
// domhandler's Element.children can hold CDATA and Directive, which html-react-parser's DOMNode excludes
const domNodes = (nodes: Element['children']): DOMNode[] =>
nodes.filter((node): node is DOMNode => node.type !== 'cdata' && node.type !== 'directive');
/**
* Recursively extracts and concatenates all text content from an array of ChildNode objects.
* Recursively extracts and concatenates all text content from an array of DOMNode objects.
*
* @param {ChildNode[]} nodes - An array of ChildNode objects to extract text from.
* @param {DOMNode[]} nodes - An array of DOMNode objects to extract text from.
* @returns {string} The concatenated plain text content of all descendant text nodes.
*/
const extractTextFromChildren = (nodes: ChildNode[]): string => {
const extractTextFromChildren = (nodes: DOMNode[]): string => {
let text = '';
nodes.forEach((node) => {
if (node.type === 'text') {
text += node.data;
} else if (node instanceof Element && node.children) {
text += extractTextFromChildren(node.children);
text += extractTextFromChildren(domNodes(node.children));
}
});
return text;
};
export function CodeBlock({ children }: { children: ChildNode[] }) {
export function CodeBlock({ children }: { children: DOMNode[] }) {
const code = children[0];
const languageClass =
code instanceof Element && code.name === 'code' ? code.attribs.class : undefined;
@@ -338,7 +342,7 @@ export function CodeBlock({ children }: { children: ChildNode[] }) {
<Header variant="Surface" size="400" className={css.CodeBlockHeader}>
<Box grow="Yes">
<Button
variant="Surface"
variant="Secondary"
fill="None"
size="300"
radii="300"
@@ -500,7 +504,7 @@ export function InlineCode({
opts,
props,
}: {
children: ChildNode[];
children: DOMNode[];
opts: HTMLReactParserOptions;
props: ReturnType<typeof attributesToProps>;
}) {
@@ -556,7 +560,8 @@ export const getReactCustomHtmlParser = (
const opts: HTMLReactParserOptions = {
replace: (domNode) => {
if (domNode instanceof Element && 'name' in domNode) {
const { name, attribs, children, parent } = domNode;
const { name, attribs, parent } = domNode;
const children = domNodes(domNode.children);
const props = attributesToProps(attribs);
if (name === 'h1') {
@@ -646,7 +651,7 @@ export const getReactCustomHtmlParser = (
if (parent && 'name' in parent && parent.name === 'pre') {
const codeReact = domToReact(children, opts);
if (typeof codeReact === 'string') {
let lang = props.className;
let lang = typeof props.className === 'string' ? props.className : '';
if (lang === 'language-rs') lang = 'language-rust';
else if (lang === 'language-js') lang = 'language-javascript';
else if (lang === 'language-ts') lang = 'language-typescript';
@@ -673,7 +678,7 @@ export const getReactCustomHtmlParser = (
}
}
if (name === 'a') {
if (name === 'a' && typeof props.href === 'string') {
const href = tryDecodeURIComponent(props.href);
// Handle matrix.to links as mentions
if (testMatrixTo(href)) {
@@ -723,7 +728,7 @@ export const getReactCustomHtmlParser = (
);
}
if (name === 'img') {
if (name === 'img' && typeof props.src === 'string') {
const htmlSrc = mxcUrlToHttp(mx, props.src, params.useAuthentication);
if (htmlSrc && props.src.startsWith('mxc://') === false) {
return (
+8 -1
View File
@@ -7,9 +7,16 @@ const getVariant = (variant: TContainerColor): ComplexStyleRule => ({
backgroundColor: color[variant].Container,
borderColor: color[variant].ContainerLine,
outlineColor: color[variant].ContainerLine,
color: color[variant].OnContainer,
},
selectors: {
// DefaultReset sets `color: inherit` with the same specificity as this rule,
// so which one wins depends on stylesheet order. In the Android build the
// ContainerColor chunk is emitted before folds' reset, so the theme color
// loses and text falls back to the initial color. Raise specificity so the
// theme color wins regardless of order.
'&[class]': {
color: color[variant].OnContainer,
},
'button&[aria-pressed=true]': {
backgroundColor: color[variant].ContainerActive,
},
+1 -3
View File
@@ -25,7 +25,7 @@ const TRANSPARENT_COLOR = 0xff00ff;
* @returns The Lottie animation JSON object
*/
function decompressTgs(tgsData: ArrayBuffer): object {
const decompressed = inflate(new Uint8Array(tgsData), { to: 'string' });
const decompressed = inflate(new Uint8Array(tgsData), { toText: true });
return JSON.parse(decompressed);
}
@@ -82,7 +82,6 @@ async function renderLottieToGif(
return;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const workerScript = (GIF as any).getWorkerScript?.() || '/gif.worker.js';
// Initialize GIF encoder with transparency support
@@ -236,7 +235,6 @@ export async function webmToGif(
return;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const workerScript = (GIF as any).getWorkerScript?.() || '/gif.worker.js';
// Initialize GIF encoder with transparency support
+1 -1
View File
@@ -33,7 +33,7 @@ export type DiscordCollectibleItem = {
};
export type DownloadedCollectibleAsset = DiscordCollectibleAsset & {
data: Uint8Array;
data: Uint8Array<ArrayBuffer>;
};
const CDN_HOST_RE = /(^|\.)(discordapp\.com|discordapp\.net|discord\.com)$/i;
+2 -2
View File
@@ -105,7 +105,7 @@ export const getThumbnailContent = (thumbnailInfo: {
};
export const encryptFile = async (
file: File | Blob,
file: TUploadContent,
): Promise<{
encInfo: EncryptedAttachmentInfo;
file: File;
@@ -113,7 +113,7 @@ export const encryptFile = async (
}> => {
const dataBuffer = await file.arrayBuffer();
const encryptedAttachment = await encryptAttachment(dataBuffer);
const encFile = new File([encryptedAttachment.data], file.name, {
const encFile = new File([encryptedAttachment.data], file.name ?? '', {
type: file.type,
});
return {
-1
View File
@@ -298,7 +298,6 @@ export async function importTelegramStickerPack(
// Save to user account data
console.log('Saving merged pack to account data:', AccountDataEvent.PoniesUserEmotes);
console.log('Merged content:', JSON.stringify(mergedContent, null, 2));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await mx.setAccountData(AccountDataEvent.PoniesUserEmotes as any, mergedContent as any);
console.log('Pack saved successfully');
+3 -234
View File
@@ -2,10 +2,9 @@ import { createClient, MatrixClient, IndexedDBStore, IndexedDBCryptoStore } from
import { cryptoCallbacks } from './secretStorageKeys';
import { clearNavToActivePathStore } from '../app/state/navToActivePath';
import { Session, getSessionStoreName } from '../app/state/sessions';
import { Session, Sessions, getSessionStoreName } from '../app/state/sessions';
import { getSettings } from '../app/state/settings';
import { recordPacket } from '../app/state/debugPackets';
import { promptDialog } from '../app/state/dialog';
const MAX_BODY = 8192;
@@ -86,183 +85,9 @@ const debugFetch = async (input: RequestInfo | URL, init?: RequestInit): Promise
return res;
};
// Track if we're currently handling a key conflict to prevent loops
let handlingKeyConflict = false;
const deleteIndexedDB = (dbName: string): Promise<void> =>
new Promise((resolve, reject) => {
const request = globalThis.indexedDB.deleteDatabase(dbName);
request.onsuccess = () => {
console.log(`[initMatrix] Deleted IndexedDB database: ${dbName}`);
resolve();
};
request.onerror = () => {
console.error(`[initMatrix] Failed to delete IndexedDB database: ${dbName}`, request.error);
reject(request.error);
};
request.onblocked = () => {
console.warn(`[initMatrix] Delete blocked for IndexedDB database: ${dbName}`);
// Resolve anyway as the delete might succeed later
resolve();
};
});
const getAllIndexedDBNames = async (): Promise<string[]> => {
try {
if ('databases' in globalThis.indexedDB) {
// Add timeout to prevent hanging
const timeoutPromise = new Promise<string[]>((resolve) => {
setTimeout(() => {
console.warn('[initMatrix] indexedDB.databases() timed out after 2s');
resolve([]);
}, 2000);
});
const databasesPromise = globalThis.indexedDB
.databases()
.then((dbs) => dbs.map((db) => db.name).filter((name) => typeof name === 'string'));
return await Promise.race([databasesPromise, timeoutPromise]);
}
} catch (error) {
console.warn('[initMatrix] Error getting IndexedDB names:', error);
}
// Fallback for browsers that don't support indexedDB.databases()
return [];
};
/**
* Delete the Rust crypto database to fix one-time key conflicts.
* This happens when the local crypto state has keys that conflict with server state.
*/
const deleteRustCryptoDatabase = async (session: Session): Promise<boolean> => {
console.log('[initMatrix] 🔑 Attempting to delete Rust crypto database to fix key conflicts...');
const dbNames = await getAllIndexedDBNames();
const storagePrefix = `${session.userId}@${session.deviceId}`;
// Find crypto databases for this session
const cryptoDbNames = dbNames.filter(
(name) => name.includes('matrix-sdk-crypto') || name.includes(storagePrefix),
);
if (cryptoDbNames.length === 0) {
console.log('[initMatrix] No crypto databases found to delete');
return false;
}
console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames);
for (let i = 0; i < cryptoDbNames.length; i += 1) {
const dbName = cryptoDbNames[i];
try {
await deleteIndexedDB(dbName);
console.log(`[initMatrix] ✅ Deleted: ${dbName}`);
} catch (error) {
console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error);
}
}
return true;
};
/**
* Setup error listener to detect one-time key conflicts and auto-fix them.
*/
const setupKeyConflictHandler = (mx: MatrixClient, session: Session): void => {
// Listen for HTTP errors from the client
let keyConflictCount = 0;
const KEY_CONFLICT_THRESHOLD = 3;
// Patch console.log/error to detect the key conflict errors
const keyConflictPattern = /One time key.*already exists/;
// We need to use a different approach - listen to the crypto module
// Since we can't directly intercept, we'll use a MutationObserver-style approach
// by checking for repeated key upload failures
const checkKeyConflict = (args: unknown[]): boolean => {
const message = args.map((a) => String(a)).join(' ');
return keyConflictPattern.test(message);
};
// Override console methods temporarily to detect the errors
const originalError = console.error;
const originalWarn = console.warn;
const errorHandler = (...args: unknown[]) => {
if (checkKeyConflict(args)) {
keyConflictCount += 1;
console.log(
`[initMatrix] ⚠️ Detected key conflict (${keyConflictCount}/${KEY_CONFLICT_THRESHOLD})`,
);
if (keyConflictCount >= KEY_CONFLICT_THRESHOLD && !handlingKeyConflict) {
handlingKeyConflict = true;
console.log('[initMatrix] 🔄 Too many key conflicts detected, attempting auto-fix...');
// Schedule the fix for next page load to avoid issues during active session
localStorage.setItem(
'cinny_fix_key_conflict',
JSON.stringify({
userId: session.userId,
deviceId: session.deviceId,
timestamp: Date.now(),
}),
);
// Restore console methods
console.error = originalError;
console.warn = originalWarn;
// Notify user and reload
setTimeout(() => {
promptDialog(
'Detected encryption key conflict. The app needs to reset your encryption session. You may need to re-verify your devices after this. Continue?',
true,
).then((continueFix) => {
if (continueFix) {
deleteRustCryptoDatabase(session).then(() => {
window.location.reload();
});
} else {
handlingKeyConflict = false;
}
});
}, 100);
}
}
originalError.apply(console, args);
};
console.error = errorHandler;
console.warn = (...args: unknown[]) => {
if (checkKeyConflict(args)) {
keyConflictCount += 1;
}
originalWarn.apply(console, args);
};
};
export const initClient = async (session: Session): Promise<MatrixClient> => {
const storeName = getSessionStoreName(session);
// Check if we need to fix a key conflict from a previous session
const pendingFix = localStorage.getItem('cinny_fix_key_conflict');
if (pendingFix) {
try {
const fixData = JSON.parse(pendingFix);
if (fixData.userId === session.userId && fixData.deviceId === session.deviceId) {
console.log('[initMatrix] 🔧 Found pending key conflict fix, clearing crypto database...');
await deleteRustCryptoDatabase(session);
localStorage.removeItem('cinny_fix_key_conflict');
console.log('[initMatrix] ✅ Crypto database cleared');
}
} catch {
localStorage.removeItem('cinny_fix_key_conflict');
}
}
console.log('[initMatrix] ========================================');
console.log('[initMatrix] Initializing Matrix client for session:');
console.log('[initMatrix] User ID:', session.userId);
@@ -298,15 +123,7 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
await indexedDBStore.startup();
// Initialize Rust crypto with a unique store prefix for this account
// This ensures each account has its own isolated crypto database
console.log(
'[initMatrix] Initializing Rust crypto with prefix:',
`${session.userId}@${session.deviceId}`,
);
await mx.initRustCrypto({
storagePrefix: `${session.userId}@${session.deviceId}`,
});
await mx.initRustCrypto();
console.log('[initMatrix] ✅ Client initialized successfully!');
@@ -323,9 +140,6 @@ export const initClient = async (session: Session): Promise<MatrixClient> => {
return user;
};
// Setup handler to detect and auto-fix one-time key conflicts
setupKeyConflictHandler(mx, session);
// Register this as the global MatrixClient so auth utils can access the latest token
const { setGlobalMatrixClient } = await import('../app/utils/auth');
setGlobalMatrixClient(mx);
@@ -367,51 +181,6 @@ export const clearCacheAndReload = async (mx: MatrixClient) => {
window.location.reload();
};
/**
* Fix one-time key conflicts by clearing the Rust crypto database.
* Call this when you see repeated "One time key already exists" errors.
* The user will need to re-verify their devices after this.
*/
export const fixKeyConflict = async (mx: MatrixClient): Promise<void> => {
const userId = mx.getSafeUserId();
const deviceId = mx.getDeviceId();
if (!userId || !deviceId) {
console.error('[initMatrix] Cannot fix key conflict: missing userId or deviceId');
return;
}
console.log('[initMatrix] 🔧 Fixing key conflict for', userId, deviceId);
// Stop the client first
mx.stopClient();
// Delete the crypto databases
const dbNames = await getAllIndexedDBNames();
const storagePrefix = `${userId}@${deviceId}`;
const cryptoDbNames = dbNames.filter(
(name) =>
name.includes('matrix-sdk-crypto') || name.includes(storagePrefix) || name.includes('crypto'),
);
console.log('[initMatrix] 🗑️ Deleting crypto databases:', cryptoDbNames);
for (let i = 0; i < cryptoDbNames.length; i += 1) {
const dbName = cryptoDbNames[i];
try {
await deleteIndexedDB(dbName);
console.log(`[initMatrix] ✅ Deleted: ${dbName}`);
} catch (error) {
console.error(`[initMatrix] ❌ Failed to delete ${dbName}:`, error);
}
}
// Reload the page
console.log('[initMatrix] 🔄 Reloading...');
window.location.reload();
};
export const logoutClient = async (mx: MatrixClient) => {
mx.stopClient();
@@ -430,7 +199,7 @@ export const logoutClient = async (mx: MatrixClient) => {
await import('../app/state/utils/atomWithLocalStorage');
const userId = mx.getSafeUserId();
const allSessions = getLocalStorageItem('matrixSessions', []);
const allSessions = getLocalStorageItem<Sessions>('matrixSessions', []);
const currentUserId = getLocalStorageItem('currentSessionUserId', undefined);
// Remove the current session
+14 -2
View File
@@ -17,7 +17,19 @@ interface PluginAPI {
) => Promise<{ success: boolean; data?: { path: string }; error?: string }>;
list: () => Promise<{
success: boolean;
data?: Array<{ id: string; name: string; installedDate: string; path: string }>;
data?: Array<{
id: string;
name: string;
version?: string;
description?: string;
author?: string;
repository?: string;
thumbnail?: string;
homepage?: string;
tags?: string[];
installedDate: string;
path: string;
}>;
error?: string;
}>;
uninstall: (pluginId: string) => Promise<{ success: boolean; error?: string }>;
@@ -160,7 +172,7 @@ interface ElectronAPI {
url: string;
filename: string;
mimeType: string;
data: Uint8Array;
data: Uint8Array<ArrayBuffer>;
}>;
error?: string;
}>;
+182
View File
@@ -2007,3 +2007,185 @@ textarea {
audio:not([controls]) {
display: none !important;
}
html.immersive-landscape-keyboard {
--safe-area-inset-top: 0px;
}
.twilight-theme [role='navigation'],
.twilight-theme aside {
background: linear-gradient(180deg, rgba(20, 18, 31, 0.8) 0%, rgba(28, 26, 46, 0.9) 100%);
backdrop-filter: blur(8px);
}
[data-route-transition='true'] {
animation: fadeSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}
@media (max-width: 750px) {
[data-route-transition='true'] {
animation: none;
}
}
html.mobile-gesture-lock,
html.mobile-gesture-lock body {
overscroll-behavior: none;
}
html.mobile-gesture-lock [data-timeline-scroll] {
overflow: hidden !important;
touch-action: none;
}
.twilight-theme [data-route-transition='true'] {
animation: fadeSlideIn 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}
.twilight-theme button,
.twilight-theme [role='button'],
.twilight-theme a,
.twilight-theme input,
.twilight-theme textarea {
transition:
background-color 0.2s ease,
color 0.2s ease,
transform 0.15s ease;
}
.twilight-theme button:hover,
.twilight-theme [role='button']:hover {
transform: translateY(-1px);
}
.twilight-theme button:active,
.twilight-theme [role='button']:active {
transform: translateY(0);
}
.twilight-theme [data-selected='true'],
.twilight-theme [aria-selected='true'],
.twilight-theme [aria-current='true'] {
position: relative;
transition: all 0.2s ease;
}
.twilight-theme [data-selected='true']::before,
.twilight-theme [aria-selected='true']::before,
.twilight-theme [aria-current='true']::before {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 3px;
background: linear-gradient(180deg, #8b7fff 0%, #6e62e8 100%);
transition: width 0.2s ease;
}
.twilight-theme ::-webkit-scrollbar-thumb:hover {
background: linear-gradient(180deg, #4a4580 0%, #625bac 100%);
}
.mocha-theme [role='navigation'],
.mocha-theme aside {
background: linear-gradient(180deg, rgba(26, 22, 20, 0.8) 0%, rgba(36, 32, 25, 0.9) 100%);
backdrop-filter: blur(8px);
}
.mocha-theme [data-route-transition='true'] {
animation: fadeSlideIn 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}
.mocha-theme button,
.mocha-theme [role='button'],
.mocha-theme a,
.mocha-theme input,
.mocha-theme textarea {
transition:
background-color 0.2s ease,
color 0.2s ease,
transform 0.15s ease;
}
.mocha-theme button:hover,
.mocha-theme [role='button']:hover {
transform: translateY(-1px);
}
.mocha-theme button:active,
.mocha-theme [role='button']:active {
transform: translateY(0);
}
.mocha-theme [data-selected='true'],
.mocha-theme [aria-selected='true'],
.mocha-theme [aria-current='true'] {
position: relative;
transition: all 0.2s ease;
}
.mocha-theme [data-selected='true']::before,
.mocha-theme [aria-selected='true']::before,
.mocha-theme [aria-current='true']::before {
content: '';
position: absolute;
left: 0;
top: 0;
bottom: 0;
width: 3px;
background: linear-gradient(180deg, #d4a574 0%, #b48660 100%);
transition: width 0.2s ease;
}
.mocha-theme ::-webkit-scrollbar-thumb:hover {
background: linear-gradient(180deg, #625548 0%, #7e6d5a 100%);
}
.stationery ::-webkit-scrollbar-thumb:hover {
background: linear-gradient(180deg, var(--manila-edge) 0%, var(--manila-dark) 100%);
}
html.android-capacitor,
html.android-capacitor.dark-theme,
html.android-capacitor.butter-theme,
html.android-capacitor.discord-theme,
html.android-capacitor.discord-darker-theme,
html.android-capacitor.twilight-theme,
html.android-capacitor.mocha-theme,
html.android-capacitor.light-theme,
html.android-capacitor.silver-theme,
html.android-capacitor.stationery-theme,
html.android-capacitor.stationery-dark-theme {
--font-secondary: system-ui, Roboto, 'Noto Sans', sans-serif;
}
html.android-capacitor body {
font-family: system-ui, Roboto, 'Noto Sans', sans-serif;
letter-spacing: normal;
word-spacing: normal;
font-variant-ligatures: normal;
}
@media (max-width: 750px) {
*,
*::before,
*::after {
scrollbar-width: none;
-ms-overflow-style: none;
}
*::-webkit-scrollbar,
*::-webkit-scrollbar-thumb,
*::-webkit-scrollbar-track,
*::-webkit-scrollbar-corner {
display: none;
width: 0;
height: 0;
background: transparent;
}
.twilight-theme ::-webkit-scrollbar,
.twilight-theme ::-webkit-scrollbar-thumb,
.twilight-theme ::-webkit-scrollbar-track,
.mocha-theme ::-webkit-scrollbar,
.mocha-theme ::-webkit-scrollbar-thumb,
.mocha-theme ::-webkit-scrollbar-track {
display: none;
width: 0;
height: 0;
background: transparent;
}
}
html.android-capacitor,
html.android-capacitor *,
html.android-capacitor *::before,
html.android-capacitor *::after {
scrollbar-width: none;
-ms-overflow-style: none;
}
html.android-capacitor *::-webkit-scrollbar,
html.android-capacitor *::-webkit-scrollbar-thumb,
html.android-capacitor *::-webkit-scrollbar-track,
html.android-capacitor *::-webkit-scrollbar-corner {
display: none;
width: 0;
height: 0;
background: transparent;
}
+1 -1
View File
@@ -2,7 +2,7 @@
import React from 'react';
import { createRoot } from 'react-dom/client';
import { enableMapSet } from 'immer';
import '@fontsource-variable/inter';
import '@fontsource-variable/inter/index.css';
import '@fontsource/caveat/500.css';
import '@fontsource/caveat/600.css';
import '@fontsource/caveat/700.css';
+9
View File
@@ -1,4 +1,7 @@
import { InCinnySpacesContent } from '../../app/hooks/useSidebarItems';
import { EmojiUsageData } from '../../app/hooks/useEmojiUsage';
import { EmoteRoomsContent, PackContent } from '../../app/plugins/custom-emoji/types';
import { IRecentEmojiContent } from '../../app/plugins/recent-emoji';
export enum AccountDataEvent {
PushRules = 'm.push_rules',
@@ -12,6 +15,8 @@ export enum AccountDataEvent {
PoniesUserEmotes = 'im.ponies.user_emotes',
PoniesEmoteRooms = 'im.ponies.emote_rooms',
PaarrotFavemojis = 'paarrot.favemojis',
SecretStorageDefaultKey = 'm.secret_storage.default_key',
CrossSigningMaster = 'm.cross_signing.master',
@@ -54,5 +59,9 @@ export type SecretAccountData = {
declare module 'matrix-js-sdk' {
interface AccountDataEvents {
[AccountDataEvent.CinnySpaces]: InCinnySpacesContent;
[AccountDataEvent.PoniesUserEmotes]: PackContent;
[AccountDataEvent.PoniesEmoteRooms]: EmoteRoomsContent;
[AccountDataEvent.ElementRecentEmoji]: IRecentEmojiContent;
[AccountDataEvent.PaarrotFavemojis]: EmojiUsageData;
}
}
+17
View File
@@ -1,5 +1,10 @@
import { PackContent } from '../../app/plugins/custom-emoji/types';
import { PaarrotSubRoomsContent } from '../../app/hooks/useRoomSubRooms';
import { EmojiConfettiContent } from '../../app/features/room/emoji-confetti/types';
import {
EMBED_FILTERS_ACCOUNT_DATA_TYPE,
EmbedFiltersContent,
} from '../../app/hooks/useRoomEmbedFilters';
import { IImageInfo } from './common';
export enum Membership {
@@ -235,7 +240,19 @@ declare module 'matrix-js-sdk' {
[StateEvent.PaarrotRoomKind]: { kind?: string };
}
interface RoomAccountDataEvents {
[EMBED_FILTERS_ACCOUNT_DATA_TYPE]: EmbedFiltersContent;
}
interface TimelineEvents {
[MessageEvent.PaarrotUiAction]: PaarrotUiActionContent;
[MessageEvent.RelayEmojiConfetti]: EmojiConfettiContent;
}
}
// Forum post title carried on m.room.message text content (matrixsso extension)
declare module 'matrix-js-sdk/lib/@types/events' {
interface RoomMessageTextEventContent {
'com.matrixsso.title'?: string;
}
}
+1 -1
View File
@@ -105,7 +105,7 @@ export function cssColorMXID(userId) {
/**
* Get the actual hex color value for a user ID
* @param {string} userId - Matrix user ID
* @param {boolean} isDark - Whether to use dark theme colors (default: auto-detect)
* @param {boolean} [isDark] - Whether to use dark theme colors (default: auto-detect)
* @returns {string} Hex color string
*/
export function getColorMXIDValue(userId, isDark) {