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
+13 -8
View File
@@ -42,7 +42,12 @@ import {
import { ClientBindAtoms, ClientLayout, ClientRoot } from './client';
import { Home, HomeRouteRoomProvider, HomeSearch } from './client/home';
import { Direct, DirectCreate, DirectRouteRoomProvider, DirectSearch } from './client/direct';
import { RouteSpaceProvider, SpaceRouteRoomProvider, SpaceSearch, SpaceIndexRedirect } from './client/space';
import {
RouteSpaceProvider,
SpaceRouteRoomProvider,
SpaceSearch,
SpaceIndexRedirect,
} from './client/space';
import { ForumAwareSpaceLayout } from '../features/forum/ForumAwareSpaceLayout';
import { ForumFeedPage } from '../features/forum/ForumFeedPage';
import { Explore, FeaturedRooms, PublicRooms } from './client/explore';
@@ -109,24 +114,24 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
const addingAccount = url.searchParams.get('add-account') === 'true';
const session = getCurrentSession();
const hasSession = !!session;
// Log to localStorage for persistence across reloads
const debugInfo = {
timestamp: new Date().toISOString(),
url: url.toString(),
url: url.toString(),
pathname: url.pathname,
search: url.search,
hash: url.hash,
addingAccount,
addingAccount,
hasSession,
willRedirect: hasSession && !addingAccount
willRedirect: hasSession && !addingAccount,
};
console.log('[Router] Auth loader:', debugInfo);
const debugLog = JSON.parse(localStorage.getItem('debug-router-logs') || '[]');
debugLog.push(debugInfo);
if (debugLog.length > 10) debugLog.shift(); // Keep last 10
localStorage.setItem('debug-router-logs', JSON.stringify(debugLog));
if (session && !addingAccount) {
console.log('[Router] Redirecting to last seen channel for existing session');
return redirect(getStartupPath(session.userId));
@@ -151,7 +156,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
if (!getCurrentSession()) {
const afterLoginPath = getAppPathFromHref(
getOriginBaseUrl(hashRouter),
window.location.href
window.location.href,
);
if (afterLoginPath) setAfterLoginRedirectPath(afterLoginPath);
return redirect(getLoginPath());
@@ -317,7 +322,7 @@ export const createRouter = (clientConfig: ClientConfig, screenSize: ScreenSize)
</Route>
</Route>
<Route path="/*" element={<p>Page not found</p>} />
</Route>
</Route>,
);
if (hashRouter?.enabled) {
+7 -1
View File
@@ -5,7 +5,13 @@ import * as css from './styles.css';
export function AuthFooter() {
return (
<Box className={css.AuthFooter} justifyContent="Center" gap="400" wrap="Wrap">
<Text as="a" size="T300" href="https://github.com/Paarrot/Paarrot-Desktop" target="_blank" rel="noreferrer">
<Text
as="a"
size="T300"
href="https://github.com/Paarrot/Paarrot-Desktop"
target="_blank"
rel="noreferrer"
>
About
</Text>
<Text
+4 -4
View File
@@ -87,7 +87,7 @@ export function AuthLayout() {
serverName,
response,
};
}, [])
}, []),
);
useEffect(() => {
@@ -102,7 +102,7 @@ export function AuthLayout() {
generatePath(currentAuthPath(location.pathname), {
server,
}) + location.search,
{ replace: true }
{ replace: true },
);
}
}, [urlEncodedServer, navigate, location, server]);
@@ -115,10 +115,10 @@ export function AuthLayout() {
return;
}
navigate(
generatePath(currentAuthPath(location.pathname), { server: newServer }) + location.search
generatePath(currentAuthPath(location.pathname), { server: newServer }) + location.search,
);
},
[navigate, location, discoveryState, server, discoverServer]
[navigate, location, discoveryState, server, discoverServer],
);
const [autoDiscoveryError, autoDiscoveryInfo] =
+1
View File
@@ -2,6 +2,7 @@ import React from 'react';
import { Box, color, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
export function FieldError({ message }: { message: string }) {
return (
<Box style={{ color: color.Critical.Main }} alignItems="Center" gap="100">
+2 -2
View File
@@ -44,12 +44,12 @@ export function SSOLogin({ providers, redirectUrl, action, saveScreenSpace }: SS
setLaunchingProviderId(null);
}
},
[getSSOIdUrl, launchingProviderId]
[getSSOIdUrl, launchingProviderId],
);
const withoutIcon = providers
? providers.find(
(provider) => !provider.icon || !mx.mxcUrlToHttp(provider.icon, 96, 96, 'crop', false)
(provider) => !provider.icon || !mx.mxcUrlToHttp(provider.icon, 96, 96, 'crop', false),
)
: true;
+1 -1
View File
@@ -8,8 +8,8 @@ import React, {
useState,
} from 'react';
import { Header, IconButton, Input, Menu, MenuItem, PopOut, RectCords, Text, config } from 'folds';
import { Icon, Icons } from '../../components/icons';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../components/icons';
import { useDebounce } from '../../hooks/useDebounce';
import { stopPropagation } from '../../utils/keyboard';
+2 -2
View File
@@ -31,7 +31,7 @@ const useLoginSearchParams = (searchParams: URLSearchParams): LoginPathSearchPar
email: searchParams.get('email') ?? undefined,
loginToken: searchParams.get('loginToken') ?? undefined,
}),
[searchParams]
[searchParams],
);
export function Login() {
@@ -48,7 +48,7 @@ export function Login() {
window.location.replace(
withSearchParam(absoluteLoginPath, {
loginToken: loginTokenForHashRouter,
})
}),
);
}
+17 -2
View File
@@ -1,9 +1,24 @@
import React, { FormEventHandler, MouseEventHandler, useCallback, useState } from 'react';
import { Box, Button, Header, IconButton, Input, Menu, Overlay, OverlayBackdrop, OverlayCenter, PopOut, RectCords, Spinner, Text, config } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
Button,
Header,
IconButton,
Input,
Menu,
Overlay,
OverlayBackdrop,
OverlayCenter,
PopOut,
RectCords,
Spinner,
Text,
config,
} from 'folds';
import FocusTrap from 'focus-trap-react';
import { Link } from 'react-router-dom';
import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { getMxIdLocalPart, getMxIdServer, isUserId } from '../../../utils/matrix';
import { EMAIL_REGEX } from '../../../utils/regex';
import { useAutoDiscoveryInfo } from '../../../hooks/useAutoDiscoveryInfo';
+1 -1
View File
@@ -1,7 +1,7 @@
import { Box, Overlay, OverlayBackdrop, OverlayCenter, Spinner, Text, color, config } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import React, { useCallback, useEffect } from 'react';
import { MatrixError } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { useAutoDiscoveryInfo } from '../../../hooks/useAutoDiscoveryInfo';
import { AsyncStatus, useAsyncCallback } from '../../../hooks/useAsyncCallback';
import { CustomLoginResponse, LoginError, login, useLoginComplete } from './loginUtil';
+14 -11
View File
@@ -12,7 +12,10 @@ import {
import { getHomePath } from '../../pathUtils';
import { getLastActivePath } from '../../../state/lastActivePath';
import { setFallbackSession } from '../../../state/sessions';
import { getLocalStorageItem, setLocalStorageItem } from '../../../state/utils/atomWithLocalStorage';
import {
getLocalStorageItem,
setLocalStorageItem,
} from '../../../state/utils/atomWithLocalStorage';
export enum GetBaseUrlError {
NotAllow = 'NotAllow',
@@ -61,7 +64,7 @@ export type CustomLoginResponse = {
};
export const login = async (
serverBaseUrl: string | (() => Promise<string>),
data: LoginRequest
data: LoginRequest,
): Promise<CustomLoginResponse> => {
const [urlError, url] =
typeof serverBaseUrl === 'function' ? await to(serverBaseUrl()) : [undefined, serverBaseUrl];
@@ -116,10 +119,10 @@ export const useLoginComplete = (data?: CustomLoginResponse) => {
useEffect(() => {
if (data) {
const { response: loginRes, baseUrl: loginBaseUrl } = data;
// Add session to sessions list
const sessions = getLocalStorageItem('matrixSessions', []);
const newSession = {
baseUrl: loginBaseUrl,
userId: loginRes.user_id,
@@ -129,25 +132,25 @@ export const useLoginComplete = (data?: CustomLoginResponse) => {
refreshToken: loginRes.refresh_token,
fallbackSdkStores: false,
};
// Check if session already exists (by userId AND deviceId to avoid conflicts)
const existingIndex = sessions.findIndex(
(s: any) => s.userId === loginRes.user_id && s.deviceId === loginRes.device_id
(s: any) => s.userId === loginRes.user_id && s.deviceId === loginRes.device_id,
);
if (existingIndex >= 0) {
// Preserve fallbackSdkStores if it was set, but never enable it for new logins
const oldSession = sessions[existingIndex];
sessions[existingIndex] = {
...newSession,
fallbackSdkStores: oldSession.fallbackSdkStores === true ? true : false,
fallbackSdkStores: oldSession.fallbackSdkStores === true,
};
} else {
sessions.push(newSession);
}
setLocalStorageItem('matrixSessions', sessions);
setLocalStorageItem('currentSessionUserId', loginRes.user_id);
const afterLoginRedirectUrl = getAfterLoginRedirectPath();
deleteAfterLoginRedirectPath();
const targetPath =
@@ -158,10 +161,10 @@ export const useLoginComplete = (data?: CustomLoginResponse) => {
deviceId: loginRes.device_id,
isMultiAccount: sessions.length > 1,
});
// Reload to the target path
// For hash router, we need to use just the origin without /login pathname
window.location.href = window.location.origin + '/#' + targetPath;
window.location.href = `${window.location.origin}/#${targetPath}`;
}
}, [data, navigate]);
};
@@ -112,7 +112,7 @@ function RegisterUIAFlow({
initial_device_display_name: 'Paarrot',
});
},
[onRegister, formData]
[onRegister, formData],
);
const handleCancel = useCallback(() => {
+1 -1
View File
@@ -20,7 +20,7 @@ const useRegisterSearchParams = (searchParams: URLSearchParams): RegisterPathSea
email: searchParams.get('email') ?? undefined,
token: searchParams.get('token') ?? undefined,
}),
[searchParams]
[searchParams],
);
export function Register() {
+2 -2
View File
@@ -37,7 +37,7 @@ export type CustomRegisterResponse = {
export type RegisterResult = [IAuthData, undefined] | [undefined, CustomRegisterResponse];
export const register = async (
mx: MatrixClient,
requestData: RegisterRequest
requestData: RegisterRequest,
): Promise<RegisterResult> => {
const [err, res] = await to<RegisterResponse, MatrixError>(mx.registerRequest(requestData));
@@ -130,7 +130,7 @@ export const useRegisterComplete = (data?: CustomRegisterResponse) => {
withSearchParam<LoginPathSearchParams>(getLoginPath(userServer), {
username,
}),
{ replace: true }
{ replace: true },
);
}
}
@@ -120,7 +120,7 @@ export function PasswordResetForm({ defaultEmail }: PasswordResetFormProps) {
},
password: formData.password,
},
formData.password
formData.password,
);
}
}, [ongoingAuthData, flowErrorCode, formData, handleResetPassword]);
@@ -161,7 +161,7 @@ export function PasswordResetForm({ defaultEmail }: PasswordResetFormProps) {
const { password } = formData;
handleResetPassword(authDict, password);
},
[formData, handleResetPassword]
[formData, handleResetPassword],
);
return (
@@ -7,13 +7,13 @@ import { PasswordResetForm } from './PasswordResetForm';
import { ResetPasswordPathSearchParams } from '../../paths';
const useResetPasswordSearchParams = (
searchParams: URLSearchParams
searchParams: URLSearchParams,
): ResetPasswordPathSearchParams =>
useMemo(
() => ({
email: searchParams.get('email') ?? undefined,
}),
[searchParams]
[searchParams],
);
export function ResetPassword() {
@@ -6,10 +6,10 @@ export type ResetPasswordResult = [IAuthData, undefined] | [undefined, ResetPass
export const resetPassword = async (
mx: MatrixClient,
authDict: AuthDict,
newPassword: string
newPassword: string,
): Promise<ResetPasswordResult> => {
const [err, res] = await to<ResetPasswordResponse, MatrixError>(
mx.setPassword(authDict, newPassword, false)
mx.setPassword(authDict, newPassword, false),
);
if (err) {
+38 -32
View File
@@ -1,5 +1,4 @@
import { useAtomValue } from 'jotai';
import { useAtom, useSetAtom } from 'jotai';
import { useAtomValue, useAtom, useSetAtom } from 'jotai';
import React, { ReactNode, useCallback, useEffect, useRef, useState, Fragment } from 'react';
import { useNavigate } from 'react-router-dom';
import { RoomEvent, RoomEventHandlerMap } from 'matrix-js-sdk';
@@ -13,7 +12,12 @@ import { EmojiStyle, settingsAtom } from '../../state/settings';
import { allInvitesAtom } from '../../state/room-list/inviteList';
import { usePreviousValue } from '../../hooks/usePreviousValue';
import { useMatrixClient } from '../../hooks/useMatrixClient';
import { getDirectRoomPath, getHomeRoomPath, getSpaceRoomPath, getInboxInvitesPath } from '../pathUtils';
import {
getDirectRoomPath,
getHomeRoomPath,
getSpaceRoomPath,
getInboxInvitesPath,
} from '../pathUtils';
import {
getMemberDisplayName,
getNotificationType,
@@ -23,7 +27,12 @@ import {
guessPerfectParent,
} from '../../utils/room';
import { NotificationType, UnreadInfo } from '../../../types/matrix/room';
import { getMxIdLocalPart, mxcUrlToHttp, getCanonicalAliasOrRoomId } from '../../utils/matrix';
import {
getMxIdLocalPart,
mxcUrlToHttp,
getCanonicalAliasOrRoomId,
encryptFile,
} from '../../utils/matrix';
import { mDirectAtom } from '../../state/mDirectList';
import { roomToParentsAtom } from '../../state/room/roomToParents';
import { useSelectedRoom } from '../../hooks/router/useSelectedRoom';
@@ -49,7 +58,6 @@ import {
roomIdToMsgDraftAtomFamily,
roomIdToUploadItemsAtomFamily,
} from '../../state/room/roomInputDrafts';
import { encryptFile } from '../../utils/matrix';
import {
AndroidSharePayload,
clearPendingAndroidShare,
@@ -135,10 +143,11 @@ function InviteNotifications() {
(count: number) => {
const body = `You have ${count} new invitation request.`;
const invitesPath = getInboxInvitesPath();
// Flash taskbar icon for desktop notifications (only visible when window is not focused)
if (isElectron() && (window as any).electron?.window?.flashFrame) {
(window as any).electron.window.flashFrame(true)
(window as any).electron.window
.flashFrame(true)
.then((result: { success: boolean }) => {
console.log('[InviteNotifications] flashFrame result:', result);
})
@@ -146,7 +155,7 @@ function InviteNotifications() {
console.error('[InviteNotifications] flashFrame error:', err);
});
}
if ((isTauri() && !isElectron()) || isCapacitorNative()) {
sendNotification({
title: 'Invitation',
@@ -175,14 +184,15 @@ function InviteNotifications() {
};
}
},
[navigate]
[navigate],
);
const playSound = useCallback(() => {
console.log('[InviteNotifications] playSound called, isElectron:', isElectron());
if (isElectron() && (window as any).electron?.audio?.playNotificationSound) {
console.log('[InviteNotifications] Using Electron audio API');
(window as any).electron.audio.playNotificationSound('invite')
(window as any).electron.audio
.playNotificationSound('invite')
.then((result: any) => console.log('[InviteNotifications] Sound result:', result))
.catch((err: any) => console.error('[InviteNotifications] Sound error:', err));
} else {
@@ -275,7 +285,8 @@ function MessageNotifications() {
// Flash taskbar icon for desktop notifications (only visible when window is not focused)
console.log('[Notifications] Attempting flashFrame');
if (isElectron() && (window as any).electron?.window?.flashFrame) {
(window as any).electron.window.flashFrame(true)
(window as any).electron.window
.flashFrame(true)
.then((result: { success: boolean }) => {
console.log('[Notifications] flashFrame result:', result);
})
@@ -285,7 +296,7 @@ function MessageNotifications() {
} else {
console.warn('[Notifications] flashFrame not available, isElectron:', isElectron());
}
if ((isTauri() && !isElectron()) || isCapacitorNative()) {
const roomPath = isDm
? getDirectRoomPath(roomId, eventId)
@@ -326,14 +337,15 @@ function MessageNotifications() {
notifRef.current = noti;
}
},
[mx, navigate, mDirects, roomToParents]
[mx, navigate, mDirects, roomToParents],
);
const playSound = useCallback(() => {
console.log('[MessageNotifications] playSound called, isElectron:', isElectron());
if (isElectron() && (window as any).electron?.audio?.playNotificationSound) {
console.log('[MessageNotifications] Using Electron audio API');
(window as any).electron.audio.playNotificationSound('message')
(window as any).electron.audio
.playNotificationSound('message')
.then((result: any) => console.log('[MessageNotifications] Sound result:', result))
.catch((err: any) => console.error('[MessageNotifications] Sound error:', err));
} else {
@@ -350,7 +362,7 @@ function MessageNotifications() {
room,
toStartOfTimeline,
removed,
data
data,
) => {
if (mx.getSyncState() !== 'SYNCING') return;
if (document.hasFocus() && (selectedRoomId === room?.roomId || notificationSelected)) return;
@@ -394,7 +406,7 @@ function MessageNotifications() {
const avatarMxc =
room.getAvatarFallbackMember()?.getMxcAvatarUrl() ?? room.getMxcAvatarUrl();
const content = mEvent.getContent();
let messageBody: string | undefined;
if (mEvent.getType() === 'm.reaction') {
// For reactions, show "reacted with {emoji}"
@@ -407,11 +419,11 @@ function MessageNotifications() {
} else {
messageBody = typeof content.body === 'string' ? content.body : undefined;
}
notify({
roomName: room.name ?? 'Unknown',
roomAvatar: avatarMxc
? mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined
? (mxcUrlToHttp(mx, avatarMxc, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined,
username: getMemberDisplayName(room, sender) ?? getMxIdLocalPart(sender) ?? sender,
messageBody,
@@ -483,10 +495,10 @@ function PaarrotAPIInitializer() {
useEffect(() => {
// Register navigate function for Paarrot API
setPaarrotNavigate(navigate);
// Initialize Paarrot API handlers
initPaarrotAPI(mx);
console.log('Paarrot API: Initialized with navigate function');
}, [navigate, mx]);
@@ -536,7 +548,7 @@ function AndroidShareIntentHandler() {
// Send text message if present
const nextParts = [share.subject?.trim(), share.text?.trim()].filter(
(value): value is string => !!value
(value): value is string => !!value,
);
if (nextParts.length > 0) {
const textContent = {
@@ -550,7 +562,7 @@ function AndroidShareIntentHandler() {
if (share.files.length > 0) {
for (const sharedFile of share.files) {
const originalFile = await materializeSharedFile(sharedFile, share.receivedAt);
let fileToUpload = originalFile;
let encInfo: any;
@@ -598,7 +610,7 @@ function AndroidShareIntentHandler() {
await clearPendingAndroidShare();
return true;
},
[mx]
[mx],
);
const handlePickRoom = useCallback(
@@ -609,7 +621,7 @@ function AndroidShareIntentHandler() {
.then((applied) => {
if (applied) {
setPendingShare(null);
// Navigate to the selected room
const isDirect = mDirects.has(roomId);
if (isDirect) {
@@ -630,7 +642,7 @@ function AndroidShareIntentHandler() {
setPendingShare(null);
});
},
[applyPendingShare, pendingShare, navigate, mDirects, roomToParents]
[applyPendingShare, pendingShare, navigate, mDirects, roomToParents],
);
const handleDismiss = useCallback(() => {
@@ -674,13 +686,7 @@ function AndroidShareIntentHandler() {
if (!pendingShare) return null;
return (
<ShareRoomPicker
share={pendingShare}
onPick={handlePickRoom}
onDismiss={handleDismiss}
/>
);
return <ShareRoomPicker share={pendingShare} onPick={handlePickRoom} onDismiss={handleDismiss} />;
}
type ClientNonUIFeaturesProps = {
+115 -82
View File
@@ -1,5 +1,15 @@
import { Box, Button, config, Dialog, IconButton, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
import { Icon, Icons } from '../../components/icons';
import {
Box,
Button,
config,
Dialog,
IconButton,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
} from 'folds';
import {
ClientEvent,
HttpApiEvent,
@@ -8,7 +18,16 @@ import {
SyncState,
} from 'matrix-js-sdk';
import FocusTrap from 'focus-trap-react';
import React, { MouseEventHandler, ReactNode, useCallback, useEffect, useRef, useState } from 'react';
import React, {
MouseEventHandler,
ReactNode,
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../components/icons';
import {
clearCacheAndReload,
clearLoginData,
@@ -27,7 +46,6 @@ import { SpecVersions } from './SpecVersions';
import { AsyncStatus, useAsyncCallback } from '../../hooks/useAsyncCallback';
import { useSyncState } from '../../hooks/useSyncState';
import { stopPropagation } from '../../utils/keyboard';
import { useAtomValue } from 'jotai';
import { allRoomsAtom, useBindAllRoomsAtom } from '../../state/room-list/roomList';
import { mDirectAtom, useBindMDirectAtom } from '../../state/mDirectList';
import { roomToParentsAtom, useBindRoomToParentsAtom } from '../../state/room/roomToParents';
@@ -69,9 +87,14 @@ const useVisibilitySync = (mx?: MatrixClient) => {
console.log('[useVisibilitySync] App became visible, checking sync state');
const syncState = mx.getSyncState();
console.log('[useVisibilitySync] Current sync state:', syncState);
// If sync is not running or errored, restart it
if (!mx.clientRunning || syncState === SyncState.Error || syncState === SyncState.Stopped || syncState === null) {
if (
!mx.clientRunning ||
syncState === SyncState.Error ||
syncState === SyncState.Stopped ||
syncState === null
) {
console.log('[useVisibilitySync] Restarting sync...');
startClient(mx).catch((err) => {
console.error('[useVisibilitySync] Failed to restart sync:', err);
@@ -85,10 +108,10 @@ const useVisibilitySync = (mx?: MatrixClient) => {
};
document.addEventListener('visibilitychange', handleVisibilityChange);
// Also handle resume event for mobile (if available)
window.addEventListener('resume', handleVisibilityChange);
return () => {
document.removeEventListener('visibilitychange', handleVisibilityChange);
window.removeEventListener('resume', handleVisibilityChange);
@@ -189,7 +212,9 @@ export function ClientRoot({ children }: ClientRootProps) {
const roomsAtom = useAtomValue(allRoomsAtom);
const directsAtom = useAtomValue(mDirectAtom);
const chatsReady =
roomsAtom.length > 0 && directsAtom.size > 0 && roomsAtom.some((roomId) => directsAtom.has(roomId));
roomsAtom.length > 0 &&
directsAtom.size > 0 &&
roomsAtom.some((roomId) => directsAtom.has(roomId));
const tryHide = useCallback(
(reason: string): boolean => {
@@ -199,7 +224,7 @@ export function ClientRoot({ children }: ClientRootProps) {
}
return false;
},
[chatsReady, scheduleHide]
[chatsReady, scheduleHide],
);
// The atoms fill in as the store restores the cache; hide as soon as they do.
@@ -218,7 +243,7 @@ export function ClientRoot({ children }: ClientRootProps) {
throw new Error('No session Found!');
}
return initClient(session);
}, [])
}, []),
);
const mx = loadState.status === AsyncStatus.Success ? loadState.data : undefined;
@@ -226,8 +251,8 @@ export function ClientRoot({ children }: ClientRootProps) {
mxRef.current = mx;
}, [mx]);
useEffect(() => {
return () => {
useEffect(
() => () => {
if (splashHoldTimer.current !== undefined) {
window.clearTimeout(splashHoldTimer.current);
}
@@ -237,11 +262,12 @@ export function ClientRoot({ children }: ClientRootProps) {
if (splashDeadline.current !== undefined) {
window.clearTimeout(splashDeadline.current);
}
};
}, []);
},
[],
);
const [startState, startMatrix] = useAsyncCallback<void, Error, [MatrixClient]>(
useCallback((m) => startClient(m), [])
useCallback((m) => startClient(m), []),
);
useLogoutListener(mx);
@@ -273,7 +299,7 @@ export function ClientRoot({ children }: ClientRootProps) {
'[ClientRoot] Splash gate:',
mx.getSyncState(),
`${roomsAtom.length} rooms in atom`,
`${directsAtom.size} m.direct`
`${directsAtom.size} m.direct`,
);
// Prepared can fire before this listener attaches, so look at the current
@@ -317,79 +343,82 @@ export function ClientRoot({ children }: ClientRootProps) {
// window ensures we never block the UI when offline.
useSyncState(
mx,
useCallback((state, prevState, data) => {
const client = mxRef.current;
if (state === SyncState.Prepared || state === SyncState.Syncing) {
if (state === SyncState.Prepared) {
console.log(
'[ClientRoot] Prepared from',
prevState ?? 'nothing',
data?.fromCache ? '(cache)' : '(network)'
);
}
if (tryHide(data?.fromCache ? 'cache populated' : 'first network sync')) {
return;
}
if (data?.fromCache) {
// Cache-only prepared: the room list is still being restored, so wait
// for it, but hide anyway once the grace expires so we never block the
// UI when offline.
if (firstNetworkSyncGrace.current === undefined) {
firstNetworkSyncGrace.current = window.setTimeout(() => {
firstNetworkSyncGrace.current = undefined;
scheduleHide('cache grace expired');
}, 5000);
useCallback(
(state, prevState, data) => {
const client = mxRef.current;
if (state === SyncState.Prepared || state === SyncState.Syncing) {
if (state === SyncState.Prepared) {
console.log(
'[ClientRoot] Prepared from',
prevState ?? 'nothing',
data?.fromCache ? '(cache)' : '(network)',
);
}
} else {
// First network sync completed: whatever we have is what the UI shows.
scheduleHide('first network sync completed');
}
recoverInFlight.current = false;
return;
}
if (state !== SyncState.Error || !client) {
return;
}
if (tryHide(data?.fromCache ? 'cache populated' : 'first network sync')) {
return;
}
// Sync failed (no network, first sync never landed). Show whatever the
// cache restored instead of leaving the splash up.
if (client.getRooms().length > 0) scheduleHide('sync error with cached chats');
if (recoverInFlight.current) {
return;
}
recoverInFlight.current = true;
console.warn('[ClientRoot] Sync error after sleep/network blip, soft-recovering...');
const recover = () => {
if (!mxRef.current) {
if (data?.fromCache) {
// Cache-only prepared: the room list is still being restored, so wait
// for it, but hide anyway once the grace expires so we never block the
// UI when offline.
if (firstNetworkSyncGrace.current === undefined) {
firstNetworkSyncGrace.current = window.setTimeout(() => {
firstNetworkSyncGrace.current = undefined;
scheduleHide('cache grace expired');
}, 5000);
}
} else {
// First network sync completed: whatever we have is what the UI shows.
scheduleHide('first network sync completed');
}
recoverInFlight.current = false;
return;
}
const c = mxRef.current;
if (!c.clientRunning) {
startClient(c)
.catch((err) => console.warn('[ClientRoot] Soft recover startClient failed:', err))
.finally(() => {
recoverInFlight.current = false;
});
if (state !== SyncState.Error || !client) {
return;
}
try {
c.retryImmediately();
} catch (err) {
console.warn('[ClientRoot] Soft recover retryImmediately failed:', err);
}
recoverInFlight.current = false;
};
// Give Wi‑Fi a moment to come back after lid open / resume
window.setTimeout(recover, 1500);
}, [tryHide, scheduleHide])
// Sync failed (no network, first sync never landed). Show whatever the
// cache restored instead of leaving the splash up.
if (client.getRooms().length > 0) scheduleHide('sync error with cached chats');
if (recoverInFlight.current) {
return;
}
recoverInFlight.current = true;
console.warn('[ClientRoot] Sync error after sleep/network blip, soft-recovering...');
const recover = () => {
if (!mxRef.current) {
recoverInFlight.current = false;
return;
}
const c = mxRef.current;
if (!c.clientRunning) {
startClient(c)
.catch((err) => console.warn('[ClientRoot] Soft recover startClient failed:', err))
.finally(() => {
recoverInFlight.current = false;
});
return;
}
try {
c.retryImmediately();
} catch (err) {
console.warn('[ClientRoot] Soft recover retryImmediately failed:', err);
}
recoverInFlight.current = false;
};
// Give Wi‑Fi a moment to come back after lid open / resume
window.setTimeout(recover, 1500);
},
[tryHide, scheduleHide],
),
);
// Also nudge sync when the laptop wakes / network returns
@@ -399,7 +428,11 @@ export function ClientRoot({ children }: ClientRootProps) {
const nudge = () => {
if (document.visibilityState !== 'visible') return;
const syncState = mx.getSyncState();
if (syncState === SyncState.Error || syncState === SyncState.Reconnecting || !mx.clientRunning) {
if (
syncState === SyncState.Error ||
syncState === SyncState.Reconnecting ||
!mx.clientRunning
) {
console.log('[ClientRoot] Online/visible again, nudging sync', syncState);
if (!mx.clientRunning) {
startClient(mx).catch(() => {});
+1 -1
View File
@@ -27,7 +27,7 @@ export function SyncStatus({ mx }: SyncStatusProps) {
}
return { current, previous };
});
}, [])
}, []),
);
if (
+5 -3
View File
@@ -1,15 +1,17 @@
import React, { useEffect, useState } from 'react';
import { Box, Button, Text, config, toRem } from 'folds';
import { getVersion } from '@tauri-apps/api/app';
import { Icon, Icons } from '../../components/icons';
import { Page, PageHero, PageHeroSection } from '../../components/page';
import PaarrotSVG from '../../../../public/res/svg/paarrot.svg';
import { getVersion } from '@tauri-apps/api/app';
export function WelcomePage() {
const [version, setVersion] = useState<string>('');
useEffect(() => {
getVersion().then(setVersion).catch(() => setVersion(''));
getVersion()
.then(setVersion)
.catch(() => setVersion(''));
}, []);
return (
<Page>
@@ -25,7 +27,7 @@ export function WelcomePage() {
title="Welcome to Paarrot"
subTitle={
<span>
Squawk to yer mateys! {' '}
Squawk to yer mateys!{' '}
{version && (
<a
href="https://github.com/Paarrot/Paarrot-Desktop/releases/latest"
+66 -48
View File
@@ -1,10 +1,22 @@
import React, { MouseEventHandler, forwardRef, useMemo, useRef, useState } from 'react';
import { useAtom, useAtomValue } from 'jotai';
import { Avatar, Box, Button, IconButton, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Avatar,
Box,
Button,
IconButton,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
config,
toRem,
} from 'folds';
import { useVirtualizer } from '@tanstack/react-virtual';
import FocusTrap from 'focus-trap-react';
import { useNavigate } from 'react-router-dom';
import { Icon, Icons } from '../../../components/icons';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { factoryRoomIdByActivity } from '../../../utils/sort';
import {
@@ -17,7 +29,13 @@ import {
NavItemContent,
NavLink,
} from '../../../components/nav';
import { getDirectCreatePath, getDirectRoomPath, getDirectNotificationsPath, getDirectInvitesPath, getDirectSearchPath } from '../../pathUtils';
import {
getDirectCreatePath,
getDirectRoomPath,
getDirectNotificationsPath,
getDirectInvitesPath,
getDirectSearchPath,
} from '../../pathUtils';
import { getCanonicalAliasOrRoomId } from '../../../utils/matrix';
import { useSelectedRoom } from '../../../hooks/router/useSelectedRoom';
import { VirtualTile } from '../../../components/virtualizer';
@@ -41,9 +59,13 @@ import {
getRoomNotificationMode,
useRoomsNotificationPreferencesContext,
} from '../../../hooks/useRoomsNotificationPreferences';
import { useDirectCreateSelected, useDirectSearchSelected } from '../../../hooks/router/useDirectSelected';
import {
useDirectCreateSelected,
useDirectSearchSelected,
} from '../../../hooks/router/useDirectSelected';
import { allInvitesAtom } from '../../../state/room-list/inviteList';
import { UnreadBadge } from '../../../components/unread-badge';
import { UnreadBadge } from '../../../components/unread-badge';
type DirectMenuProps = {
requestClose: () => void;
};
@@ -168,11 +190,7 @@ function InvitesNavItem() {
const inviteCount = allInvites.length;
return (
<NavItem
variant="Background"
radii="400"
highlight={inviteCount > 0}
>
<NavItem variant="Background" radii="400" highlight={inviteCount > 0}>
<NavLink to={getDirectInvitesPath()}>
<NavItemContent>
<Box as="span" grow="Yes" alignItems="Center" gap="200">
@@ -233,7 +251,7 @@ export function Direct() {
const noRoomToDisplay = directs.length === 0;
const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom());
const scrollRef = useRef<HTMLDivElement>(null);
const reorderTrigger = useRoomListReorder(mx, directs);
const sortedDirects = useMemo(() => {
@@ -254,7 +272,7 @@ export function Direct() {
});
const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) =>
closedCategories.has(categoryId)
closedCategories.has(categoryId),
);
return (
@@ -315,44 +333,44 @@ export function Direct() {
</RoomNavCategoryButton>
</NavCategoryHeader>
{sortedDirects.length > 0 && (
<div data-nav-rooms="">
<div
ref={animationRef}
data-nav-room-list=""
style={{
position: 'relative',
height: virtualizer.getTotalSize(),
}}
>
{virtualizer.getVirtualItems().map((vItem) => {
const roomId = sortedDirects[vItem.index];
const room = mx.getRoom(roomId);
if (!room) return null;
const selected = selectedRoomId === roomId;
<div data-nav-rooms="">
<div
ref={animationRef}
data-nav-room-list=""
style={{
position: 'relative',
height: virtualizer.getTotalSize(),
}}
>
{virtualizer.getVirtualItems().map((vItem) => {
const roomId = sortedDirects[vItem.index];
const room = mx.getRoom(roomId);
if (!room) return null;
const selected = selectedRoomId === roomId;
return (
<VirtualTile
virtualItem={vItem}
key={roomId}
ref={virtualizer.measureElement}
data-room-id={roomId}
>
<RoomNavItem
room={room}
selected={selected}
showAvatar
direct
linkPath={getDirectRoomPath(getCanonicalAliasOrRoomId(mx, roomId))}
notificationMode={getRoomNotificationMode(
notificationPreferences,
room.roomId
)}
/>
</VirtualTile>
);
})}
return (
<VirtualTile
virtualItem={vItem}
key={roomId}
ref={virtualizer.measureElement}
data-room-id={roomId}
>
<RoomNavItem
room={room}
selected={selected}
showAvatar
direct
linkPath={getDirectRoomPath(getCanonicalAliasOrRoomId(mx, roomId))}
notificationMode={getRoomNotificationMode(
notificationPreferences,
room.roomId,
)}
/>
</VirtualTile>
);
})}
</div>
</div>
</div>
)}
</NavCategory>
</Box>
+1 -4
View File
@@ -29,10 +29,7 @@ export function DirectRouteRoomProvider({ children }: { children: ReactNode }) {
if (!room || !isJoinedDirect) {
return (
<JoinBeforeNavigate
roomIdOrAlias={roomIdOrAlias ?? rawRoomIdOrAlias!}
eventId={eventId}
/>
<JoinBeforeNavigate roomIdOrAlias={roomIdOrAlias ?? rawRoomIdOrAlias!} eventId={eventId} />
);
}
+16 -2
View File
@@ -1,7 +1,21 @@
import React, { FormEventHandler, useCallback, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import FocusTrap from 'focus-trap-react';
import { Avatar, Box, Button, Dialog, Header, IconButton, Input, Overlay, OverlayBackdrop, OverlayCenter, Text, color, config } from 'folds';
import {
Avatar,
Box,
Button,
Dialog,
Header,
IconButton,
Input,
Overlay,
OverlayBackdrop,
OverlayCenter,
Text,
color,
config,
} from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
NavCategory,
@@ -30,7 +44,7 @@ export function AddServer() {
const serverInputRef = useRef<HTMLInputElement>(null);
const [exploreState] = useAsyncCallback(
useCallback((server: string) => mx.publicRooms({ server, limit: 1 }), [mx])
useCallback((server: string) => mx.publicRooms({ server, limit: 1 }), [mx]),
);
const getInputServer = (): string | undefined => {
+1 -1
View File
@@ -1,7 +1,7 @@
import React from 'react';
import { Box, IconButton, Scroll, Text } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { useClientConfig } from '../../../hooks/useClientConfig';
import { RoomCard, RoomCardGrid } from '../../../components/room-card';
import { allRoomsAtom } from '../../../state/room-list/roomList';
+21 -5
View File
@@ -8,13 +8,29 @@ import React, {
useRef,
useState,
} from 'react';
import { Box, Button, Chip, IconButton, Input, Line, Menu, MenuItem, PopOut, RectCords, Scroll, Spinner, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
Button,
Chip,
IconButton,
Input,
Line,
Menu,
MenuItem,
PopOut,
RectCords,
Scroll,
Spinner,
Text,
config,
toRem,
} from 'folds';
import { useNavigate, useParams, useSearchParams } from 'react-router-dom';
import FocusTrap from 'focus-trap-react';
import { useAtomValue } from 'jotai';
import { useQuery } from '@tanstack/react-query';
import { MatrixClient, Method, RoomType } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageContentCenter, PageHeader } from '../../../components/page';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { RoomTopicViewer } from '../../../components/room-topic-viewer';
@@ -38,7 +54,7 @@ const useServerSearchParams = (searchParams: URLSearchParams): ExploreServerPath
type: searchParams.get('type') ?? undefined,
instance: searchParams.get('instance') ?? undefined,
}),
[searchParams]
[searchParams],
);
type RoomTypeFilter = {
@@ -61,7 +77,7 @@ const useRoomTypeFilters = (): RoomTypeFilter[] =>
value: 'null',
},
],
[]
[],
);
const FALLBACK_ROOMS_LIMIT = 24;
@@ -374,7 +390,7 @@ export function PublicRooms() {
room_types: roomType !== undefined ? [roomType] : undefined,
},
third_party_instance_id: serverSearchParams.instance,
}
},
);
}, [mx, server, serverSearchParams]);
+128 -104
View File
@@ -1,11 +1,23 @@
import React, { MouseEventHandler, forwardRef, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Avatar, Box, Button, IconButton, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Avatar,
Box,
Button,
IconButton,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
config,
toRem,
} from 'folds';
import { useVirtualizer } from '@tanstack/react-virtual';
import { useAtom, useAtomValue } from 'jotai';
import FocusTrap from 'focus-trap-react';
import { Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import { factoryRoomIdByActivity, factoryRoomIdByAtoZ } from '../../../utils/sort';
import {
NavButton,
@@ -34,7 +46,11 @@ import {
import { useHomeRooms } from './useHomeRooms';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { VirtualTile } from '../../../components/virtualizer';
import { RoomNavCategoryButton, RoomNavItem, UnjoinedSubRoomItem } from '../../../features/room-nav';
import {
RoomNavCategoryButton,
RoomNavItem,
UnjoinedSubRoomItem,
} from '../../../features/room-nav';
import { makeNavCategoryId } from '../../../state/closedNavCategories';
import { roomToUnreadAtom } from '../../../state/room/roomToUnread';
import { useCategoryHandler } from '../../../hooks/useCategoryHandler';
@@ -108,7 +124,7 @@ const HomeMenu = forwardRef<HTMLDivElement, HomeMenuProps>(
</Box>
</Menu>
);
}
},
);
function HomeHeader() {
@@ -117,11 +133,11 @@ function HomeHeader() {
const mx = useMatrixClient();
const orphanRooms = useHomeRooms();
const rooms = useMemo(() => {
return orphanRooms
.map((roomId) => mx.getRoom(roomId))
.filter((room): room is Room => room !== null);
}, [mx, orphanRooms]);
const rooms = useMemo(
() =>
orphanRooms.map((roomId) => mx.getRoom(roomId)).filter((room): room is Room => room !== null),
[mx, orphanRooms],
);
const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
const cords = evt.currentTarget.getBoundingClientRect();
@@ -223,7 +239,7 @@ function HomeEmpty() {
);
}
type RoomListItem =
type RoomListItem =
| { type: 'room'; roomId: string; room: Room; depth: number; parentId?: string; isLast?: boolean }
| { type: 'unjoined-subroom'; roomId: string; depth: number; parentId: string; isLast?: boolean };
@@ -247,9 +263,9 @@ export function Home() {
const items = Array.from(rooms).sort(
closedCategories.has(DEFAULT_CATEGORY_ID)
? factoryRoomIdByActivity(mx)
: factoryRoomIdByAtoZ(mx)
: factoryRoomIdByAtoZ(mx),
);
if (closedCategories.has(DEFAULT_CATEGORY_ID)) {
return items.filter((rId) => roomToUnread.has(rId) || rId === selectedRoomId);
}
@@ -261,23 +277,28 @@ export function Home() {
const items: RoomListItem[] = [];
const processedRooms = new Set<string>();
const addRoomAndSubRooms = (roomId: string, depth: number = 0, parentId?: string, isLast: boolean = false) => {
const addRoomAndSubRooms = (
roomId: string,
depth: number = 0,
parentId?: string,
isLast: boolean = false,
) => {
if (processedRooms.has(roomId)) return; // Prevent infinite loops
processedRooms.add(roomId);
const room = mx.getRoom(roomId);
if (room) {
// Joined room - show normally
items.push({ type: 'room', roomId, room, depth, parentId, isLast });
// Get sub-rooms from room state
const subRoomsEvent = room.currentState.getStateEvents(StateEvent.PaarrotSubRooms, '');
const subRooms = subRoomsEvent?.getContent<{ children: string[] }>()?.children ?? [];
// Filter to only joined sub-rooms
const joinedSubRooms = subRooms.filter(subRoomId => mx.getRoom(subRoomId));
const joinedSubRooms = subRooms.filter((subRoomId) => mx.getRoom(subRoomId));
// Add sub-rooms recursively
joinedSubRooms.forEach((subRoomId, index) => {
addRoomAndSubRooms(subRoomId, depth + 1, roomId, index === joinedSubRooms.length - 1);
@@ -287,17 +308,17 @@ export function Home() {
// Build set of all sub-room IDs to identify top-level rooms
const allSubRoomIds = new Set<string>();
sortedRooms.forEach(roomId => {
sortedRooms.forEach((roomId) => {
const room = mx.getRoom(roomId);
if (room) {
const subRoomsEvent = room.currentState.getStateEvents(StateEvent.PaarrotSubRooms, '');
const subRooms = subRoomsEvent?.getContent<{ children: string[] }>()?.children ?? [];
subRooms.forEach(id => allSubRoomIds.add(id));
subRooms.forEach((id) => allSubRoomIds.add(id));
}
});
// Only add top-level rooms (rooms that aren't sub-rooms of another)
sortedRooms.forEach(roomId => {
sortedRooms.forEach((roomId) => {
if (!allSubRoomIds.has(roomId)) {
addRoomAndSubRooms(roomId);
}
@@ -314,7 +335,7 @@ export function Home() {
});
const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) =>
closedCategories.has(categoryId)
closedCategories.has(categoryId),
);
return (
@@ -366,15 +387,10 @@ export function Home() {
onCancel={() => setOpen(false)}
onOpen={(roomIdOrAlias, viaServers, eventId) => {
setOpen(false);
const searchParams: _RoomSearchParams = {
viaServers: viaServers?.join(',')
const searchParams: _RoomSearchParams = {
viaServers: viaServers?.join(','),
};
navigate(
withSearchParam(
getHomeRoomPath(roomIdOrAlias),
searchParams
)
);
navigate(withSearchParam(getHomeRoomPath(roomIdOrAlias), searchParams));
}}
/>
)}
@@ -411,84 +427,92 @@ export function Home() {
</NavCategoryHeader>
<PluginNavSlot location="home-section" />
{listItems.length > 0 && (
<div data-nav-rooms="">
<div
data-nav-room-list=""
style={{
position: 'relative',
height: virtualizer.getTotalSize(),
}}
>
{virtualizer.getVirtualItems().map((vItem) => {
const item = listItems[vItem.index];
if (!item) return null;
<div data-nav-rooms="">
<div
data-nav-room-list=""
style={{
position: 'relative',
height: virtualizer.getTotalSize(),
}}
>
{virtualizer.getVirtualItems().map((vItem) => {
const item = listItems[vItem.index];
if (!item) return null;
if (item.type === 'unjoined-subroom') {
return (
<VirtualTile
virtualItem={vItem}
key={vItem.index}
ref={virtualizer.measureElement}
>
<UnjoinedSubRoomItem roomId={item.roomId} depth={item.depth} isLast={item.isLast} />
</VirtualTile>
);
}
if (item.type === 'unjoined-subroom') {
return (
<VirtualTile
virtualItem={vItem}
key={vItem.index}
ref={virtualizer.measureElement}
>
<UnjoinedSubRoomItem
roomId={item.roomId}
depth={item.depth}
isLast={item.isLast}
/>
</VirtualTile>
);
}
const selected = selectedRoomId === item.roomId;
const paddingLeft = item.depth > 0 ? '30px' : undefined;
let treeIcon = '';
if (item.depth > 0) {
treeIcon = item.isLast ? '╰' : '├';
}
const selected = selectedRoomId === item.roomId;
const paddingLeft = item.depth > 0 ? '30px' : undefined;
return (
<VirtualTile
virtualItem={vItem}
key={vItem.index}
ref={virtualizer.measureElement}
>
<div
data-nav-depth={item.depth}
style={{
paddingLeft,
display: 'flex',
alignItems: 'center',
minHeight: item.depth > 0 ? '1.5rem' : undefined,
position: 'relative',
}}
>
{treeIcon && (
<span style={{
paddingRight: '2px',
opacity: 0.5,
fontFamily: 'monospace',
fontSize: '14px',
lineHeight: '1',
userSelect: 'none'
}}>
{treeIcon}
</span>
)}
<div style={{ flex: 1, minWidth: 0 }}>
<RoomNavItem
room={item.room}
selected={selected}
hideIcon={item.depth > 0}
linkPath={getHomeRoomPath(getCanonicalAliasOrRoomId(mx, item.roomId))}
notificationMode={getRoomNotificationMode(
notificationPreferences,
item.room.roomId
let treeIcon = '';
if (item.depth > 0) {
treeIcon = item.isLast ? '╰' : '├';
}
return (
<VirtualTile
virtualItem={vItem}
key={vItem.index}
ref={virtualizer.measureElement}
>
<div
data-nav-depth={item.depth}
style={{
paddingLeft,
display: 'flex',
alignItems: 'center',
minHeight: item.depth > 0 ? '1.5rem' : undefined,
position: 'relative',
}}
>
{treeIcon && (
<span
style={{
paddingRight: '2px',
opacity: 0.5,
fontFamily: 'monospace',
fontSize: '14px',
lineHeight: '1',
userSelect: 'none',
}}
>
{treeIcon}
</span>
)}
/>
</div>
</div>
</VirtualTile>
);
})}
<div style={{ flex: 1, minWidth: 0 }}>
<RoomNavItem
room={item.room}
selected={selected}
hideIcon={item.depth > 0}
linkPath={getHomeRoomPath(
getCanonicalAliasOrRoomId(mx, item.roomId),
)}
notificationMode={getRoomNotificationMode(
notificationPreferences,
item.room.roomId,
)}
/>
</div>
</div>
</VirtualTile>
);
})}
</div>
</div>
</div>
)}
</NavCategory>
</Box>
@@ -1,10 +1,16 @@
import React, { useCallback, useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Avatar, Box, Text, Badge } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { useAtom, useSetAtom } from 'jotai';
import { Room, Thread, ThreadEvent } from 'matrix-js-sdk';
import { NavCategory, NavCategoryHeader, NavItem, NavItemContent, NavButton } from '../../../components/nav';
import { Icon, Icons } from '../../../components/icons';
import {
NavCategory,
NavCategoryHeader,
NavItem,
NavItemContent,
NavButton,
} from '../../../components/nav';
import { RoomNavCategoryButton } from '../../../features/room-nav';
import { makeNavCategoryId } from '../../../state/closedNavCategories';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
@@ -39,8 +45,7 @@ function ThreadNavItem({ room, thread, selected }: ThreadNavItemProps) {
const { rootEvent } = thread;
const senderId = rootEvent?.getSender() ?? '';
const senderName =
getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId;
const senderName = getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId;
const rootBody = rootEvent?.getContent()?.body ?? '';
const replyCount = thread.length;
@@ -69,7 +74,12 @@ function ThreadNavItem({ room, thread, selected }: ThreadNavItemProps) {
<Avatar size="200" radii="400">
<Icon src={Icons.Thread} size="100" />
</Avatar>
<Box as="span" grow="Yes" direction="Column" style={{ overflow: 'hidden', minWidth: 0 }}>
<Box
as="span"
grow="Yes"
direction="Column"
style={{ overflow: 'hidden', minWidth: 0 }}
>
<Text as="span" size="Inherit" truncate>
{senderName}
</Text>
@@ -105,18 +115,20 @@ export function HomeThreadsCategory({ rooms }: HomeThreadsCategoryProps) {
const mx = useMatrixClient();
const [closedCategories, setClosedCategories] = useAtom(useClosedNavCategoriesAtom());
const getParticipatedThreads = useCallback((): ThreadEntry[] =>
rooms.reduce<ThreadEntry[]>((acc, roomId) => {
const room = mx.getRoom(roomId);
if (!room) return acc;
return acc.concat(
room
.getThreads()
.filter((t) => t.hasCurrentUserParticipated)
.map((t) => ({ room, thread: t }))
);
}, []),
[mx, rooms]);
const getParticipatedThreads = useCallback(
(): ThreadEntry[] =>
rooms.reduce<ThreadEntry[]>((acc, roomId) => {
const room = mx.getRoom(roomId);
if (!room) return acc;
return acc.concat(
room
.getThreads()
.filter((t) => t.hasCurrentUserParticipated)
.map((t) => ({ room, thread: t })),
);
}, []),
[mx, rooms],
);
const [threads, setThreads] = useState<ThreadEntry[]>(getParticipatedThreads);
@@ -148,7 +160,7 @@ export function HomeThreadsCategory({ rooms }: HomeThreadsCategoryProps) {
}, [mx, rooms, getParticipatedThreads]);
const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) =>
closedCategories.has(categoryId)
closedCategories.has(categoryId),
);
if (threads.length === 0) return null;
+8 -2
View File
@@ -1,8 +1,14 @@
import React, { useRef } from 'react';
import { Avatar, Box, Text } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { useAtomValue } from 'jotai';
import { NavCategory, NavCategoryHeader, NavItem, NavItemContent, NavLink } from '../../../components/nav';
import { Icon, Icons } from '../../../components/icons';
import {
NavCategory,
NavCategoryHeader,
NavItem,
NavItemContent,
NavLink,
} from '../../../components/nav';
import { getInboxInvitesPath, getInboxNotificationsPath } from '../../pathUtils';
import {
useInboxInvitesSelected,
+27 -12
View File
@@ -1,10 +1,25 @@
import React, { useCallback, useMemo, useRef, useState } from 'react';
import { Avatar, Badge, Box, Button, Chip, IconButton, Overlay, OverlayBackdrop, OverlayCenter, Scroll, Spinner, Text, color, config } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Avatar,
Badge,
Box,
Button,
Chip,
IconButton,
Overlay,
OverlayBackdrop,
OverlayCenter,
Scroll,
Spinner,
Text,
color,
config,
} from 'folds';
import { useAtomValue } from 'jotai';
import { RoomTopicEventContent } from 'matrix-js-sdk/lib/types';
import FocusTrap from 'focus-trap-react';
import { MatrixClient, MatrixError, Room } from 'matrix-js-sdk';
import { Icon, Icons } from '../../../components/icons';
import {
Page,
PageContent,
@@ -91,7 +106,7 @@ const makeInviteData = (mx: MatrixClient, room: Room, useAuthentication: boolean
const senderId = memberEvent?.getSender();
const senderName = senderId
? getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId
? (getMemberDisplayName(room, senderId) ?? getMxIdLocalPart(senderId) ?? senderId)
: undefined;
const inviteTs = memberEvent?.getTs();
const reason =
@@ -161,10 +176,10 @@ function InviteCard({
await addRoomIdToMDirect(mx, invite.roomId, dmUserId);
}
onNavigate(invite.roomId, invite.isSpace);
}, [mx, invite, userId, onNavigate])
}, [mx, invite, userId, onNavigate]),
);
const [leaveState, leave] = useAsyncCallback<Record<string, never>, MatrixError, []>(
useCallback(() => mx.leave(invite.roomId), [mx, invite])
useCallback(() => mx.leave(invite.roomId), [mx, invite]),
);
const joining =
@@ -464,7 +479,7 @@ function UnknownInvites({
const roomIds = invites.map((invite) => invite.roomId);
await rateLimitedActions(roomIds, (roomId) => mx.leave(roomId));
}, [mx, invites])
}, [mx, invites]),
);
const declining = declineAllStatus.status === AsyncStatus.Loading;
@@ -540,7 +555,7 @@ function SpamInvites({
const roomIds = invites.map((invite) => invite.roomId);
await rateLimitedActions(roomIds, (roomId) => mx.leave(roomId));
}, [mx, invites])
}, [mx, invites]),
);
const [reportAllStatus, reportAll] = useAsyncCallback(
@@ -548,18 +563,18 @@ function SpamInvites({
const roomIds = invites.map((invite) => invite.roomId);
await rateLimitedActions(roomIds, (roomId) => mx.reportRoom(roomId, 'Spam Invite'));
}, [mx, invites])
}, [mx, invites]),
);
const ignoredUsers = useIgnoredUsers();
const unignoredUsers = Array.from(new Set(invites.map((invite) => invite.senderId))).filter(
(user) => !ignoredUsers.includes(user)
(user) => !ignoredUsers.includes(user),
);
const [blockAllStatus, blockAll] = useAsyncCallback(
useCallback(
() => mx.setIgnoredUsers([...ignoredUsers, ...unignoredUsers]),
[mx, ignoredUsers, unignoredUsers]
)
[mx, ignoredUsers, unignoredUsers],
),
);
const declining = declineAllStatus.status === AsyncStatus.Loading;
@@ -714,7 +729,7 @@ export function Invites() {
const [compact, setCompact] = useState(document.body.clientWidth <= COMPACT_CARD_WIDTH);
useElementSizeObserver(
useCallback(() => containerRef.current, []),
useCallback((width) => setCompact(width <= COMPACT_CARD_WIDTH), [])
useCallback((width) => setCompact(width <= COMPACT_CARD_WIDTH), []),
);
const screenSize = useScreenSizeContext();
+28 -34
View File
@@ -1,7 +1,6 @@
/* eslint-disable react/destructuring-assignment */
import React, { MouseEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Avatar, Box, Chip, Header, IconButton, Scroll, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { useSearchParams } from 'react-router-dom';
import {
INotification,
@@ -16,6 +15,7 @@ import { useVirtualizer } from '@tanstack/react-virtual';
import { HTMLReactParserOptions } from 'html-react-parser';
import { Opts as LinkifyOpts } from 'linkifyjs';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageContentCenter, PageHeader } from '../../../components/page';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { getMxIdLocalPart, mxcUrlToHttp } from '../../../utils/matrix';
@@ -102,7 +102,7 @@ type SilentReloadTimeline = () => Promise<void>;
const groupNotifications = (
notifications: INotification[],
allowRooms: Set<string>
allowRooms: Set<string>,
): RoomNotificationsGroup[] => {
const groups: RoomNotificationsGroup[] = [];
notifications.forEach((notification) => {
@@ -124,7 +124,7 @@ const groupNotifications = (
const useNotificationTimeline = (
paginationLimit: number,
onlyHighlight?: boolean
onlyHighlight?: boolean,
): [NotificationTimeline, LoadTimeline, SilentReloadTimeline] => {
const mx = useMatrixClient();
const allRooms = useAtomValue(allRoomsAtom);
@@ -140,10 +140,10 @@ const useNotificationTimeline = (
return mx.http.authedRequest<INotificationsResponse>(
Method.Get,
'/notifications',
queryParams
queryParams,
);
},
[mx]
[mx],
);
const loadTimeline: LoadTimeline = useCallback(
@@ -154,7 +154,7 @@ const useNotificationTimeline = (
const data = await fetchNotifications(
from,
paginationLimit,
onlyHighlight ? 'highlight' : undefined
onlyHighlight ? 'highlight' : undefined,
);
const groups = groupNotifications(data.notifications, allJoinedRooms);
@@ -168,7 +168,7 @@ const useNotificationTimeline = (
return currentTimeline;
});
},
[paginationLimit, onlyHighlight, fetchNotifications, allJoinedRooms]
[paginationLimit, onlyHighlight, fetchNotifications, allJoinedRooms],
);
/**
@@ -179,7 +179,7 @@ const useNotificationTimeline = (
const data = await fetchNotifications(
undefined,
paginationLimit,
onlyHighlight ? 'highlight' : undefined
onlyHighlight ? 'highlight' : undefined,
);
const groups = groupNotifications(data.notifications, allJoinedRooms);
setNotificationTimeline({
@@ -199,7 +199,9 @@ type NotificationItemProps = {
notification: INotification;
getMemberPowerTag: ReturnType<typeof useGetMemberPowerTag>;
accessibleTagColors: Map<string, string> | undefined;
renderMatrixEvent: ReturnType<typeof useMatrixEventRenderer<[IRoomEvent, string, GetContentCallback]>>;
renderMatrixEvent: ReturnType<
typeof useMatrixEventRenderer<[IRoomEvent, string, GetContentCallback]>
>;
handleOpenClick: MouseEventHandler;
legacyUsernameColor?: boolean;
hour24Clock: boolean;
@@ -225,16 +227,13 @@ function NotificationItem({
const { event } = notification;
const displayName =
getMemberDisplayName(room, event.sender) ??
getMxIdLocalPart(event.sender) ??
event.sender;
getMemberDisplayName(room, event.sender) ?? getMxIdLocalPart(event.sender) ?? event.sender;
const senderAvatarMxc = getMemberAvatarMxc(room, event.sender);
const getContent = (() => event.content) as GetContentCallback;
const relation = event.content['m.relates_to'];
const replyEventId = relation?.['m.in_reply_to']?.event_id;
const threadRootId =
relation?.rel_type === RelationType.Thread ? relation.event_id : undefined;
const threadRootId = relation?.rel_type === RelationType.Thread ? relation.event_id : undefined;
// Get custom user color from avatar metadata
const customUserColor = useOtherUserColor(event.sender, room);
@@ -248,7 +247,8 @@ function NotificationItem({
: undefined;
// Priority: custom user color > tag color (non-legacy) > colorMXID (legacy)
const usernameColor = customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor);
const usernameColor =
customUserColor ?? (legacyUsernameColor ? colorMXID(event.sender) : tagColor);
return (
<SequenceCard
@@ -265,14 +265,8 @@ function NotificationItem({
userId={event.sender}
src={
senderAvatarMxc
? mxcUrlToHttp(
mx,
senderAvatarMxc,
useAuthentication,
48,
48,
'crop'
) ?? undefined
? (mxcUrlToHttp(mx, senderAvatarMxc, useAuthentication, 48, 48, 'crop') ??
undefined)
: undefined
}
alt={displayName}
@@ -370,10 +364,10 @@ function RoomNotificationsGroupComp({
() => ({
...LINKIFY_OPTS,
render: factoryRenderLinkifyWithMention((href) =>
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler))
renderMatrixMention(mx, room.roomId, href, makeMentionCustomProps(mentionClickHandler)),
),
}),
[mx, room, mentionClickHandler]
[mx, room, mentionClickHandler],
);
const htmlReactParserOptions = useMemo<HTMLReactParserOptions>(
() =>
@@ -383,7 +377,7 @@ function RoomNotificationsGroupComp({
handleSpoilerClick: spoilerClickHandler,
handleMentionClick: mentionClickHandler,
}),
[mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication]
[mx, room, linkifyOpts, mentionClickHandler, spoilerClickHandler, useAuthentication],
);
const renderMatrixEvent = useMatrixEventRenderer<[IRoomEvent, string, GetContentCallback]>(
@@ -445,7 +439,7 @@ function RoomNotificationsGroupComp({
const editedEvent = getEditedEvent(
evt.event_id,
mEvent,
evtTimeline.getTimelineSet()
evtTimeline.getTimelineSet(),
);
const getContent = (() =>
editedEvent?.getContent()['m.new_content'] ??
@@ -522,7 +516,7 @@ function RoomNotificationsGroupComp({
</Text>
</Box>
);
}
},
);
const handleOpenClick: MouseEventHandler = (evt) => {
@@ -586,13 +580,13 @@ function RoomNotificationsGroupComp({
}
const useNotificationsSearchParams = (
searchParams: URLSearchParams
searchParams: URLSearchParams,
): InboxNotificationsPathSearchParams =>
useMemo(
() => ({
only: searchParams.get('only') ?? undefined,
}),
[searchParams]
[searchParams],
);
const DEFAULT_REFRESH_MS = 7000;
@@ -621,7 +615,7 @@ export function Notifications() {
setSearchParams(
new URLSearchParams({
only: 'highlight',
})
}),
);
return;
}
@@ -630,7 +624,7 @@ export function Notifications() {
const [notificationTimeline, _loadTimeline, silentReloadTimeline] = useNotificationTimeline(
24,
onlyHighlight
onlyHighlight,
);
const [timelineState, loadTimeline] = useAsyncCallback(_loadTimeline);
@@ -646,12 +640,12 @@ export function Notifications() {
useCallback(() => {
silentReloadTimeline();
}, [silentReloadTimeline]),
refreshIntervalTime
refreshIntervalTime,
);
const handleScrollTopVisibility = useCallback(
(onTop: boolean) => setRefreshIntervalTime(onTop ? DEFAULT_REFRESH_MS : -1),
[]
[],
);
useEffect(() => {
+2 -2
View File
@@ -1,8 +1,8 @@
import React, { MouseEventHandler, useState } from 'react';
import { Box, config, Menu, PopOut, RectCords, Text } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import FocusTrap from 'focus-trap-react';
import { useNavigate } from 'react-router-dom';
import { Icon, Icons } from '../../../components/icons';
import { SidebarAvatar, SidebarItem, SidebarItemTooltip } from '../../../components/sidebar';
import { stopPropagation } from '../../../utils/keyboard';
import { SequenceCard } from '../../../components/sequence-card';
@@ -122,7 +122,7 @@ export function CreateTab() {
? withSearchParam<_RoomSearchParams>(path, {
viaServers: encodeSearchParamValueArray(viaServers),
})
: path
: path,
);
}}
/>
+12 -10
View File
@@ -1,9 +1,9 @@
import React, { MouseEventHandler, forwardRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Box, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import FocusTrap from 'focus-trap-react';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import PaarrotSVG from '../../../../../public/res/svg/paarrot.svg';
import PaarrotUnreadSVG from '../../../../../public/res/svg/paarrot-unread.svg';
import PaarrotHighlightSVG from '../../../../../public/res/svg/paarrot-highlight.svg';
@@ -111,8 +111,8 @@ export function DirectTab() {
directUnread?.highlight
? PaarrotHighlightSVG
: directUnread?.total
? PaarrotUnreadSVG
: PaarrotSVG
? PaarrotUnreadSVG
: PaarrotSVG
}
alt="Direct Messages"
style={{ width: '100%', height: '100%', objectFit: 'contain' }}
@@ -121,13 +121,15 @@ export function DirectTab() {
)}
</SidebarItemTooltip>
{directUnread && directUnread.total > 0 && (
<div style={{
position: 'absolute',
bottom: '2px',
right: '2px',
pointerEvents: 'none',
zIndex: 2,
}}>
<div
style={{
position: 'absolute',
bottom: '2px',
right: '2px',
pointerEvents: 'none',
zIndex: 2,
}}
>
<UnreadBadge highlight={directUnread.highlight > 0} count={directUnread.total} />
</div>
)}
+1 -1
View File
@@ -1,8 +1,8 @@
import { Icon, Icons } from '../../../components/icons';
import React from 'react';
import { useNavigate } from 'react-router-dom';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { SidebarAvatar, SidebarItem, SidebarItemTooltip } from '../../../components/sidebar';
import { useExploreSelected } from '../../../hooks/router/useExploreSelected';
import {
+10 -5
View File
@@ -1,10 +1,10 @@
import React, { MouseEventHandler, forwardRef, useState } from 'react';
import { useNavigateWithTransition } from '../../../hooks/useViewTransitions';
import { Box, Line, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { useAtomValue } from 'jotai';
import FocusTrap from 'focus-trap-react';
import { useOrphanRooms } from '../../../state/hooks/roomList';
import { Icon, Icons } from '../../../components/icons';
import { useNavigateWithTransition } from '../../../hooks/useViewTransitions';
import { useOrphanRooms, useOrphanSpaces } from '../../../state/hooks/roomList';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { mDirectAtom } from '../../../state/mDirectList';
import { roomToParentsAtom } from '../../../state/room/roomToParents';
@@ -27,9 +27,14 @@ import { useMarkRoomsAsRead } from '../../../hooks/useMarkAsRead';
import { stopPropagation } from '../../../utils/keyboard';
import { useSetting } from '../../../state/hooks/settings';
import { settingsAtom } from '../../../state/settings';
import { makeHideHomeContent, parseHiddenSpaces, parseSidebar, useHiddenSpaces, useSidebarItems } from '../../../hooks/useSidebarItems';
import {
makeHideHomeContent,
parseHiddenSpaces,
parseSidebar,
useHiddenSpaces,
useSidebarItems,
} from '../../../hooks/useSidebarItems';
import { AccountDataEvent } from '../../../../types/matrix/accountData';
import { useOrphanSpaces } from '../../../state/hooks/roomList';
type HomeMenuProps = {
requestClose: () => void;
+2 -2
View File
@@ -1,8 +1,8 @@
import { Icon, Icons } from '../../../components/icons';
import React from 'react';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { useNavigateWithTransition } from '../../../hooks/useViewTransitions';
import { useAtomValue } from 'jotai';
import {
SidebarAvatar,
SidebarItem,
+1 -1
View File
@@ -1,7 +1,7 @@
import { Icon, Icons } from '../../../components/icons';
import React from 'react';
import { useAtom } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { SidebarAvatar, SidebarItem, SidebarItemTooltip } from '../../../components/sidebar';
import { searchModalAtom } from '../../../state/searchModal';
import * as sidebarCss from '../../../components/sidebar/Sidebar.css';
+13 -15
View File
@@ -1,7 +1,7 @@
import React, { MouseEventHandler, useState } from 'react';
import { Box, config, Line, Menu, MenuItem, PopOut, RectCords, Text } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../../components/icons';
import { useNavigateWithTransition } from '../../../hooks/useViewTransitions';
import { SidebarItem, SidebarAvatar } from '../../../components/sidebar';
import { UserAvatar } from '../../../components/user-avatar';
@@ -37,15 +37,16 @@ export function SettingsTab() {
const [customStatusOpen, setCustomStatusOpen] = useState(false);
const displayName = profile.displayName ?? getMxIdLocalPart(userId ?? '') ?? userId ?? '';
const avatarUrl = profile.avatarUrl && userId
? mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined
: undefined;
const avatarUrl =
profile.avatarUrl && userId
? (mxcUrlToHttp(mx, profile.avatarUrl, useAuthentication, 96, 96, 'crop') ?? undefined)
: undefined;
const { assetUrls } = useOtherUserCollectibles(userId ?? '');
const avatarDecorationUrl = pickAvatarDecorationUrl(assetUrls);
const nameplateUrl = pickNameplateUrl(assetUrls);
const [sidebarNameplateOpacity] = useSetting(settingsAtom, 'sidebarNameplateOpacity');
const nameplateIsVideo = Boolean(
assetUrls['nameplate:animated'] || assetUrls['nameplate:asset.webm']
assetUrls['nameplate:animated'] || assetUrls['nameplate:asset.webm'],
);
const openSettings = () => setSettings(true);
@@ -105,7 +106,7 @@ export function SettingsTab() {
)}
</div>
</SidebarAvatar>
<PopOut
anchor={menuAnchor}
position="Right"
@@ -129,12 +130,12 @@ export function SettingsTab() {
</Box>
<Line variant="Surface" size="300" />
<Box direction="Column" gap="100" style={{ padding: config.space.S100 }}>
<MenuItem
<MenuItem
onClick={() => {
setMenuAnchor(undefined);
navigate(`${getLoginPath()}?add-account=true`);
}}
size="300"
}}
size="300"
radii="300"
>
<Box gap="200" alignItems="Center">
@@ -185,12 +186,9 @@ export function SettingsTab() {
</FocusTrap>
}
/>
<CustomStatusDialog
open={customStatusOpen}
onClose={() => setCustomStatusOpen(false)}
/>
<CustomStatusDialog open={customStatusOpen} onClose={() => setCustomStatusOpen(false)} />
{settings && (
<Modal500 requestClose={closeSettings}>
<Settings requestClose={closeSettings} />
+50 -39
View File
@@ -9,9 +9,18 @@ import React, {
useRef,
useState,
} from 'react';
import { useNavigateWithTransition } from '../../../hooks/useViewTransitions';
import { Box, IconButton, Line, Menu, MenuItem, PopOut, RectCords, Text, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Box,
IconButton,
Line,
Menu,
MenuItem,
PopOut,
RectCords,
Text,
config,
toRem,
} from 'folds';
import { useAtom, useAtomValue } from 'jotai';
import { Room } from 'matrix-js-sdk';
import {
@@ -27,6 +36,8 @@ import {
import { autoScrollForElements } from '@atlaskit/pragmatic-drag-and-drop-auto-scroll/element';
import { combine } from '@atlaskit/pragmatic-drag-and-drop/combine';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../../components/icons';
import { useNavigateWithTransition } from '../../../hooks/useViewTransitions';
import {
useOrphanRooms,
useOrphanSpaces,
@@ -118,7 +129,7 @@ const SpaceMenu = forwardRef<HTMLDivElement, SpaceMenuProps>(
const allChild = useSpaceChildren(
allRoomsAtom,
room.roomId,
useRecursiveChildScopeFactory(mx, roomToParents)
useRecursiveChildScopeFactory(mx, roomToParents),
);
const unread = useRoomsUnread(allChild, roomToUnreadAtom);
@@ -276,7 +287,7 @@ const SpaceMenu = forwardRef<HTMLDivElement, SpaceMenuProps>(
</Box>
</Menu>
);
}
},
);
type InstructionType = Instruction['type'];
@@ -291,7 +302,7 @@ const useDraggableItem = (
item: SidebarDraggable,
targetRef: RefObject<HTMLElement>,
onDragging: (item?: SidebarDraggable) => void,
dragHandleRef?: RefObject<HTMLElement>
dragHandleRef?: RefObject<HTMLElement>,
): boolean => {
const [dragging, setDragging] = useState(false);
@@ -321,7 +332,7 @@ const useDraggableItem = (
const useDropTarget = (
item: SidebarDraggable,
targetRef: RefObject<HTMLElement>
targetRef: RefObject<HTMLElement>,
): Instruction | undefined => {
const [dropState, setDropState] = useState<Instruction>();
@@ -348,7 +359,7 @@ const useDropTarget = (
indentPerLevel: 0,
mode: 'standard',
block,
}
},
);
const instruction: Instruction | null = extractInstruction(insData);
@@ -370,7 +381,7 @@ const useDropTarget = (
function useDropTargetInstruction<T extends InstructionType>(
item: SidebarDraggable,
targetRef: RefObject<HTMLElement>,
instructionType: T
instructionType: T,
): T | undefined {
const [dropState, setDropState] = useState<T>();
@@ -406,8 +417,8 @@ const useDnDMonitor = (
onReorder: (
draggable: SidebarDraggable,
container: SidebarDraggable,
instruction: InstructionType
) => void
instruction: InstructionType,
) => void,
) => {
useEffect(() => {
const scrollElement = scrollRef.current;
@@ -424,15 +435,14 @@ const useDnDMonitor = (
const item = source.data.item as SidebarDraggable;
const containerItem = dropTargets[0].data.item as SidebarDraggable;
const instructionType = dropTargets[0].data.instructionType as
| InstructionType
| undefined;
InstructionType | undefined;
if (!instructionType) return;
onReorder(item, containerItem, instructionType);
},
}),
autoScrollForElements({
element: scrollElement,
})
}),
);
}, [scrollRef, onDragging, onReorder]);
};
@@ -469,7 +479,7 @@ function SpaceTab({
spaceId: space.roomId,
}
: space.roomId,
[folder, space]
[folder, space],
);
useDraggableItem(spaceDraggable, targetRef, onDragging);
@@ -701,16 +711,18 @@ function HiddenSpacesFolder({
const orphanRooms = useOrphanRooms(mx, allRoomsAtom, mDirects, roomToParents);
const homeUnread = useRoomsUnread(orphanRooms, roomToUnreadAtom);
const handleContextMenu = (spaceId: string): MouseEventHandler<HTMLButtonElement> => (evt) => {
evt.preventDefault();
const cords = evt.currentTarget.getBoundingClientRect();
setMenuSpaceId(spaceId);
setMenuIsHome(false);
setMenuAnchor((currentState) => {
if (currentState) return undefined;
return cords;
});
};
const handleContextMenu =
(spaceId: string): MouseEventHandler<HTMLButtonElement> =>
(evt) => {
evt.preventDefault();
const cords = evt.currentTarget.getBoundingClientRect();
setMenuSpaceId(spaceId);
setMenuIsHome(false);
setMenuAnchor((currentState) => {
if (currentState) return undefined;
return cords;
});
};
const handleHomeContextMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
evt.preventDefault();
@@ -752,12 +764,13 @@ function HiddenSpacesFolder({
<RoomsUnreadProvider rooms={hiddenSpaces}>
{(unread) => {
// Combine space unreads with home unreads if home is hidden
const totalUnread = homeHidden && homeUnread
? {
total: (unread?.total ?? 0) + homeUnread.total,
highlight: (unread?.highlight ?? 0) + homeUnread.highlight,
}
: unread;
const totalUnread =
homeHidden && homeUnread
? {
total: (unread?.total ?? 0) + homeUnread.total,
highlight: (unread?.highlight ?? 0) + homeUnread.highlight,
}
: unread;
return (
<SidebarItem
@@ -844,9 +857,7 @@ function HiddenSpacesFolder({
roomId={space.roomId}
src={getRoomAvatarUrl(mx, space, 96, useAuthentication) ?? undefined}
alt={space.name}
renderFallback={() => (
<Text size="H6">{nameInitials(space.name, 2)}</Text>
)}
renderFallback={() => <Text size="H6">{nameInitials(space.name, 2)}</Text>}
/>
</SidebarAvatar>
)}
@@ -1044,8 +1055,8 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) {
localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent));
mx.setAccountData(AccountDataEvent.CinnySpaces, newSpacesContent);
},
[mx, sidebarItems, setOpenedFolder, localEchoSidebarItem, orphanSpaces]
)
[mx, sidebarItems, setOpenedFolder, localEchoSidebarItem, orphanSpaces],
),
);
const selectedSpaceId = useSelectedSpace();
@@ -1090,7 +1101,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) {
localEchoSidebarItem(parseSidebar(mx, orphanSpaces, newSpacesContent));
mx.setAccountData(AccountDataEvent.CinnySpaces, newSpacesContent);
},
[mx, sidebarItems, orphanSpaces, localEchoSidebarItem]
[mx, sidebarItems, orphanSpaces, localEchoSidebarItem],
);
const handleHide = useCallback(
@@ -1100,7 +1111,7 @@ export function SpaceTabs({ scrollRef }: SpaceTabsProps) {
localEchoHiddenSpaces(parseHiddenSpaces(mx, newContent));
mx.setAccountData(AccountDataEvent.CinnySpaces, newContent);
},
[mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces]
[mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces],
);
if (sidebarItems.length === 0) return null;
@@ -1226,7 +1237,7 @@ export function HiddenSpacesTabs() {
localEchoHiddenSpaces(parseHiddenSpaces(mx, newContent));
mx.setAccountData(AccountDataEvent.CinnySpaces, newContent);
},
[mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces]
[mx, orphanSpaces, localEchoSidebarItem, localEchoHiddenSpaces],
);
const handleUnhideHome = useCallback(() => {
@@ -30,7 +30,7 @@ function UnverifiedIndicator() {
const verificationStatus = useDeviceVerificationStatus(
crypto,
mx.getSafeUserId(),
currentDevice?.device_id
currentDevice?.device_id,
);
const unverified = verificationStatus === VerificationStatus.Unverified;
@@ -38,7 +38,7 @@ function UnverifiedIndicator() {
const unverifiedDeviceCount = useUnverifiedDeviceCount(
crypto,
mx.getSafeUserId(),
otherDevicesId
otherDevicesId,
);
const [settings, setSettings] = useState(false);
+2 -9
View File
@@ -33,7 +33,7 @@ export function SpaceRouteRoomProvider({ children }: { children: ReactNode }) {
const isJoined = Boolean(room && allRooms.includes(room.roomId));
const isSpaceChild = Boolean(room && getSpaceChildren(space).includes(room.roomId));
const hasParentMapping = Boolean(
room && getAllParents(roomToParents, room.roomId).has(space.roomId)
room && getAllParents(roomToParents, room.roomId).has(space.roomId),
);
// roomToParents can lag behind live space state during catch-up sync.
@@ -45,14 +45,7 @@ export function SpaceRouteRoomProvider({ children }: { children: ReactNode }) {
parent: space.roomId,
children: [room.roomId],
});
}, [
room,
isJoined,
hasParentMapping,
isSpaceChild,
space.roomId,
setRoomToParents,
]);
}, [room, isJoined, hasParentMapping, isSpaceChild, space.roomId, setRoomToParents]);
if (!room || !isJoined) {
// room is not joined
+2 -2
View File
@@ -1,7 +1,7 @@
import React, { useRef } from 'react';
import { Box, Text, Scroll, IconButton } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import { useAtomValue } from 'jotai';
import { Icon, Icons } from '../../../components/icons';
import { Page, PageContent, PageContentCenter, PageHeader } from '../../../components/page';
import { MessageSearch } from '../../../features/message-search';
import { useSpace } from '../../../hooks/useSpace';
@@ -24,7 +24,7 @@ export function SpaceSearch() {
const rooms = useSpaceChildren(
allRoomsAtom,
space.roomId,
useRecursiveChildRoomScopeFactory(mx, mDirects, roomToParents)
useRecursiveChildRoomScopeFactory(mx, mDirects, roomToParents),
);
return (
+37 -20
View File
@@ -7,11 +7,26 @@ import React, {
useState,
} from 'react';
import { useAtom, useAtomValue } from 'jotai';
import { Avatar, Box, Button, IconButton, Line, Menu, MenuItem, PopOut, RectCords, Spinner, Text, color, config, toRem } from 'folds';
import { Icon, Icons } from '../../../components/icons';
import {
Avatar,
Box,
Button,
IconButton,
Line,
Menu,
MenuItem,
PopOut,
RectCords,
Spinner,
Text,
color,
config,
toRem,
} from 'folds';
import { JoinRule, Room, Thread, ThreadEvent } from 'matrix-js-sdk';
import { RoomJoinRulesEventContent } from 'matrix-js-sdk/lib/types';
import FocusTrap from 'focus-trap-react';
import { Icon, Icons } from '../../../components/icons';
import { useMatrixClient } from '../../../hooks/useMatrixClient';
import { mDirectAtom } from '../../../state/mDirectList';
import {
@@ -29,7 +44,11 @@ import {
useSpaceSearchSelected,
} from '../../../hooks/router/useSelectedSpace';
import { useSpace } from '../../../hooks/useSpace';
import { RoomNavCategoryButton, RoomNavItem, UnjoinedSubRoomItem } from '../../../features/room-nav';
import {
RoomNavCategoryButton,
RoomNavItem,
UnjoinedSubRoomItem,
} from '../../../features/room-nav';
import { makeNavCategoryId } from '../../../state/closedNavCategories';
import { roomToUnreadAtom } from '../../../state/room/roomToUnread';
import { useCategoryHandler } from '../../../hooks/useCategoryHandler';
@@ -152,7 +171,7 @@ function SpaceNavSection({
linkPath={getToLink(item.roomId)}
notificationMode={getRoomNotificationMode(
notificationPreferences,
item.roomId
item.roomId,
)}
/>
</div>
@@ -171,10 +190,7 @@ function SpaceNavSection({
showAvatar={mDirects.has(item.roomId)}
direct={mDirects.has(item.roomId)}
linkPath={getToLink(item.roomId)}
notificationMode={getRoomNotificationMode(
notificationPreferences,
room.roomId
)}
notificationMode={getRoomNotificationMode(notificationPreferences, room.roomId)}
/>
);
})}
@@ -192,7 +208,7 @@ function SpaceHeader() {
const joinRules = useStateEvent(
space,
StateEvent.RoomJoinRules
StateEvent.RoomJoinRules,
)?.getContent<RoomJoinRulesEventContent>();
const handleOpenMenu: MouseEventHandler<HTMLButtonElement> = (evt) => {
@@ -259,7 +275,7 @@ export function SpaceTombstone({ roomId, replacementRoomId }: SpaceTombstoneProp
return mx.joinRoom(replacementRoomId, {
viaServers: via,
});
}, [mx, roomId, replacementRoomId])
}, [mx, roomId, replacementRoomId]),
);
const replacementRoom = mx.getRoom(replacementRoomId);
@@ -343,7 +359,7 @@ export function Space() {
}
return undefined;
},
[mx, allJoinedRooms]
[mx, allJoinedRooms],
);
const hierarchy = useSpaceJoinedHierarchy(
@@ -358,12 +374,12 @@ export function Space() {
if (showRoom) return false;
return true;
},
[space.roomId, closedCategories, roomToUnread, selectedRoomId]
[space.roomId, closedCategories, roomToUnread, selectedRoomId],
),
useCallback(
(sId) => closedCategories.has(makeNavCategoryId(space.roomId, sId)),
[closedCategories, space.roomId]
)
[closedCategories, space.roomId],
),
);
// Build a global set of all sub-room IDs to filter from hierarchy
@@ -379,9 +395,10 @@ export function Space() {
}, [mx, allJoinedRooms, hierarchy]);
// Filter hierarchy to exclude sub-rooms (they'll be shown nested under their parent)
const filteredHierarchy = useMemo(() => {
return hierarchy.filter((entry) => !globalSubRoomIds.has(entry.roomId));
}, [hierarchy, globalSubRoomIds]);
const filteredHierarchy = useMemo(
() => hierarchy.filter((entry) => !globalSubRoomIds.has(entry.roomId)),
[hierarchy, globalSubRoomIds],
);
// One paper dropdown per space: space header + its rooms/sub-rooms
const navSections = useMemo(() => {
@@ -397,7 +414,7 @@ export function Space() {
const subRooms = subRoomsEvent?.getContent<{ children: string[] }>()?.children ?? [];
const joinedSubRooms = subRooms.filter(
(subRoomId) => !processedSubRooms.has(subRoomId) && mx.getRoom(subRoomId)
(subRoomId) => !processedSubRooms.has(subRoomId) && mx.getRoom(subRoomId),
);
joinedSubRooms.forEach((subRoomId, index) => {
@@ -434,7 +451,7 @@ export function Space() {
if (isSpaceEntry || (room && isSpace(room))) {
startSection(
entry.roomId,
entry.roomId === space.roomId ? 'Rooms' : room?.name ?? entry.roomId
entry.roomId === space.roomId ? 'Rooms' : (room?.name ?? entry.roomId),
);
return;
}
@@ -453,7 +470,7 @@ export function Space() {
}, [mx, filteredHierarchy, space.roomId]);
const handleCategoryClick = useCategoryHandler(setClosedCategories, (categoryId) =>
closedCategories.has(categoryId)
closedCategories.has(categoryId),
);
const getToLink = (roomId: string) =>
+1 -1
View File
@@ -7,7 +7,7 @@ export const getRoomSearchParams: SearchParamsGetter<_RoomSearchParams> = (searc
});
export const getDirectCreateSearchParams: SearchParamsGetter<DirectCreateSearchParams> = (
searchParams
searchParams,
) => ({
userId: searchParams.get('userId') ?? undefined,
});
+3 -3
View File
@@ -1,4 +1,5 @@
import { generatePath, Path } from 'react-router-dom';
import type { MatrixClient } from 'matrix-js-sdk';
import {
DIRECT_CREATE_PATH,
DIRECT_PATH,
@@ -31,7 +32,6 @@ import {
import { trimLeadingSlash, trimTrailingSlash } from '../utils/common';
import { tryDecodeURIComponent } from '../utils/dom';
import { HashRouterConfig } from '../hooks/useClientConfig';
import type { MatrixClient } from 'matrix-js-sdk';
import { getCanonicalAliasOrRoomId } from '../utils/matrix';
import { shouldShowForumLobby } from '../utils/room';
@@ -39,7 +39,7 @@ export const joinPathComponent = (path: Path): string => path.pathname + path.se
export const withSearchParam = <T extends Record<string, string>>(
path: string,
searchParam: T
searchParam: T,
): string => {
const params = new URLSearchParams(searchParam);
@@ -171,7 +171,7 @@ export const getSpaceSearchPath = (spaceIdOrAlias: string): string => {
export const getSpaceRoomPath = (
spaceIdOrAlias: string,
roomIdOrAlias: string,
eventId?: string
eventId?: string,
): string => {
const params = {
spaceIdOrAlias,