mirror of
https://github.com/SableClient/Sable.git
synced 2026-11-21 17:41:25 -08:00
Feat/tauri desktop (#1103)
<!-- Please read https://github.com/SableClient/Sable/blob/dev/CONTRIBUTING.md before submitting your pull request --> ### Description <!-- Please include a summary of the change. Please also include relevant motivation and context. List any dependencies that are required for this change. --> Fixes # #### Type of change - [ ] Bug fix (non-breaking change which fixes an issue) - [x] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected) - [ ] This change requires a documentation update ### Checklist: - [x] My code follows the style guidelines of this project - [ ] I have performed a self-review of my own code - [ ] I have commented my code, particularly in hard-to-understand areas - [ ] I have made corresponding changes to the documentation - [ ] My changes generate no new warnings ### AI disclosure: - [ ] Partially AI assisted (clarify which code was AI assisted and briefly explain what it does). - [ ] Fully AI generated (explain what all the generated code does in moderate detail). <!-- Write any explanation required here, but do not generate the explanation using AI!! You must prove you understand what the code in this PR does. -->
This commit is contained in:
356 files changed
+25422
-1132
No files matched your search
@@ -7,6 +7,7 @@ import { useAutoDiscoveryInfo } from '$hooks/useAutoDiscoveryInfo';
|
||||
import { promiseFulfilledResult, promiseRejectedResult } from '$utils/common';
|
||||
import type { AuthFlows, RegisterFlowsResponse } from '$hooks/useAuthFlows';
|
||||
import { RegisterFlowStatus, parseRegisterErrResp } from '$hooks/useAuthFlows';
|
||||
import { fetch } from '$utils/fetch';
|
||||
|
||||
type AuthFlowsLoaderProps = {
|
||||
fallback?: () => ReactNode;
|
||||
@@ -17,7 +18,7 @@ export function AuthFlowsLoader({ fallback, error, children }: AuthFlowsLoaderPr
|
||||
const autoDiscoveryInfo = useAutoDiscoveryInfo();
|
||||
const baseUrl = autoDiscoveryInfo['m.homeserver'].base_url;
|
||||
|
||||
const mx = useMemo(() => createClient({ baseUrl }), [baseUrl]);
|
||||
const mx = useMemo(() => createClient({ baseUrl, fetchFn: fetch }), [baseUrl]);
|
||||
|
||||
const [state, load] = useAsyncCallback(
|
||||
useCallback(async () => {
|
||||
|
||||
@@ -2,24 +2,9 @@ import type { ReactNode } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import { useSetAtom } from 'jotai';
|
||||
import { matchPath, useLocation, useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
getDirectPath,
|
||||
getExplorePath,
|
||||
getHomePath,
|
||||
getInboxPath,
|
||||
getSpacePath,
|
||||
} from '$pages/pathUtils';
|
||||
import {
|
||||
DIRECT_PATH,
|
||||
EXPLORE_PATH,
|
||||
HOME_PATH,
|
||||
INBOX_PATH,
|
||||
SPACE_PATH,
|
||||
HOME_ROOM_PATH,
|
||||
DIRECT_ROOM_PATH,
|
||||
SPACE_ROOM_PATH,
|
||||
} from '$pages/paths';
|
||||
import { lastVisitedRoomIdAtom } from '$state/room/lastRoom';
|
||||
import { resolveSection } from '$pages/pathUtils';
|
||||
import { HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH } from '$pages/paths';
|
||||
import { lastVisitedRoomAtom } from '$state/room/lastRoom';
|
||||
|
||||
type BackRouteHandlerProps = {
|
||||
children: (onBack: () => void) => ReactNode;
|
||||
@@ -27,88 +12,27 @@ type BackRouteHandlerProps = {
|
||||
export function BackRouteHandler({ children }: BackRouteHandlerProps) {
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const setLastRoomId = useSetAtom(lastVisitedRoomIdAtom);
|
||||
const setLastRoom = useSetAtom(lastVisitedRoomAtom);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
const roomPaths = [HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH];
|
||||
const section = resolveSection(location.pathname);
|
||||
if (!section) return;
|
||||
|
||||
const roomPaths = [HOME_ROOM_PATH, DIRECT_ROOM_PATH, SPACE_ROOM_PATH];
|
||||
const roomMatch = roomPaths
|
||||
.map((path) => matchPath({ path, end: false }, location.pathname))
|
||||
.find((match) => match !== null);
|
||||
|
||||
const currentRoomIdOrAlias = roomMatch?.params.roomIdOrAlias;
|
||||
if (currentRoomIdOrAlias) {
|
||||
setLastRoomId(decodeURIComponent(currentRoomIdOrAlias));
|
||||
if (section.getRoomPath && currentRoomIdOrAlias) {
|
||||
setLastRoom({
|
||||
section: section.key,
|
||||
roomId: decodeURIComponent(currentRoomIdOrAlias),
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
matchPath(
|
||||
{
|
||||
path: HOME_PATH,
|
||||
caseSensitive: true,
|
||||
end: false,
|
||||
},
|
||||
location.pathname
|
||||
)
|
||||
) {
|
||||
navigate(getHomePath());
|
||||
return;
|
||||
}
|
||||
if (
|
||||
matchPath(
|
||||
{
|
||||
path: DIRECT_PATH,
|
||||
caseSensitive: true,
|
||||
end: false,
|
||||
},
|
||||
location.pathname
|
||||
)
|
||||
) {
|
||||
navigate(getDirectPath());
|
||||
return;
|
||||
}
|
||||
const spaceMatch = matchPath(
|
||||
{
|
||||
path: SPACE_PATH,
|
||||
caseSensitive: true,
|
||||
end: false,
|
||||
},
|
||||
location.pathname
|
||||
);
|
||||
const encodedSpaceIdOrAlias = spaceMatch?.params.spaceIdOrAlias;
|
||||
const decodedSpaceIdOrAlias =
|
||||
encodedSpaceIdOrAlias && decodeURIComponent(encodedSpaceIdOrAlias);
|
||||
|
||||
if (decodedSpaceIdOrAlias) {
|
||||
navigate(getSpacePath(decodedSpaceIdOrAlias));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
matchPath(
|
||||
{
|
||||
path: EXPLORE_PATH,
|
||||
caseSensitive: true,
|
||||
end: false,
|
||||
},
|
||||
location.pathname
|
||||
)
|
||||
) {
|
||||
navigate(getExplorePath());
|
||||
return;
|
||||
}
|
||||
if (
|
||||
matchPath(
|
||||
{
|
||||
path: INBOX_PATH,
|
||||
caseSensitive: true,
|
||||
end: false,
|
||||
},
|
||||
location.pathname
|
||||
)
|
||||
) {
|
||||
navigate(getInboxPath());
|
||||
}
|
||||
}, [navigate, location, setLastRoomId]);
|
||||
navigate(section.listPath);
|
||||
}, [navigate, location, setLastRoom]);
|
||||
|
||||
return children(goBack);
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { Box, Button, Dialog, Text, color, config } from 'folds';
|
||||
import type { ClientConfig } from '$hooks/useClientConfig';
|
||||
import { trimTrailingSlash } from '$utils/common';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import { SplashScreen } from '$components/splash-screen';
|
||||
|
||||
export const FALLBACK_CLIENT_CONFIG: ClientConfig = {
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { FormEventHandler } from 'react';
|
||||
import { forwardRef, useCallback, useState } from 'react';
|
||||
import { Dialog, Header, Box, Text, IconButton, config, Button, Chip, color, Spinner } from 'folds';
|
||||
import { composerIcon, X } from '$components/icons/phosphor';
|
||||
import FileSaver from 'file-saver';
|
||||
import { saveFileToDevice } from '$utils/download';
|
||||
import to from 'await-to-js';
|
||||
import type { AuthDict, IAuthData, UIAuthCallback, UIAFlow } from '$types/matrix-sdk';
|
||||
import { MatrixError } from '$types/matrix-sdk';
|
||||
@@ -258,7 +258,7 @@ function RecoveryKeyDisplay({ recoveryKey }: Readonly<RecoveryKeyDisplayProps>)
|
||||
const blob = new Blob([recoveryKey], {
|
||||
type: 'text/plain;charset=us-ascii',
|
||||
});
|
||||
FileSaver.saveAs(blob, 'recovery-key.txt');
|
||||
void saveFileToDevice(blob, 'recovery-key.txt');
|
||||
};
|
||||
|
||||
const safeToDisplayKey = show ? recoveryKey : recoveryKey.replaceAll(/[^\s]/g, '*');
|
||||
|
||||
@@ -28,8 +28,7 @@ import {
|
||||
sizedIcon,
|
||||
} from '$components/icons/phosphor';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import FileSaver from 'file-saver';
|
||||
import { getDownloadFilename } from '$utils/download';
|
||||
import { getDownloadFilename, saveFileToDevice } from '$utils/download';
|
||||
import { AsyncStatus } from '$hooks/useAsyncCallback';
|
||||
import { useImageGestures } from '$hooks/useImageGestures';
|
||||
import { createPage, usePdfDocumentLoader, usePdfJSLoader } from '$plugins/pdfjs-dist';
|
||||
@@ -62,8 +61,11 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
||||
);
|
||||
const isLoading =
|
||||
pdfJSState.status === AsyncStatus.Loading || docState.status === AsyncStatus.Loading;
|
||||
const [renderError, setRenderError] = useState(false);
|
||||
const isError =
|
||||
pdfJSState.status === AsyncStatus.Error || docState.status === AsyncStatus.Error;
|
||||
pdfJSState.status === AsyncStatus.Error ||
|
||||
docState.status === AsyncStatus.Error ||
|
||||
renderError;
|
||||
const [pageNo, setPageNo] = useState(1);
|
||||
const [jumpAnchor, setJumpAnchor] = useState<RectCords>();
|
||||
|
||||
@@ -77,21 +79,30 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
||||
}, [pdfJSState, loadPdfDocument]);
|
||||
|
||||
useEffect(() => {
|
||||
if (docState.status === AsyncStatus.Success) {
|
||||
const doc = docState.data;
|
||||
if (pageNo < 0 || pageNo > doc.numPages) return;
|
||||
createPage(doc, pageNo, { scale: zoom }).then((canvas) => {
|
||||
if (docState.status !== AsyncStatus.Success) return undefined;
|
||||
const doc = docState.data;
|
||||
if (pageNo < 0 || pageNo > doc.numPages) return undefined;
|
||||
let cancelled = false;
|
||||
setRenderError(false);
|
||||
createPage(doc, pageNo, { scale: zoom })
|
||||
.then((canvas) => {
|
||||
if (cancelled) return;
|
||||
const container = containerRef.current;
|
||||
if (!container) return;
|
||||
container.textContent = '';
|
||||
container.append(canvas);
|
||||
canvas.style.touchAction = 'pan-x pan-y';
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) setRenderError(true);
|
||||
});
|
||||
}
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [docState, pageNo, zoom]);
|
||||
|
||||
const handleDownload = () => {
|
||||
FileSaver.saveAs(src, getDownloadFilename(name, undefined, 'document.pdf'));
|
||||
void saveFileToDevice(src, getDownloadFilename(name, undefined, 'document.pdf'));
|
||||
};
|
||||
|
||||
const handleJumpSubmit: FormEventHandler<HTMLFormElement> = (evt) => {
|
||||
@@ -186,7 +197,7 @@ export const PdfViewer = as<'div', PdfViewerProps>(
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
{docState.status === AsyncStatus.Success && (
|
||||
{docState.status === AsyncStatus.Success && !renderError && (
|
||||
<Scroll
|
||||
ref={scrollRef}
|
||||
size="300"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import type { SpecVersions } from '../cs-api';
|
||||
import { specVersions } from '../cs-api';
|
||||
|
||||
|
||||
@@ -1,62 +1,60 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { motion, useMotionValue, useSpring } from 'framer-motion';
|
||||
import { animate, motion, useMotionValue } from 'framer-motion';
|
||||
import { useDrag } from '@use-gesture/react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom, RightSwipeAction } from '$state/settings';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
|
||||
interface SwipeableChatWrapperProps {
|
||||
children: ReactNode;
|
||||
onOpenSidebar?: () => void;
|
||||
onOpenMembers?: () => void;
|
||||
onReply?: () => void;
|
||||
}
|
||||
|
||||
export function SwipeableChatWrapper({
|
||||
children,
|
||||
onOpenSidebar,
|
||||
onOpenMembers,
|
||||
onReply,
|
||||
}: SwipeableChatWrapperProps) {
|
||||
const settings = useAtomValue(settingsAtom);
|
||||
const [mobileGestures] = useSetting(settingsAtom, 'mobileGestures');
|
||||
const [rightSwipeAction] = useSetting(settingsAtom, 'rightSwipeAction');
|
||||
const x = useMotionValue(0);
|
||||
const springX = useSpring(x, { stiffness: 400, damping: 40 });
|
||||
|
||||
const bind = useDrag(
|
||||
({ active, movement: [mx], velocity: [vx], direction: [dx], event: e }) => {
|
||||
({ first, active, offset: [ox], velocity: [vx], direction: [dx], event: e }) => {
|
||||
if (e && 'target' in e && e.target instanceof HTMLElement) {
|
||||
if (e.target.closest('[data-gestures="ignore"]')) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!settings.mobileGestures || !mobileOrTablet()) return;
|
||||
if (!mobileGestures || !mobileOrTablet()) return;
|
||||
|
||||
let val = mx;
|
||||
let val = ox;
|
||||
|
||||
const canSwipeRight = !!onOpenSidebar;
|
||||
const canSwipeLeft =
|
||||
settings.rightSwipeAction === RightSwipeAction.Members ? !!onOpenMembers : !!onReply;
|
||||
rightSwipeAction === RightSwipeAction.Members ? !!onOpenMembers : !!onReply;
|
||||
|
||||
if (!canSwipeRight && val > 0) val = 0;
|
||||
// The drawer owns the rightward reveal; this wrapper only handles leftward actions.
|
||||
if (val > 0) val = 0;
|
||||
if (!canSwipeLeft && val < 0) val = 0;
|
||||
|
||||
if (active) {
|
||||
// Take over any settling spring; offset is seeded from the live position.
|
||||
if (first) x.stop();
|
||||
x.set(val);
|
||||
} else {
|
||||
const swipeThreshold = 120;
|
||||
const velocityThreshold = 0.5;
|
||||
|
||||
if (val > swipeThreshold || (vx > velocityThreshold && dx > 0 && val > 0)) {
|
||||
onOpenSidebar?.();
|
||||
} else if (val < -swipeThreshold || (vx > velocityThreshold && dx < 0 && val < 0)) {
|
||||
if (settings.rightSwipeAction === RightSwipeAction.Members) {
|
||||
if (val < -swipeThreshold || (vx > velocityThreshold && dx < 0 && val < 0)) {
|
||||
if (rightSwipeAction === RightSwipeAction.Members) {
|
||||
onOpenMembers?.();
|
||||
} else {
|
||||
onReply?.();
|
||||
}
|
||||
}
|
||||
x.set(0);
|
||||
animate(x, 0, { type: 'spring', stiffness: 400, damping: 40 });
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -64,10 +62,12 @@ export function SwipeableChatWrapper({
|
||||
bounds: { left: -200, right: 200 },
|
||||
rubberband: true,
|
||||
filterTaps: true,
|
||||
pointer: { capture: false },
|
||||
from: () => [x.get(), 0],
|
||||
}
|
||||
);
|
||||
|
||||
if (!settings.mobileGestures || !mobileOrTablet()) {
|
||||
if (!mobileGestures || !mobileOrTablet()) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -98,7 +98,7 @@ export function SwipeableChatWrapper({
|
||||
>
|
||||
<motion.div
|
||||
style={{
|
||||
x: springX,
|
||||
x,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flexGrow: 1,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { motion, useMotionValue, useSpring } from 'framer-motion';
|
||||
import { animate, motion, useMotionValue } from 'framer-motion';
|
||||
import { useDrag } from '@use-gesture/react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { mobileOrTablet } from '$utils/user-agent';
|
||||
|
||||
@@ -16,28 +16,29 @@ export function SwipeableOverlayWrapper({
|
||||
onClose,
|
||||
direction,
|
||||
}: SwipeableOverlayWrapperProps) {
|
||||
const settings = useAtomValue(settingsAtom);
|
||||
const [mobileGestures] = useSetting(settingsAtom, 'mobileGestures');
|
||||
const x = useMotionValue(0);
|
||||
const springX = useSpring(x, { stiffness: 400, damping: 40 });
|
||||
|
||||
const bind = useDrag(
|
||||
({ active, movement: [mx], velocity: [vx], direction: [dx], event, event: e }) => {
|
||||
if (e && 'target' in e && e.target instanceof HTMLElement) {
|
||||
if (e.target.closest('[data-gestures="ignore"]')) {
|
||||
({ first, active, offset: [ox], velocity: [vx], direction: [dx], event }) => {
|
||||
if (event && 'target' in event && event.target instanceof HTMLElement) {
|
||||
if (event.target.closest('[data-gestures="ignore"]')) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!settings.mobileGestures || !mobileOrTablet()) return;
|
||||
if (!mobileGestures || !mobileOrTablet()) return;
|
||||
|
||||
event.stopPropagation();
|
||||
|
||||
let val = mx;
|
||||
let val = ox;
|
||||
|
||||
if (direction === 'left' && val > 0) val = 0;
|
||||
if (direction === 'right' && val < 0) val = 0;
|
||||
|
||||
if (active) {
|
||||
// Take over any settling spring; offset is seeded from the live position.
|
||||
if (first) x.stop();
|
||||
x.set(val);
|
||||
} else {
|
||||
const swipeThreshold = 100;
|
||||
@@ -52,7 +53,7 @@ export function SwipeableOverlayWrapper({
|
||||
onClose();
|
||||
}
|
||||
|
||||
x.set(0);
|
||||
animate(x, 0, { type: 'spring', stiffness: 400, damping: 40 });
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -61,10 +62,11 @@ export function SwipeableOverlayWrapper({
|
||||
rubberband: true,
|
||||
filterTaps: true,
|
||||
pointer: { capture: true },
|
||||
from: () => [x.get(), 0],
|
||||
}
|
||||
);
|
||||
|
||||
if (!settings.mobileGestures || !mobileOrTablet()) {
|
||||
if (!mobileGestures || !mobileOrTablet()) {
|
||||
return (
|
||||
<div
|
||||
style={{
|
||||
@@ -95,7 +97,7 @@ export function SwipeableOverlayWrapper({
|
||||
>
|
||||
<motion.div
|
||||
style={{
|
||||
x: springX,
|
||||
x,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
flexGrow: 1,
|
||||
|
||||
@@ -0,0 +1,162 @@
|
||||
import classNames from 'classnames';
|
||||
import { Box, config, Line, Text } from 'folds';
|
||||
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
|
||||
import { SyncState } from '$types/matrix-sdk';
|
||||
import { type TitlebarStatusView } from '$state/titlebarStatus';
|
||||
import { ContainerColor } from '$styles/ContainerColor.css';
|
||||
|
||||
const TITLEBAR_EASE_OUT: [number, number, number, number] = [0.32, 0.72, 0, 1];
|
||||
const TITLEBAR_EASE_OUT_SOFT: [number, number, number, number] = [0.24, 0.72, 0.08, 1];
|
||||
|
||||
type SyncConnectionStatusProps = {
|
||||
status: TitlebarStatusView | null;
|
||||
};
|
||||
|
||||
export function getSyncConnectionStatusView(
|
||||
current: SyncState | null,
|
||||
previous: SyncState | null | undefined
|
||||
): TitlebarStatusView | null {
|
||||
if (
|
||||
(current === SyncState.Prepared ||
|
||||
current === SyncState.Syncing ||
|
||||
current === SyncState.Catchup) &&
|
||||
previous !== SyncState.Syncing
|
||||
) {
|
||||
return { text: 'Connecting...', variant: 'Success' };
|
||||
}
|
||||
|
||||
if (current === SyncState.Reconnecting) {
|
||||
return { text: 'Connection Lost! Reconnecting...', variant: 'Warning' };
|
||||
}
|
||||
|
||||
if (current === SyncState.Error) {
|
||||
return { text: 'Connection Lost!', variant: 'Critical' };
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function SyncConnectionStatusBanner({ status }: SyncConnectionStatusProps) {
|
||||
if (!status) return null;
|
||||
|
||||
return (
|
||||
<Box direction="Column" shrink="No">
|
||||
<Box
|
||||
className={ContainerColor({ variant: status.variant })}
|
||||
style={{ padding: `${config.space.S100} 0` }}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
>
|
||||
<Text size="L400">{status.text}</Text>
|
||||
</Box>
|
||||
<Line variant={status.variant} size="300" />
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
export function SyncConnectionStatusTitlebar({ status }: SyncConnectionStatusProps) {
|
||||
const shouldReduceMotion = useReducedMotion();
|
||||
const pillVariants = shouldReduceMotion
|
||||
? {
|
||||
hidden: { opacity: 0 },
|
||||
visible: {
|
||||
opacity: 1,
|
||||
transition: { duration: 0.18, ease: TITLEBAR_EASE_OUT },
|
||||
},
|
||||
exit: {
|
||||
opacity: 0,
|
||||
transition: {
|
||||
when: 'afterChildren' as const,
|
||||
opacity: { duration: 0.1, delay: 0.08, ease: TITLEBAR_EASE_OUT_SOFT },
|
||||
},
|
||||
},
|
||||
}
|
||||
: {
|
||||
hidden: {
|
||||
y: -2,
|
||||
scaleX: 0.98,
|
||||
scaleY: 0.96,
|
||||
opacity: 0,
|
||||
clipPath: 'inset(0 50% 0 50% round 999px)',
|
||||
},
|
||||
visible: {
|
||||
y: 0,
|
||||
scaleX: 1,
|
||||
scaleY: 1,
|
||||
opacity: 1,
|
||||
clipPath: 'inset(0 0% 0 0% round 999px)',
|
||||
transition: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
|
||||
},
|
||||
exit: {
|
||||
y: -2,
|
||||
scaleX: 0.98,
|
||||
scaleY: 0.96,
|
||||
opacity: 0,
|
||||
clipPath: 'inset(0 50% 0 50% round 999px)',
|
||||
transition: {
|
||||
when: 'afterChildren' as const,
|
||||
y: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
|
||||
scaleX: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
|
||||
scaleY: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
|
||||
clipPath: { duration: 0.2, ease: TITLEBAR_EASE_OUT },
|
||||
opacity: { duration: 0.1, delay: 0.08, ease: TITLEBAR_EASE_OUT_SOFT },
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
const textVariants = shouldReduceMotion
|
||||
? {
|
||||
hidden: { opacity: 0 },
|
||||
visible: {
|
||||
opacity: 1,
|
||||
transition: { duration: 0.12, ease: TITLEBAR_EASE_OUT },
|
||||
},
|
||||
exit: {
|
||||
opacity: 0,
|
||||
transition: { duration: 0.1, ease: TITLEBAR_EASE_OUT_SOFT },
|
||||
},
|
||||
}
|
||||
: {
|
||||
hidden: { opacity: 0 },
|
||||
visible: {
|
||||
opacity: 1,
|
||||
transition: { duration: 0.12, delay: 0.04, ease: TITLEBAR_EASE_OUT_SOFT },
|
||||
},
|
||||
exit: {
|
||||
opacity: 0,
|
||||
transition: { duration: 0.1, ease: TITLEBAR_EASE_OUT_SOFT },
|
||||
},
|
||||
};
|
||||
|
||||
return (
|
||||
<AnimatePresence mode="sync" initial={false}>
|
||||
{status && (
|
||||
<motion.span
|
||||
key={`${status.variant}-${status.text}`}
|
||||
className={classNames(
|
||||
'tauri-titlebar-status__label',
|
||||
status.variant === 'Success' && 'tauri-titlebar-status__label--success',
|
||||
status.variant === 'Warning' && 'tauri-titlebar-status__label--warning',
|
||||
status.variant === 'Critical' && 'tauri-titlebar-status__label--critical'
|
||||
)}
|
||||
style={{
|
||||
transformOrigin: 'center top',
|
||||
willChange: shouldReduceMotion ? 'opacity' : 'transform, opacity, clip-path',
|
||||
}}
|
||||
variants={pillVariants}
|
||||
initial="hidden"
|
||||
animate="visible"
|
||||
exit="exit"
|
||||
>
|
||||
<motion.span
|
||||
className="tauri-titlebar-status__text"
|
||||
style={{ willChange: 'opacity' }}
|
||||
variants={textVariants}
|
||||
>
|
||||
{status.text}
|
||||
</motion.span>
|
||||
</motion.span>
|
||||
)}
|
||||
</AnimatePresence>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { type ReactNode, Suspense, lazy, useState } from 'react';
|
||||
import { Provider as JotaiProvider } from 'jotai';
|
||||
import { OverlayContainerProvider, PopOutContainerProvider, TooltipContainerProvider } from 'folds';
|
||||
import { QueryClientProvider } from '@tanstack/react-query';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
|
||||
import { TauriFrontendReady } from '$components/tauri/TauriFrontendReady';
|
||||
import { WindowsTitleBar } from '$components/tauri/WindowsTitleBar';
|
||||
import { Toast } from '$components/toast/Toast';
|
||||
import type { ScreenSize } from '$hooks/useScreenSize';
|
||||
import { ScreenSizeProvider } from '$hooks/useScreenSize';
|
||||
import { isReactQueryDevtoolsEnabled } from '$pages/reactQueryDevtoolsGate';
|
||||
import { SystemBarShell } from './SystemBarShell';
|
||||
|
||||
const ReactQueryDevtools = lazy(async () => {
|
||||
const { ReactQueryDevtools: Devtools } = await import('@tanstack/react-query-devtools');
|
||||
|
||||
return { default: Devtools };
|
||||
});
|
||||
|
||||
type AppShellProps = {
|
||||
children: ReactNode;
|
||||
queryClient: Parameters<typeof QueryClientProvider>[0]['client'];
|
||||
screenSize: ScreenSize;
|
||||
};
|
||||
|
||||
export function AppShell({ children, queryClient, screenSize }: AppShellProps) {
|
||||
const tauriOs = isTauri() ? osType() : undefined;
|
||||
const useCustomWindowsTitleBar = tauriOs === 'windows';
|
||||
const reactQueryDevtoolsEnabled = isReactQueryDevtoolsEnabled();
|
||||
const contentHeight = useCustomWindowsTitleBar
|
||||
? 'calc(100% - var(--tauri-titlebar-height))'
|
||||
: '100%';
|
||||
const [portalContainer, setPortalContainer] = useState<HTMLDivElement | null>(null);
|
||||
|
||||
return (
|
||||
<TooltipContainerProvider value={portalContainer ?? undefined}>
|
||||
<PopOutContainerProvider value={portalContainer ?? undefined}>
|
||||
<OverlayContainerProvider value={portalContainer ?? undefined}>
|
||||
<ScreenSizeProvider value={screenSize}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<JotaiProvider>
|
||||
<TauriFrontendReady />
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
width: '100%',
|
||||
minHeight: 0,
|
||||
overflow: 'hidden',
|
||||
height: '100%',
|
||||
}}
|
||||
>
|
||||
{useCustomWindowsTitleBar && <WindowsTitleBar />}
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
width: '100%',
|
||||
minHeight: 0,
|
||||
height: contentHeight,
|
||||
}}
|
||||
>
|
||||
<SystemBarShell onPortalContainerChange={setPortalContainer}>
|
||||
{children}
|
||||
</SystemBarShell>
|
||||
<Toast container={portalContainer} />
|
||||
</div>
|
||||
</div>
|
||||
</JotaiProvider>
|
||||
{reactQueryDevtoolsEnabled && (
|
||||
<Suspense fallback={null}>
|
||||
<ReactQueryDevtools initialIsOpen={false} />
|
||||
</Suspense>
|
||||
)}
|
||||
</QueryClientProvider>
|
||||
</ScreenSizeProvider>
|
||||
</OverlayContainerProvider>
|
||||
</PopOutContainerProvider>
|
||||
</TooltipContainerProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { render } from '@testing-library/react';
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import { SystemBarShell } from './SystemBarShell';
|
||||
|
||||
const { mockIsTauri, mockOsType } = vi.hoisted(() => ({
|
||||
mockIsTauri: vi.fn<() => boolean>(),
|
||||
mockOsType: vi.fn<() => string>(),
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({
|
||||
invoke: vi.fn<() => Promise<void>>(),
|
||||
isTauri: mockIsTauri,
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/plugin-os', () => ({
|
||||
type: mockOsType,
|
||||
}));
|
||||
|
||||
describe('SystemBarShell', () => {
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('does not observe document mutations outside mobile Tauri', () => {
|
||||
mockIsTauri.mockReturnValue(false);
|
||||
const mutationObserver = vi.fn<() => void>();
|
||||
vi.stubGlobal('MutationObserver', mutationObserver);
|
||||
|
||||
render(
|
||||
<SystemBarShell onPortalContainerChange={vi.fn<(node: HTMLDivElement | null) => void>()}>
|
||||
<div>Content</div>
|
||||
</SystemBarShell>
|
||||
);
|
||||
|
||||
expect(mockOsType).not.toHaveBeenCalled();
|
||||
expect(mutationObserver).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
import { type ReactNode, type RefObject, useEffect, useRef, useState } from 'react';
|
||||
import { invoke, isTauri } from '@tauri-apps/api/core';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
import { updateThemeColorMeta } from '../../theme/themeColorMeta';
|
||||
|
||||
const safeAreaTop = 'var(--safe-area-inset-top, env(safe-area-inset-top, 0px))';
|
||||
const safeAreaBottom = 'var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px))';
|
||||
const iosBottomInset = `max(${safeAreaBottom}, var(--keyboard-height, 0px))`;
|
||||
const safeAreaLeft = 'var(--safe-area-inset-left, env(safe-area-inset-left, 0px))';
|
||||
const safeAreaRight = 'var(--safe-area-inset-right, env(safe-area-inset-right, 0px))';
|
||||
|
||||
const TRANSPARENT = /^(transparent$|rgba?\(\s*0\s*,\s*0\s*,\s*0\s*,\s*0\s*\))/;
|
||||
|
||||
// First non-transparent background color painted at (x, y).
|
||||
function readSurfaceColor(x: number, y: number): string | undefined {
|
||||
let el = document.elementFromPoint(x, y);
|
||||
while (el) {
|
||||
const bg = getComputedStyle(el).backgroundColor;
|
||||
if (bg && !TRANSPARENT.test(bg)) return bg;
|
||||
el = el.parentElement;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// "rgb(r, g, b)" -> packed ARGB int for the native Android status bar.
|
||||
function rgbToArgb(color: string): number | undefined {
|
||||
const parts = color.match(/\d+/g);
|
||||
if (!parts || parts.length < 3) return undefined;
|
||||
const [r, g, b] = parts.map((part) => parseInt(part, 10));
|
||||
if (r === undefined || g === undefined || b === undefined) return undefined;
|
||||
return ((0xff << 24) | (r << 16) | (g << 8) | b) >>> 0;
|
||||
}
|
||||
|
||||
// Color of the surface adjacent to a strip; on Android also tints the native system bar.
|
||||
function useBarColor(
|
||||
probeRef: RefObject<HTMLDivElement>,
|
||||
edge: 'top' | 'bottom',
|
||||
android: boolean,
|
||||
enabled: boolean
|
||||
): string | undefined {
|
||||
const [color, setColor] = useState<string>();
|
||||
const lastRef = useRef<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled) return undefined;
|
||||
|
||||
let frame = 0;
|
||||
let timer = 0;
|
||||
const sample = () => {
|
||||
frame = 0;
|
||||
const rect = probeRef.current?.getBoundingClientRect();
|
||||
const x = Math.round(rect ? rect.left + rect.width / 2 : window.innerWidth / 2);
|
||||
const y =
|
||||
edge === 'top'
|
||||
? Math.round((rect?.bottom ?? 0) + 1)
|
||||
: Math.round((rect?.top ?? window.innerHeight) - 1);
|
||||
const next = readSurfaceColor(x, y);
|
||||
if (next && next !== lastRef.current) {
|
||||
lastRef.current = next;
|
||||
setColor(next);
|
||||
if (edge === 'top') updateThemeColorMeta(next);
|
||||
if (android) {
|
||||
const argb = rgbToArgb(next);
|
||||
const command = edge === 'top' ? 'set_status_bar_color' : 'set_navigation_bar_color';
|
||||
if (argb !== undefined) invoke(command, { color: argb }).catch(() => {});
|
||||
}
|
||||
}
|
||||
};
|
||||
const runSample = () => {
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
frame = requestAnimationFrame(sample);
|
||||
};
|
||||
const schedule = () => {
|
||||
window.clearTimeout(timer);
|
||||
timer = window.setTimeout(runSample, 120);
|
||||
};
|
||||
|
||||
runSample();
|
||||
const observer = new MutationObserver(schedule);
|
||||
// childList = navigation; class/style = theme swaps and per-view recolors.
|
||||
observer.observe(document.body, {
|
||||
subtree: true,
|
||||
childList: true,
|
||||
attributes: true,
|
||||
attributeFilter: ['class', 'style'],
|
||||
});
|
||||
observer.observe(document.head, { childList: true }); // remote-theme css
|
||||
window.addEventListener('resize', schedule);
|
||||
|
||||
return () => {
|
||||
window.clearTimeout(timer);
|
||||
if (frame) cancelAnimationFrame(frame);
|
||||
observer.disconnect();
|
||||
window.removeEventListener('resize', schedule);
|
||||
};
|
||||
}, [probeRef, edge, android, enabled]);
|
||||
|
||||
return color;
|
||||
}
|
||||
|
||||
type SystemBarStripProps = {
|
||||
size: string;
|
||||
background: string;
|
||||
stripRef?: RefObject<HTMLDivElement>;
|
||||
transition?: string;
|
||||
};
|
||||
|
||||
function SystemBarStrip({ size, background, stripRef, transition }: SystemBarStripProps) {
|
||||
return (
|
||||
<div
|
||||
ref={stripRef}
|
||||
style={{
|
||||
height: size,
|
||||
flexShrink: 0,
|
||||
overflow: 'hidden',
|
||||
transition,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
background,
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type SystemBarShellProps = {
|
||||
children: ReactNode;
|
||||
onPortalContainerChange: (node: HTMLDivElement | null) => void;
|
||||
};
|
||||
|
||||
export function SystemBarShell({ children, onPortalContainerChange }: SystemBarShellProps) {
|
||||
const tauriOs = isTauri() ? osType() : undefined;
|
||||
const enabled = tauriOs === 'android' || tauriOs === 'ios';
|
||||
|
||||
const topStripRef = useRef<HTMLDivElement>(null);
|
||||
const bottomStripRef = useRef<HTMLDivElement>(null);
|
||||
const topColor = useBarColor(topStripRef, 'top', tauriOs === 'android', enabled);
|
||||
const bottomColor = useBarColor(bottomStripRef, 'bottom', tauriOs === 'android', enabled);
|
||||
|
||||
return (
|
||||
<>
|
||||
{enabled && (
|
||||
<SystemBarStrip
|
||||
size={safeAreaTop}
|
||||
background={topColor ?? 'var(--sable-bg-container)'}
|
||||
stripRef={topStripRef}
|
||||
/>
|
||||
)}
|
||||
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
width: '100%',
|
||||
minHeight: 0,
|
||||
flex: 1,
|
||||
paddingLeft: enabled ? safeAreaLeft : 0,
|
||||
paddingRight: enabled ? safeAreaRight : 0,
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
width: '100%',
|
||||
minHeight: 0,
|
||||
flex: 1,
|
||||
}}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
|
||||
<div id="portalContainer" ref={onPortalContainerChange} />
|
||||
</div>
|
||||
|
||||
{enabled && (
|
||||
<SystemBarStrip
|
||||
size={tauriOs === 'ios' ? iosBottomInset : safeAreaBottom}
|
||||
background={bottomColor ?? 'var(--sable-surface-container)'}
|
||||
stripRef={bottomStripRef}
|
||||
transition={tauriOs === 'ios' ? 'height 0.25s ease-out' : undefined}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { AppShell } from './AppShell';
|
||||
export { SystemBarShell } from './SystemBarShell';
|
||||
@@ -93,7 +93,7 @@ function RenderEmoticonElement({
|
||||
{element.key.startsWith('mxc://') ? (
|
||||
<img
|
||||
className={css.EmoticonImg}
|
||||
src={mxcUrlToHttp(mx, element.key, useAuthentication) ?? element.key}
|
||||
src={mxcUrlToHttp(mx, element.key, useAuthentication) ?? undefined}
|
||||
alt={element.shortcode}
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
|
||||
import { useEffect, useMemo } from 'react';
|
||||
import type { Editor } from 'slate';
|
||||
import { Box, MenuItem, Text, toRem } from 'folds';
|
||||
@@ -123,6 +123,7 @@ export function EmoticonAutocomplete({
|
||||
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||
onTabPress(evt, () => handleAutocomplete(key, emoticon.shortcode))
|
||||
}
|
||||
onMouseDown={(evt: ReactMouseEvent<HTMLButtonElement>) => evt.preventDefault()}
|
||||
onClick={() => handleAutocomplete(key, emoticon.shortcode)}
|
||||
before={
|
||||
isCustomEmoji && customEmojiUrl ? (
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
|
||||
import { useCallback, useEffect, useMemo } from 'react';
|
||||
import type { Editor } from 'slate';
|
||||
import { Avatar, MenuItem, Text } from 'folds';
|
||||
@@ -48,6 +48,7 @@ function UnknownRoomMentionItem({
|
||||
as="button"
|
||||
radii="300"
|
||||
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) => onTabPress(evt, handleSelect)}
|
||||
onMouseDown={(evt: ReactMouseEvent<HTMLButtonElement>) => evt.preventDefault()}
|
||||
onClick={handleSelect}
|
||||
before={<Avatar size="200">{sizedIcon(Hash, '100')}</Avatar>}
|
||||
>
|
||||
@@ -161,6 +162,7 @@ export function RoomMentionAutocomplete({
|
||||
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||
onTabPress(evt, handleSelect)
|
||||
}
|
||||
onMouseDown={(evt: ReactMouseEvent<HTMLButtonElement>) => evt.preventDefault()}
|
||||
onClick={handleSelect}
|
||||
after={
|
||||
<Text size="T200" priority="300" truncate>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import type { Editor } from 'slate';
|
||||
import { Avatar, MenuItem, Text } from 'folds';
|
||||
@@ -52,6 +52,7 @@ function UnknownMentionItem({
|
||||
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||
onTabPress(evt, () => handleAutocomplete(userId, name))
|
||||
}
|
||||
onMouseDown={(evt: ReactMouseEvent<HTMLButtonElement>) => evt.preventDefault()}
|
||||
onClick={() => handleAutocomplete(userId, name)}
|
||||
before={
|
||||
<Avatar size="200">
|
||||
@@ -185,6 +186,7 @@ export function UserMentionAutocomplete({
|
||||
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||
onTabPress(evt, () => handleAutocomplete(roomMember.userId, getName(roomMember)))
|
||||
}
|
||||
onMouseDown={(evt: ReactMouseEvent<HTMLButtonElement>) => evt.preventDefault()}
|
||||
onClick={() => handleAutocomplete(roomMember.userId, getName(roomMember))}
|
||||
after={
|
||||
<Text size="T200" priority="300" truncate>
|
||||
|
||||
@@ -22,6 +22,7 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useRecentEmoji } from '$hooks/useRecentEmoji';
|
||||
import { isUserId, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { editableActiveElement, targetFromEvent } from '$utils/dom';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import type { UseAsyncSearchOptions } from '$hooks/useAsyncSearch';
|
||||
import { useAsyncSearch } from '$hooks/useAsyncSearch';
|
||||
import { useDebounce } from '$hooks/useDebounce';
|
||||
|
||||
@@ -37,7 +37,7 @@ export function Preview({ previewAtom }: PreviewProps) {
|
||||
{key.startsWith('mxc://') ? (
|
||||
<img
|
||||
className={css.PreviewImg}
|
||||
src={mxcUrlToHttp(mx, key, useAuthentication) ?? key}
|
||||
src={mxcUrlToHttp(mx, key, useAuthentication) ?? undefined}
|
||||
alt={shortcode}
|
||||
/>
|
||||
) : (
|
||||
|
||||
@@ -42,7 +42,7 @@ export function ImageTile({
|
||||
before={
|
||||
<img
|
||||
className={css.ImagePackImage}
|
||||
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? ''}
|
||||
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? undefined}
|
||||
alt={image.shortcode}
|
||||
loading="lazy"
|
||||
/>
|
||||
@@ -166,7 +166,7 @@ export function ImageTileEdit({
|
||||
before={
|
||||
<img
|
||||
className={css.ImagePackImage}
|
||||
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? ''}
|
||||
src={mxcUrlToHttp(mx, image.url, useAuthentication) ?? undefined}
|
||||
alt={image.shortcode}
|
||||
loading="lazy"
|
||||
/>
|
||||
|
||||
@@ -24,6 +24,7 @@ import { useObjectURL } from '$hooks/useObjectURL';
|
||||
import type { UploadSuccess } from '$state/upload';
|
||||
import { createUploadAtom } from '$state/upload';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import { PackMetaReader } from '$plugins/custom-emoji';
|
||||
import { CompactUploadCardRenderer } from '$components/upload-card';
|
||||
|
||||
@@ -32,10 +33,11 @@ type ImagePackAvatarProps = {
|
||||
name?: string;
|
||||
};
|
||||
function ImagePackAvatar({ url, name }: ImagePackAvatarProps) {
|
||||
const resolvedUrl = useRenderableMediaUrl(url);
|
||||
return (
|
||||
<Avatar size="500" className={ContainerColor({ variant: 'Secondary' })}>
|
||||
{url ? (
|
||||
<AvatarImage src={url} alt={name ?? 'Unknown'} />
|
||||
<AvatarImage src={resolvedUrl ?? url} alt={name ?? 'Unknown'} />
|
||||
) : (
|
||||
<AvatarFallback>
|
||||
<Text size="H2">{nameInitials(name ?? 'Unknown')}</Text>
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { PointerEvent, SyntheticEvent, WheelEvent } from 'react';
|
||||
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import FileSaver from 'file-saver';
|
||||
import { ImageViewer } from './ImageViewer';
|
||||
|
||||
const downloadMedia = vi.fn<(src: string) => Promise<Blob>>();
|
||||
|
||||
vi.mock('$hooks/useImageGestures', () => ({
|
||||
useImageGestures: () => ({
|
||||
transforms: { zoom: 1, pan: { x: 0, y: 0 } },
|
||||
cursor: 'grab',
|
||||
fitRatio: 1,
|
||||
imageRef: { current: null },
|
||||
containerRef: { current: null },
|
||||
handleWheel: vi.fn<(event: WheelEvent) => void>(),
|
||||
onPointerDown: vi.fn<(event: PointerEvent) => void>(),
|
||||
handleImageLoad: vi.fn<(event: SyntheticEvent<HTMLImageElement>) => void>(),
|
||||
setZoom: vi.fn<(next: number) => void>(),
|
||||
resetTransforms: vi.fn<() => void>(),
|
||||
zoomIn: vi.fn<() => void>(),
|
||||
zoomOut: vi.fn<() => void>(),
|
||||
enableResizeWithWindow: vi.fn<() => void>(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('$utils/matrix', () => ({
|
||||
downloadMedia: (...args: [string]) => downloadMedia(...args),
|
||||
}));
|
||||
|
||||
vi.mock('file-saver', () => ({
|
||||
default: {
|
||||
saveAs: vi.fn<(data: Blob | string, filename?: string) => void>(),
|
||||
},
|
||||
}));
|
||||
|
||||
describe('ImageViewer', () => {
|
||||
it('downloads media without passing a media token argument', async () => {
|
||||
downloadMedia.mockResolvedValue(new Blob(['image']));
|
||||
|
||||
render(
|
||||
<ImageViewer
|
||||
alt="kitten.png"
|
||||
src="https://example.org/kitten.png"
|
||||
requestClose={vi.fn<() => void>()}
|
||||
/>
|
||||
);
|
||||
|
||||
fireEvent.click(screen.getByText('Download'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(downloadMedia).toHaveBeenCalledWith('https://example.org/kitten.png');
|
||||
});
|
||||
expect(FileSaver.saveAs).toHaveBeenCalledWith(expect.any(Blob), 'kitten.png');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,5 @@
|
||||
import type { MouseEventHandler } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import FileSaver from 'file-saver';
|
||||
import classNames from 'classnames';
|
||||
import {
|
||||
Box,
|
||||
@@ -37,7 +36,7 @@ import { CheckerboardIcon, CopyIcon, DownloadIcon } from '@phosphor-icons/react'
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { copyImageToClipboard } from '$utils/dom';
|
||||
import { getDownloadFilename } from '$utils/download';
|
||||
import { getDownloadFilename, saveFileToDevice } from '$utils/download';
|
||||
|
||||
export type ImageViewerProps = {
|
||||
alt: string;
|
||||
@@ -100,7 +99,7 @@ export const ImageViewer = as<'div', ImageViewerProps>(
|
||||
|
||||
const handleDownload = async () => {
|
||||
const fileContent = await downloadMedia(src);
|
||||
FileSaver.saveAs(fileContent, getDownloadFilename(filename, alt, 'image'));
|
||||
await saveFileToDevice(fileContent, getDownloadFilename(filename, alt, 'image'));
|
||||
};
|
||||
|
||||
const [menuAnchor, setMenuAnchor] = useState<RectCords>();
|
||||
|
||||
@@ -3,13 +3,12 @@ import { Download, sizedIcon } from '$components/icons/phosphor';
|
||||
import type { ReactNode } from 'react';
|
||||
import { useCallback } from 'react';
|
||||
import type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
|
||||
import FileSaver from 'file-saver';
|
||||
import { mimeTypeToExt } from '$utils/mimeTypes';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { getDownloadFilename } from '$utils/download';
|
||||
import { getDownloadFilename, saveFileToDevice } from '$utils/download';
|
||||
|
||||
const badgeStyles = { maxWidth: toRem(100) };
|
||||
|
||||
@@ -32,7 +31,7 @@ export function FileDownloadButton({ filename, url, mimeType, encInfo }: FileDow
|
||||
: await downloadMedia(mediaUrl);
|
||||
|
||||
const fileURL = URL.createObjectURL(fileContent);
|
||||
FileSaver.saveAs(fileURL, getDownloadFilename(filename));
|
||||
await saveFileToDevice(fileContent, getDownloadFilename(filename), mimeType);
|
||||
return fileURL;
|
||||
}, [mx, url, useAuthentication, mimeType, encInfo, filename])
|
||||
);
|
||||
|
||||
@@ -46,7 +46,7 @@ export const Reaction = as<
|
||||
return (
|
||||
<img
|
||||
className={css.ReactionImg}
|
||||
src={mxcUrlToHttp(mx, reaction, useAuthentication) ?? reaction}
|
||||
src={mxcUrlToHttp(mx, reaction, useAuthentication) ?? undefined}
|
||||
alt={reaction}
|
||||
onError={() => setImgError(true)}
|
||||
/>
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { menuIcon, Warning } from '$components/icons/phosphor';
|
||||
import { scaleSystemEmoji } from '$plugins/react-custom-html-parser';
|
||||
import { mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import * as css from './Reaction.css';
|
||||
|
||||
type ReactionKeyInlineProps = {
|
||||
@@ -20,6 +21,11 @@ export function ReactionKeyInline({
|
||||
useAuthentication,
|
||||
}: ReactionKeyInlineProps) {
|
||||
const [imgError, setImgError] = useState(false);
|
||||
const rawReactionUrl =
|
||||
reactionKey && reactionKey.startsWith('mxc://')
|
||||
? (mxcUrlToHttp(mx, reactionKey, useAuthentication) ?? undefined)
|
||||
: undefined;
|
||||
const renderableReactionUrl = useRenderableMediaUrl(rawReactionUrl);
|
||||
|
||||
if (!reactionKey) {
|
||||
if (shortcode) {
|
||||
@@ -44,7 +50,7 @@ export function ReactionKeyInline({
|
||||
return (
|
||||
<img
|
||||
className={css.ReactionImg}
|
||||
src={mxcUrlToHttp(mx, reactionKey, useAuthentication) ?? reactionKey}
|
||||
src={renderableReactionUrl}
|
||||
alt={shortcode ?? 'reaction'}
|
||||
onError={() => setImgError(true)}
|
||||
/>
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
as,
|
||||
} from 'folds';
|
||||
import { ArrowRight, Download, sizedIcon, Warning } from '$components/icons/phosphor';
|
||||
import FileSaver from 'file-saver';
|
||||
import type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
|
||||
import FocusTrap from 'focus-trap-react';
|
||||
import type { IFileInfo } from '$types/matrix/common';
|
||||
@@ -31,7 +30,7 @@ import { stopPropagation } from '$utils/keyboard';
|
||||
import { decryptFile, downloadEncryptedMedia, downloadMedia, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { ModalWide } from '$styles/Modal.css';
|
||||
import { getDownloadFilename } from '$utils/download';
|
||||
import { getDownloadFilename, saveFileToDevice } from '$utils/download';
|
||||
|
||||
const renderErrorButton = (retry: () => void, text: string) => (
|
||||
<TooltipProvider
|
||||
@@ -258,7 +257,7 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
|
||||
: await downloadMedia(mediaUrl);
|
||||
|
||||
const fileURL = URL.createObjectURL(fileContent);
|
||||
FileSaver.saveAs(fileURL, getDownloadFilename(body));
|
||||
await saveFileToDevice(fileContent, getDownloadFilename(body), mimeType);
|
||||
return fileURL;
|
||||
}, [mx, url, useAuthentication, mimeType, encInfo, body])
|
||||
);
|
||||
@@ -273,7 +272,7 @@ export function DownloadFile({ body, mimeType, url, info, encInfo }: DownloadFil
|
||||
size="400"
|
||||
onClick={() =>
|
||||
downloadState.status === AsyncStatus.Success
|
||||
? FileSaver.saveAs(downloadState.data, getDownloadFilename(body))
|
||||
? void saveFileToDevice(downloadState.data, getDownloadFilename(body), mimeType)
|
||||
: download()
|
||||
}
|
||||
disabled={downloadState.status === AsyncStatus.Loading}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import {
|
||||
Badge,
|
||||
Box,
|
||||
@@ -49,23 +49,7 @@ import {
|
||||
MATRIX_UNSTABLE_BLUR_HASH_PROPERTY_NAME,
|
||||
} from '../../../../unstable/prefixes';
|
||||
import { useFavoriteGifs } from '$hooks/useFavoriteGifs';
|
||||
|
||||
function thumbnailDimsForMaxEdge(
|
||||
maxEdge: number,
|
||||
w?: number,
|
||||
h?: number
|
||||
): { tw: number; th: number } {
|
||||
const safeEdge = Math.max(1, Math.round(maxEdge));
|
||||
const iw = typeof w === 'number' && Number.isFinite(w) && w > 0 ? w : safeEdge;
|
||||
const ih = typeof h === 'number' && Number.isFinite(h) && h > 0 ? h : safeEdge;
|
||||
const longest = Math.max(iw, ih);
|
||||
if (longest <= safeEdge) return { tw: Math.round(iw), th: Math.round(ih) };
|
||||
const scale = safeEdge / longest;
|
||||
return {
|
||||
tw: Math.max(1, Math.round(iw * scale)),
|
||||
th: Math.max(1, Math.round(ih * scale)),
|
||||
};
|
||||
}
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
|
||||
export function checkIfGif(url: string, mimetype?: string, body?: string) {
|
||||
return (
|
||||
@@ -160,26 +144,24 @@ export const ImageContent = as<'div', ImageContentProps>(
|
||||
|
||||
const isGif = checkIfGif(url, info?.mimetype, body);
|
||||
|
||||
const rawMediaUrl = useMemo(() => {
|
||||
if (url.startsWith('http')) return url;
|
||||
return mxcUrlToHttp(mx, url, useAuthentication) ?? undefined;
|
||||
}, [mx, url, useAuthentication]);
|
||||
|
||||
const resolvedMediaUrl = useRenderableMediaUrl(encInfo ? undefined : rawMediaUrl);
|
||||
|
||||
const [srcState, loadSrc] = useAsyncCallback(
|
||||
useCallback(async () => {
|
||||
if (url.startsWith('http')) return url;
|
||||
|
||||
if (typeof matrixThumbnailMaxEdge === 'number' && matrixThumbnailMaxEdge > 0 && !encInfo) {
|
||||
const { tw, th } = thumbnailDimsForMaxEdge(matrixThumbnailMaxEdge, info?.w, info?.h);
|
||||
const thumbUrl = mxcUrlToHttp(mx, url, useAuthentication, tw, th, 'scale', false);
|
||||
if (thumbUrl) return thumbUrl;
|
||||
}
|
||||
|
||||
const mediaUrl = mxcUrlToHttp(mx, url, useAuthentication);
|
||||
if (!mediaUrl) throw new Error('Invalid media URL');
|
||||
if (encInfo) {
|
||||
const fileContent = await downloadEncryptedMedia(mediaUrl, (encBuf) =>
|
||||
if (!rawMediaUrl) throw new Error('Invalid media URL');
|
||||
const fileContent = await downloadEncryptedMedia(rawMediaUrl, (encBuf) =>
|
||||
decryptFile(encBuf, mimeType ?? FALLBACK_MIMETYPE, encInfo)
|
||||
);
|
||||
return URL.createObjectURL(fileContent);
|
||||
}
|
||||
return mediaUrl;
|
||||
}, [mx, url, useAuthentication, mimeType, encInfo, matrixThumbnailMaxEdge, info?.w, info?.h])
|
||||
return resolvedMediaUrl ?? rawMediaUrl ?? url;
|
||||
}, [rawMediaUrl, resolvedMediaUrl, url, mimeType, encInfo])
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { useCallback, useEffect } from 'react';
|
||||
import { useCallback, useEffect, useMemo } from 'react';
|
||||
import type { IThumbnailContent } from '$types/matrix/common';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { decryptFile, downloadEncryptedMedia, mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import { FALLBACK_MIMETYPE } from '$utils/mimeTypes';
|
||||
|
||||
export type ThumbnailContentProps = {
|
||||
@@ -15,26 +16,31 @@ export function ThumbnailContent({ info, renderImage }: ThumbnailContentProps) {
|
||||
const mx = useMatrixClient();
|
||||
const useAuthentication = useMediaAuthentication();
|
||||
|
||||
const encInfo = info.thumbnail_file;
|
||||
const thumbMxcUrl = encInfo?.url ?? info.thumbnail_url;
|
||||
|
||||
const rawMediaUrl = useMemo(() => {
|
||||
if (typeof thumbMxcUrl !== 'string') return undefined;
|
||||
return mxcUrlToHttp(mx, thumbMxcUrl, useAuthentication) ?? undefined;
|
||||
}, [mx, thumbMxcUrl, useAuthentication]);
|
||||
|
||||
const resolvedMediaUrl = useRenderableMediaUrl(encInfo ? undefined : rawMediaUrl);
|
||||
|
||||
const [thumbSrcState, loadThumbSrc] = useAsyncCallback(
|
||||
useCallback(async () => {
|
||||
const thumbInfo = info.thumbnail_info;
|
||||
const thumbMxcUrl = info.thumbnail_file?.url ?? info.thumbnail_url;
|
||||
const encInfo = info.thumbnail_file;
|
||||
if (typeof thumbMxcUrl !== 'string' || typeof thumbInfo?.mimetype !== 'string') {
|
||||
throw new Error('Failed to load thumbnail');
|
||||
}
|
||||
|
||||
const mediaUrl = mxcUrlToHttp(mx, thumbMxcUrl, useAuthentication);
|
||||
if (!mediaUrl) throw new Error('Invalid media URL');
|
||||
if (encInfo) {
|
||||
const fileContent = await downloadEncryptedMedia(mediaUrl, (encBuf) =>
|
||||
if (!rawMediaUrl) throw new Error('Invalid media URL');
|
||||
const fileContent = await downloadEncryptedMedia(rawMediaUrl, (encBuf) =>
|
||||
decryptFile(encBuf, thumbInfo.mimetype ?? FALLBACK_MIMETYPE, encInfo)
|
||||
);
|
||||
return URL.createObjectURL(fileContent);
|
||||
}
|
||||
|
||||
return mediaUrl;
|
||||
}, [mx, info, useAuthentication])
|
||||
return resolvedMediaUrl ?? rawMediaUrl ?? thumbMxcUrl;
|
||||
}, [info, thumbMxcUrl, rawMediaUrl, resolvedMediaUrl, encInfo])
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { EncryptedAttachmentInfo } from 'browser-encrypt-attachment';
|
||||
import { Box, Button, IconButton, Spinner, Switch, Text, config, toRem } from 'folds';
|
||||
|
||||
import { Star, sizedIcon } from '$components/icons/phosphor';
|
||||
import { getCspNonce } from '$utils/cspNonce';
|
||||
import { ThemePreviewCard } from '$components/theme/ThemePreviewCard';
|
||||
import { CssViewerButton } from '$components/theme/CssViewerButton';
|
||||
import { usePatchSettings } from '$features/settings/cosmetics/themeSettingsPatch';
|
||||
@@ -161,7 +162,7 @@ function UploadedTweakCard({ data }: { data: Extract<SuccessfulUpload, { role: '
|
||||
</Box>
|
||||
{styleBlock && (
|
||||
<>
|
||||
<style>{styleBlock}</style>
|
||||
<style nonce={getCspNonce()}>{styleBlock}</style>
|
||||
<Box
|
||||
className={scopeClass}
|
||||
style={{
|
||||
|
||||
@@ -90,12 +90,26 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
}, [mx, url, useAuthentication, mimeType, encInfo])
|
||||
);
|
||||
|
||||
// When the source download succeeds, reset video-element error state so the
|
||||
// Retry button doesn't flash before the <video> has had a chance to load.
|
||||
useEffect(() => {
|
||||
if (srcState.status === AsyncStatus.Success) {
|
||||
setError(false);
|
||||
}
|
||||
}, [srcState.status]);
|
||||
|
||||
const handleLoad = () => {
|
||||
setLoad(true);
|
||||
setError(false);
|
||||
};
|
||||
const handleError = () => {
|
||||
setLoad(false);
|
||||
setError(true);
|
||||
// Only show the error if the source download already succeeded — if
|
||||
// it's still loading the video element may fire a transient error
|
||||
// before the blob URL is ready.
|
||||
if (srcState.status === AsyncStatus.Success) {
|
||||
setLoad(false);
|
||||
setError(true);
|
||||
}
|
||||
};
|
||||
|
||||
const handleRetry = () => {
|
||||
@@ -198,12 +212,13 @@ export const VideoContent = as<'div', VideoContentProps>(
|
||||
)}
|
||||
{(srcState.status === AsyncStatus.Loading || srcState.status === AsyncStatus.Success) &&
|
||||
!load &&
|
||||
!error &&
|
||||
!blurred && (
|
||||
<Box className={css.AbsoluteContainer} alignItems="Center" justifyContent="Center">
|
||||
<Spinner variant="Secondary" />
|
||||
</Box>
|
||||
)}
|
||||
{(error || srcState.status === AsyncStatus.Error) && (
|
||||
{!load && (error || srcState.status === AsyncStatus.Error) && (
|
||||
<Box
|
||||
className={css.AbsoluteContainer}
|
||||
alignItems="Center"
|
||||
|
||||
@@ -26,6 +26,8 @@ const slideOut = keyframes({
|
||||
// Positions at the top of the viewport, spanning full width.
|
||||
// Uses fixed positioning with safe-area-inset to handle iOS keyboard correctly.
|
||||
// On iOS, the banner stays at the top of the visual viewport even when keyboard is open.
|
||||
// On Android (Tauri) the insets are injected via JS from Kotlin; the
|
||||
// env() fallback handles the window between page load and injection.
|
||||
export const BannerContainer = style({
|
||||
position: 'fixed',
|
||||
// Use env(safe-area-inset-top) to respect device-specific safe areas (notches, etc)
|
||||
@@ -38,6 +40,7 @@ export const BannerContainer = style({
|
||||
flexDirection: 'column',
|
||||
gap: config.space.S200,
|
||||
padding: config.space.S400,
|
||||
paddingTop: `calc(${config.space.S400} + var(--sable-inset-top, env(safe-area-inset-top, 0px)))`,
|
||||
pointerEvents: 'none',
|
||||
alignItems: 'flex-end',
|
||||
|
||||
|
||||
@@ -0,0 +1,384 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { startTransition, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { motion, useMotionValue, useReducedMotion } from 'framer-motion';
|
||||
import { useDrag } from '@use-gesture/react';
|
||||
import { useAtomValue, useSetAtom } from 'jotai';
|
||||
import { matchPath, useLocation, useNavigate } from 'react-router-dom';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { lastVisitedRoomAtom } from '$state/room/lastRoom';
|
||||
import {
|
||||
DIRECT_PATH,
|
||||
DIRECT_ROOM_PATH,
|
||||
EXPLORE_PATH,
|
||||
HOME_PATH,
|
||||
HOME_ROOM_PATH,
|
||||
INBOX_PATH,
|
||||
SPACE_PATH,
|
||||
SPACE_ROOM_PATH,
|
||||
} from '$pages/paths';
|
||||
import { resolveSection } from '$pages/pathUtils';
|
||||
|
||||
const SLIDE_MS = 300;
|
||||
const SLIDE_EASE = 'cubic-bezier(0.32, 0.72, 0, 1)';
|
||||
const OPEN_FRACTION = 0.35;
|
||||
const VELOCITY_THRESHOLD = 0.4;
|
||||
const DIRECTION_DEADZONE = 10;
|
||||
|
||||
type MobileNavDrawerProps = {
|
||||
nav: ReactNode;
|
||||
rail?: ReactNode;
|
||||
bottomNav?: ReactNode;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
const clamp = (value: number, min: number, max: number): number =>
|
||||
Math.min(Math.max(value, min), max);
|
||||
|
||||
/** Sliding mobile drawer: the list and active room are adjacent panels; dragging
|
||||
* reveals the list and commits the route on release. */
|
||||
export function MobileNavDrawer({ nav, rail, bottomNav, children }: MobileNavDrawerProps) {
|
||||
const [mobileGestures] = useSetting(settingsAtom, 'mobileGestures');
|
||||
const reduceMotion = useReducedMotion();
|
||||
const matrixClient = useMatrixClient();
|
||||
const location = useLocation();
|
||||
const navigate = useNavigate();
|
||||
const setLastRoom = useSetAtom(lastVisitedRoomAtom);
|
||||
const lastRoom = useAtomValue(lastVisitedRoomAtom);
|
||||
|
||||
const roomMatch =
|
||||
matchPath({ path: HOME_ROOM_PATH, end: false }, location.pathname) ??
|
||||
matchPath({ path: DIRECT_ROOM_PATH, end: false }, location.pathname) ??
|
||||
matchPath({ path: SPACE_ROOM_PATH, end: false }, location.pathname);
|
||||
|
||||
// The bare section route is the list; anything deeper is content revealed by dragging.
|
||||
const listView =
|
||||
matchPath({ path: HOME_PATH, end: true }, location.pathname) !== null ||
|
||||
matchPath({ path: DIRECT_PATH, end: true }, location.pathname) !== null ||
|
||||
matchPath({ path: SPACE_PATH, end: true }, location.pathname) !== null ||
|
||||
matchPath({ path: EXPLORE_PATH, end: true }, location.pathname) !== null ||
|
||||
matchPath({ path: INBOX_PATH, end: true }, location.pathname) !== null;
|
||||
const contentOpen = !listView;
|
||||
|
||||
const viewportRef = useRef<HTMLDivElement | null>(null);
|
||||
const sliderRef = useRef<HTMLDivElement | null>(null);
|
||||
const navPanelRef = useRef<HTMLDivElement | null>(null);
|
||||
const contentPanelRef = useRef<HTMLDivElement | null>(null);
|
||||
const [width, setWidth] = useState(0);
|
||||
const x = useMotionValue(0);
|
||||
const draggingRef = useRef(false);
|
||||
const openingRef = useRef(false);
|
||||
const prevContentOpenRef = useRef(contentOpen);
|
||||
const openRafRef = useRef(0);
|
||||
const [deferContent, setDeferContent] = useState(false);
|
||||
const [prevOpen, setPrevOpen] = useState(contentOpen);
|
||||
|
||||
if (contentOpen !== prevOpen) {
|
||||
setPrevOpen(contentOpen);
|
||||
setDeferContent(contentOpen && !reduceMotion && !draggingRef.current);
|
||||
}
|
||||
|
||||
// Compositor transition for the settle animation; off = finger-1:1 during drag.
|
||||
const applyTransition = useCallback((animated: boolean) => {
|
||||
const el = sliderRef.current;
|
||||
if (el) el.style.transition = animated ? `transform ${SLIDE_MS}ms ${SLIDE_EASE}` : 'none';
|
||||
}, []);
|
||||
|
||||
const settle = useCallback(
|
||||
(target: number) => {
|
||||
if (reduceMotion) {
|
||||
applyTransition(false);
|
||||
x.jump(target);
|
||||
return;
|
||||
}
|
||||
applyTransition(true);
|
||||
x.set(target);
|
||||
},
|
||||
[reduceMotion, x, applyTransition]
|
||||
);
|
||||
|
||||
// Release the deferred room after the slide is committed to the compositor.
|
||||
useLayoutEffect(() => {
|
||||
if (!deferContent) return undefined;
|
||||
cancelAnimationFrame(openRafRef.current);
|
||||
openRafRef.current = requestAnimationFrame(() =>
|
||||
requestAnimationFrame(() => setDeferContent(false))
|
||||
);
|
||||
return () => cancelAnimationFrame(openRafRef.current);
|
||||
}, [deferContent]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const el = viewportRef.current;
|
||||
if (!el) return undefined;
|
||||
const update = () => setWidth(el.clientWidth);
|
||||
update();
|
||||
const observer = new ResizeObserver(update);
|
||||
observer.observe(el);
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
// Keep the offscreen panel out of the focus order and accessibility tree.
|
||||
useLayoutEffect(() => {
|
||||
navPanelRef.current?.toggleAttribute('inert', contentOpen);
|
||||
contentPanelRef.current?.toggleAttribute('inert', !contentOpen);
|
||||
}, [contentOpen]);
|
||||
|
||||
// Sync panel position to the route: animate on route change, jump on mount/resize.
|
||||
useLayoutEffect(() => {
|
||||
const routeChanged = prevContentOpenRef.current !== contentOpen;
|
||||
prevContentOpenRef.current = contentOpen;
|
||||
if (draggingRef.current) return;
|
||||
const target = contentOpen ? -width : 0;
|
||||
if (routeChanged && width > 0 && !reduceMotion) {
|
||||
settle(target);
|
||||
} else {
|
||||
applyTransition(false);
|
||||
x.jump(target);
|
||||
}
|
||||
}, [contentOpen, width, x, settle, applyTransition, reduceMotion]);
|
||||
|
||||
const goToList = useCallback((): boolean => {
|
||||
const section = resolveSection(location.pathname);
|
||||
if (!section) return false;
|
||||
|
||||
const id = roomMatch?.params.roomIdOrAlias;
|
||||
if (section.getRoomPath && id) {
|
||||
setLastRoom({ section: section.key, roomId: decodeURIComponent(id) });
|
||||
}
|
||||
|
||||
navigate(section.listPath);
|
||||
return true;
|
||||
}, [roomMatch, location.pathname, navigate, setLastRoom]);
|
||||
|
||||
const goToRoom = useCallback((): boolean => {
|
||||
const section = resolveSection(location.pathname);
|
||||
if (!section?.getRoomPath) return false;
|
||||
// Scope the remembered room to its section so a DM never opens under /home/, etc.
|
||||
if (!lastRoom || lastRoom.section !== section.key) return false;
|
||||
|
||||
startTransition(() => navigate(section.getRoomPath!(lastRoom.roomId)));
|
||||
return true;
|
||||
}, [lastRoom, location.pathname, navigate]);
|
||||
|
||||
const openableSection = resolveSection(location.pathname);
|
||||
const canOpenRoom =
|
||||
!!openableSection?.getRoomPath && !!lastRoom && lastRoom.section === openableSection.key;
|
||||
|
||||
useEffect(() => {
|
||||
if (contentOpen || !canOpenRoom || !lastRoom) return undefined;
|
||||
const room = matrixClient.getRoom(lastRoom.roomId);
|
||||
if (!room) return undefined;
|
||||
const ric =
|
||||
window.requestIdleCallback ??
|
||||
((cb: IdleRequestCallback) =>
|
||||
window.setTimeout(
|
||||
() => cb({ didTimeout: false, timeRemaining: () => 30 } as IdleDeadline),
|
||||
200
|
||||
));
|
||||
const cic = window.cancelIdleCallback ?? window.clearTimeout;
|
||||
const handle = ric(() => {
|
||||
room
|
||||
.getLiveTimeline()
|
||||
.getEvents()
|
||||
.slice(-20)
|
||||
.forEach((event) => {
|
||||
if (event.isEncrypted()) matrixClient.decryptEventIfNeeded(event).catch(() => undefined);
|
||||
});
|
||||
});
|
||||
return () => cic(handle);
|
||||
}, [contentOpen, canOpenRoom, lastRoom, matrixClient]);
|
||||
|
||||
const readX = useCallback((): number => {
|
||||
const el = sliderRef.current;
|
||||
if (!el) return x.get();
|
||||
const t = getComputedStyle(el).transform;
|
||||
if (!t || t === 'none') return 0;
|
||||
try {
|
||||
return new DOMMatrix(t).m41;
|
||||
} catch {
|
||||
return x.get();
|
||||
}
|
||||
}, [x]);
|
||||
|
||||
const bind = useDrag(
|
||||
({
|
||||
first,
|
||||
active,
|
||||
canceled,
|
||||
movement: [mx],
|
||||
offset: [ox],
|
||||
velocity: [vx],
|
||||
direction: [dx],
|
||||
event,
|
||||
cancel,
|
||||
}) => {
|
||||
if (canceled) {
|
||||
if (draggingRef.current) {
|
||||
draggingRef.current = false;
|
||||
openingRef.current = false;
|
||||
settle(contentOpen ? -width : 0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!mobileGestures || width === 0) return;
|
||||
|
||||
const target = event?.target;
|
||||
if (target instanceof HTMLElement && target.closest('[data-gestures="ignore"]')) {
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
|
||||
if (contentOpen) {
|
||||
if (mx < -DIRECTION_DEADZONE && !openingRef.current) {
|
||||
if (draggingRef.current) {
|
||||
draggingRef.current = false;
|
||||
settle(-width);
|
||||
}
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
if (active) {
|
||||
// Take over any settling animation; offset is seeded from the live position.
|
||||
if (first) {
|
||||
x.stop();
|
||||
applyTransition(false);
|
||||
}
|
||||
draggingRef.current = true;
|
||||
x.set(clamp(ox, -width, 0));
|
||||
return;
|
||||
}
|
||||
draggingRef.current = false;
|
||||
if (openingRef.current) {
|
||||
openingRef.current = false;
|
||||
const keepRoom = -ox > width * OPEN_FRACTION || (vx > VELOCITY_THRESHOLD && dx < 0);
|
||||
if (keepRoom) {
|
||||
settle(-width);
|
||||
} else {
|
||||
goToList();
|
||||
settle(0);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const opened = width + ox > width * OPEN_FRACTION || (vx > VELOCITY_THRESHOLD && dx > 0);
|
||||
if (opened && goToList()) {
|
||||
settle(0);
|
||||
} else {
|
||||
settle(-width);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (mx > DIRECTION_DEADZONE || !canOpenRoom) {
|
||||
if (draggingRef.current) {
|
||||
draggingRef.current = false;
|
||||
settle(0);
|
||||
}
|
||||
cancel();
|
||||
return;
|
||||
}
|
||||
if (active) {
|
||||
if (first) {
|
||||
x.stop();
|
||||
applyTransition(false);
|
||||
}
|
||||
draggingRef.current = true;
|
||||
x.set(clamp(ox, -width, 0));
|
||||
if (!openingRef.current && -ox > width * 0.12 && goToRoom()) {
|
||||
openingRef.current = true;
|
||||
}
|
||||
return;
|
||||
}
|
||||
draggingRef.current = false;
|
||||
if (openingRef.current) {
|
||||
openingRef.current = false;
|
||||
const keep = -ox > width * OPEN_FRACTION || (vx > VELOCITY_THRESHOLD && dx < 0);
|
||||
if (keep) {
|
||||
settle(-width);
|
||||
} else {
|
||||
goToList();
|
||||
settle(0);
|
||||
}
|
||||
} else {
|
||||
settle(0);
|
||||
}
|
||||
},
|
||||
// axis:'x' + touch-action:pan-y lets the browser keep native vertical scroll.
|
||||
{
|
||||
axis: 'x',
|
||||
filterTaps: true,
|
||||
pointer: { capture: false },
|
||||
from: () => [readX(), 0],
|
||||
}
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
{...bind()}
|
||||
ref={viewportRef}
|
||||
style={{
|
||||
position: 'relative',
|
||||
overflow: 'hidden',
|
||||
display: 'flex',
|
||||
flexGrow: 1,
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
touchAction: 'pan-y',
|
||||
}}
|
||||
>
|
||||
<motion.div
|
||||
ref={sliderRef}
|
||||
style={{ x, display: 'flex', height: '100%', willChange: 'transform' }}
|
||||
>
|
||||
<div
|
||||
ref={navPanelRef}
|
||||
style={{
|
||||
width,
|
||||
height: '100%',
|
||||
flexShrink: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
<div
|
||||
style={{
|
||||
flexGrow: 1,
|
||||
minHeight: 0,
|
||||
display: 'flex',
|
||||
flexDirection: 'row',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{rail && (
|
||||
<div style={{ flexShrink: 0, display: 'flex', overflow: 'hidden' }}>{rail}</div>
|
||||
)}
|
||||
<div
|
||||
style={{
|
||||
flexGrow: 1,
|
||||
minWidth: 0,
|
||||
display: 'flex',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{nav}
|
||||
</div>
|
||||
</div>
|
||||
{bottomNav}
|
||||
</div>
|
||||
<div
|
||||
ref={contentPanelRef}
|
||||
style={{
|
||||
width,
|
||||
height: '100%',
|
||||
flexShrink: 0,
|
||||
display: 'flex',
|
||||
overflow: 'hidden',
|
||||
}}
|
||||
>
|
||||
{deferContent ? null : children}
|
||||
</div>
|
||||
</motion.div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -3,22 +3,37 @@ import { Box, Header, Line, Scroll, Text, as } from 'folds';
|
||||
import classNames from 'classnames';
|
||||
import { ContainerColor } from '$styles/ContainerColor.css';
|
||||
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { MobileNavDrawer } from './MobileNavDrawer';
|
||||
import * as css from './style.css';
|
||||
|
||||
type PageRootProps = {
|
||||
nav: ReactNode;
|
||||
rail?: ReactNode;
|
||||
bottomNav?: ReactNode;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export function PageRoot({ nav, children }: PageRootProps) {
|
||||
export function PageRoot({ nav, rail, bottomNav, children }: PageRootProps) {
|
||||
const screenSize = useScreenSizeContext();
|
||||
const [mobileGestures] = useSetting(settingsAtom, 'mobileGestures');
|
||||
const isMobile = screenSize === ScreenSize.Mobile;
|
||||
|
||||
if (isMobile && mobileGestures) {
|
||||
return (
|
||||
<Box grow="Yes" className={ContainerColor({ variant: 'Background' })}>
|
||||
<MobileNavDrawer nav={nav} rail={rail} bottomNav={bottomNav}>
|
||||
{children}
|
||||
</MobileNavDrawer>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Box grow="Yes" className={ContainerColor({ variant: 'Background' })}>
|
||||
{nav}
|
||||
{screenSize !== ScreenSize.Mobile && (
|
||||
<Line variant="Background" size="300" direction="Vertical" />
|
||||
)}
|
||||
{!isMobile && <Line variant="Background" size="300" direction="Vertical" />}
|
||||
{children}
|
||||
</Box>
|
||||
);
|
||||
@@ -73,6 +88,7 @@ export function PageNavContent({
|
||||
size="300"
|
||||
hideTrack
|
||||
visibility="Hover"
|
||||
style={{ touchAction: 'pan-y' }}
|
||||
>
|
||||
<div className={css.PageNavContent}>{children}</div>
|
||||
</Scroll>
|
||||
|
||||
@@ -25,7 +25,8 @@ export type PageNavVariants = RecipeVariants<typeof PageNav>;
|
||||
|
||||
export const PageNavHeader = recipe({
|
||||
base: {
|
||||
padding: `0 ${config.space.S200} 0 ${config.space.S300}`,
|
||||
paddingRight: config.space.S200,
|
||||
paddingLeft: config.space.S300,
|
||||
flexShrink: 0,
|
||||
selectors: {
|
||||
'button&': {
|
||||
@@ -58,8 +59,8 @@ export type PageNavHeaderVariants = RecipeVariants<typeof PageNavHeader>;
|
||||
|
||||
export const PageNavContent = style({
|
||||
minHeight: '100%',
|
||||
padding: config.space.S200,
|
||||
paddingRight: 0,
|
||||
paddingTop: config.space.S200,
|
||||
paddingLeft: config.space.S200,
|
||||
paddingBottom: config.space.S700,
|
||||
});
|
||||
|
||||
@@ -91,7 +92,6 @@ export const PageContent = style([
|
||||
{
|
||||
paddingTop: config.space.S400,
|
||||
paddingLeft: config.space.S400,
|
||||
paddingRight: 0,
|
||||
paddingBottom: toRem(100),
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { AvatarImage as FoldsAvatarImage } from 'folds';
|
||||
import type { ReactEventHandler } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useState } from 'react';
|
||||
import bgColorImg from '$utils/bgColorImg';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import * as css from './RoomAvatar.css';
|
||||
|
||||
type AvatarImageProps = {
|
||||
@@ -16,68 +17,28 @@ type AvatarImageProps = {
|
||||
export function AvatarImage({ src, alt, uniformIcons, onError }: AvatarImageProps) {
|
||||
const [uniformIconsSetting] = useSetting(settingsAtom, 'uniformIcons');
|
||||
const [image, setImage] = useState<HTMLImageElement | undefined>(undefined);
|
||||
const [processedSrc, setProcessedSrc] = useState<string>(src);
|
||||
const resolvedSrc = useRenderableMediaUrl(src);
|
||||
const mediaSrc = resolvedSrc ?? src;
|
||||
|
||||
const useUniformIcons = uniformIconsSetting && uniformIcons === true;
|
||||
const normalizedBg = useUniformIcons && image ? bgColorImg(image) : undefined;
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
let objectUrl: string | null = null;
|
||||
|
||||
const processImage = async () => {
|
||||
try {
|
||||
const res = await fetch(src, { mode: 'cors' });
|
||||
const contentType = res.headers.get('content-type');
|
||||
|
||||
if (contentType && contentType.includes('image/svg+xml')) {
|
||||
const text = await res.text();
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(text, 'image/svg+xml');
|
||||
|
||||
const animations = doc.querySelectorAll('animate, animateTransform, animateMotion');
|
||||
animations.forEach((anim) => anim.setAttribute('repeatCount', 'indefinite'));
|
||||
|
||||
const style = doc.createElementNS('http://www.w3.org/2000/svg', 'style');
|
||||
style.textContent = '* { animation-iteration-count: infinite !important; }';
|
||||
doc.documentElement.appendChild(style);
|
||||
|
||||
const serializer = new XMLSerializer();
|
||||
const newSvgString = serializer.serializeToString(doc);
|
||||
const blob = new Blob([newSvgString], { type: 'image/svg+xml' });
|
||||
|
||||
objectUrl = URL.createObjectURL(blob);
|
||||
if (isMounted) setProcessedSrc(objectUrl);
|
||||
} else if (isMounted) setProcessedSrc(src);
|
||||
} catch {
|
||||
if (isMounted) setProcessedSrc(src);
|
||||
}
|
||||
};
|
||||
|
||||
processImage();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
if (objectUrl) {
|
||||
URL.revokeObjectURL(objectUrl);
|
||||
}
|
||||
};
|
||||
}, [src]);
|
||||
|
||||
const handleLoad: ReactEventHandler<HTMLImageElement> = (evt) => {
|
||||
evt.currentTarget.setAttribute('data-image-loaded', 'true');
|
||||
setImage(evt.currentTarget);
|
||||
};
|
||||
|
||||
const isBlobUrl = processedSrc.startsWith('blob:');
|
||||
const isBlobUrl = mediaSrc.startsWith('blob:');
|
||||
|
||||
return (
|
||||
<FoldsAvatarImage
|
||||
className={css.RoomAvatar}
|
||||
style={{ backgroundColor: useUniformIcons ? normalizedBg : undefined }}
|
||||
src={processedSrc}
|
||||
src={mediaSrc}
|
||||
crossOrigin={isBlobUrl ? undefined : 'anonymous'}
|
||||
alt={alt}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={() => {
|
||||
setImage(undefined);
|
||||
onError();
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
import { render, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { TauriFrontendReady } from './TauriFrontendReady';
|
||||
|
||||
const { mockIsTauri, mockOsType, mockShow, mockGetCurrentWindow } = vi.hoisted(() => ({
|
||||
mockIsTauri: vi.fn<() => boolean>(),
|
||||
mockOsType: vi.fn<() => string>(),
|
||||
mockShow: vi.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
mockGetCurrentWindow: vi.fn<() => { show: () => Promise<void> }>(),
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({
|
||||
isTauri: mockIsTauri,
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/plugin-os', () => ({
|
||||
type: mockOsType,
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/api/window', () => ({
|
||||
getCurrentWindow: mockGetCurrentWindow,
|
||||
}));
|
||||
|
||||
vi.mock('$utils/debug', () => ({
|
||||
createLogger: () => ({
|
||||
log: vi.fn<(...args: unknown[]) => void>(),
|
||||
warn: vi.fn<(...args: unknown[]) => void>(),
|
||||
}),
|
||||
}));
|
||||
|
||||
function setDocumentReadyState(value: DocumentReadyState) {
|
||||
Object.defineProperty(document, 'readyState', {
|
||||
configurable: true,
|
||||
value,
|
||||
});
|
||||
}
|
||||
|
||||
describe('TauriFrontendReady', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockIsTauri.mockReturnValue(true);
|
||||
mockGetCurrentWindow.mockReturnValue({ show: mockShow });
|
||||
setDocumentReadyState('complete');
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('does not schedule mobile startup work after mount', () => {
|
||||
const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
|
||||
mockOsType.mockReturnValue('android');
|
||||
|
||||
render(<TauriFrontendReady />);
|
||||
|
||||
expect(addEventListenerSpy).not.toHaveBeenCalledWith('load', expect.any(Function), {
|
||||
once: true,
|
||||
});
|
||||
expect(mockGetCurrentWindow).not.toHaveBeenCalled();
|
||||
expect(mockShow).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('shows the desktop window without syncing desktop preferences on desktop', async () => {
|
||||
const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
|
||||
mockOsType.mockReturnValue('windows');
|
||||
setDocumentReadyState('complete');
|
||||
|
||||
render(<TauriFrontendReady />);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockShow).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
expect(addEventListenerSpy).not.toHaveBeenCalledWith('load', expect.any(Function), {
|
||||
once: true,
|
||||
});
|
||||
expect(mockGetCurrentWindow).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('waits for the window load event before showing the desktop window', async () => {
|
||||
const addEventListenerSpy = vi.spyOn(window, 'addEventListener');
|
||||
mockOsType.mockReturnValue('linux');
|
||||
setDocumentReadyState('loading');
|
||||
|
||||
render(<TauriFrontendReady />);
|
||||
|
||||
expect(addEventListenerSpy).toHaveBeenCalledWith('load', expect.any(Function), { once: true });
|
||||
expect(mockGetCurrentWindow).toHaveBeenCalledOnce();
|
||||
expect(mockShow).not.toHaveBeenCalled();
|
||||
|
||||
window.dispatchEvent(new Event('load'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockShow).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
import { useEffect } from 'react';
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
import { createLogger } from '$utils/debug';
|
||||
|
||||
const log = createLogger('TauriFrontendReady');
|
||||
|
||||
function onPageFullyLoaded(cb: () => void): () => void {
|
||||
if (document.readyState === 'complete') {
|
||||
cb();
|
||||
return () => {};
|
||||
}
|
||||
|
||||
const handleLoad = () => {
|
||||
cb();
|
||||
};
|
||||
|
||||
window.addEventListener('load', handleLoad, { once: true });
|
||||
return () => {
|
||||
window.removeEventListener('load', handleLoad);
|
||||
};
|
||||
}
|
||||
|
||||
export function TauriFrontendReady() {
|
||||
useEffect(() => {
|
||||
if (!isTauri()) return undefined;
|
||||
|
||||
const os = osType();
|
||||
if (os !== 'windows' && os !== 'linux' && os !== 'macos') return undefined;
|
||||
|
||||
const appWindow = getCurrentWindow();
|
||||
return onPageFullyLoaded(() => {
|
||||
appWindow.show().catch((error) => {
|
||||
log.warn('Failed to show main window after frontend fully loaded:', error);
|
||||
});
|
||||
});
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { getCurrentWindow, type Window } from '@tauri-apps/api/window';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { createLogger } from '$utils/debug';
|
||||
import { titlebarStatusAtom } from '$state/titlebarStatus';
|
||||
import { SyncConnectionStatusTitlebar } from '$components/SyncConnectionStatus';
|
||||
import {
|
||||
hideSnapOverlay as hideSnapOverlayCommand,
|
||||
showSnapOverlay as showSnapOverlayCommand,
|
||||
startWindowTrackingWithTarget,
|
||||
stopWindowTracking,
|
||||
} from '$generated/tauri/commands';
|
||||
|
||||
const log = createLogger('WindowsTitleBar');
|
||||
const SNAP_OVERLAY_DELAY_MS = 620;
|
||||
const SNAP_POPUP_WINDOW_CLASS = 'Xaml_WindowedPopupClass';
|
||||
const SNAP_POPUP_EXE = 'explorer.exe';
|
||||
|
||||
type TrackingEventType = 'Started' | 'TargetLost' | 'Timeout' | 'Stopped';
|
||||
type TrackingEventPayload = {
|
||||
event_type: TrackingEventType;
|
||||
};
|
||||
|
||||
function MinimizeIcon() {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 12 12"
|
||||
aria-hidden
|
||||
focusable="false"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<path d="M1.5 6.5h9" strokeLinecap="square" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function MaximizeIcon() {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 12 12"
|
||||
aria-hidden
|
||||
focusable="false"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<rect x="1.5" y="1.5" width="9" height="9" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function RestoreIcon() {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 12 12"
|
||||
aria-hidden
|
||||
focusable="false"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<rect x="1.5" y="3.5" width="7" height="7" />
|
||||
<path d="M3.5 1.5h5a2 2 0 0 1 2 2v5" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
function CloseIcon() {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 12 12"
|
||||
aria-hidden
|
||||
focusable="false"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1"
|
||||
shapeRendering="crispEdges"
|
||||
>
|
||||
<path d="M1.5 1.5l9 9M10.5 1.5l-9 9" strokeLinecap="square" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
|
||||
export function WindowsTitleBar() {
|
||||
const [maximized, setMaximized] = useState(false);
|
||||
const appWindowRef = useRef<Window | null>(null);
|
||||
const snapTimerRef = useRef<number | undefined>(undefined);
|
||||
const isWindowsDesktopTauri = isTauri() && osType() === 'windows';
|
||||
const titlebarStatus = useAtomValue(titlebarStatusAtom);
|
||||
|
||||
const hideSnapOverlay = async () => {
|
||||
try {
|
||||
await hideSnapOverlayCommand();
|
||||
} catch (error) {
|
||||
log.warn('Failed to hide snap overlay:', error);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWindowsDesktopTauri) return undefined;
|
||||
|
||||
const appWindow = getCurrentWindow();
|
||||
appWindowRef.current = appWindow;
|
||||
|
||||
let mounted = true;
|
||||
let unlistenResize: (() => void) | undefined;
|
||||
let unlistenTracking: (() => void) | undefined;
|
||||
|
||||
const syncMaximized = async () => {
|
||||
try {
|
||||
const isMaximizedState = await appWindow.isMaximized();
|
||||
if (mounted) setMaximized(isMaximizedState);
|
||||
} catch (error) {
|
||||
log.warn('Failed to sync maximized state:', error);
|
||||
}
|
||||
};
|
||||
|
||||
syncMaximized().catch((error) => {
|
||||
log.warn('Failed to sync maximized state:', error);
|
||||
});
|
||||
appWindow
|
||||
.onResized(() => {
|
||||
syncMaximized().catch((error) => {
|
||||
log.warn('Failed to sync maximized state:', error);
|
||||
});
|
||||
})
|
||||
.then((removeListener) => {
|
||||
unlistenResize = removeListener;
|
||||
})
|
||||
.catch((error) => {
|
||||
log.warn('Failed to subscribe to window resize:', error);
|
||||
});
|
||||
|
||||
listen<TrackingEventPayload>('window-tracking', (event) => {
|
||||
const eventType = event.payload?.event_type;
|
||||
if (eventType === 'TargetLost' || eventType === 'Timeout') {
|
||||
hideSnapOverlay();
|
||||
}
|
||||
})
|
||||
.then((removeListener) => {
|
||||
unlistenTracking = removeListener;
|
||||
})
|
||||
.catch((error) => {
|
||||
log.warn('Failed to subscribe to window-tracking event:', error);
|
||||
});
|
||||
|
||||
return () => {
|
||||
mounted = false;
|
||||
if (snapTimerRef.current !== undefined) {
|
||||
window.clearTimeout(snapTimerRef.current);
|
||||
}
|
||||
stopWindowTracking().catch(() => {});
|
||||
hideSnapOverlay();
|
||||
unlistenResize?.();
|
||||
unlistenTracking?.();
|
||||
};
|
||||
}, [isWindowsDesktopTauri]);
|
||||
|
||||
if (!isWindowsDesktopTauri) return null;
|
||||
|
||||
const minimize = () => {
|
||||
if (!isWindowsDesktopTauri) return;
|
||||
|
||||
stopWindowTracking().catch(() => {});
|
||||
hideSnapOverlay();
|
||||
appWindowRef.current?.minimize().catch((error) => {
|
||||
log.warn('Failed to minimize window:', error);
|
||||
});
|
||||
};
|
||||
|
||||
const toggleMaximize = () => {
|
||||
if (!isWindowsDesktopTauri) return;
|
||||
|
||||
if (snapTimerRef.current !== undefined) {
|
||||
window.clearTimeout(snapTimerRef.current);
|
||||
snapTimerRef.current = undefined;
|
||||
}
|
||||
|
||||
stopWindowTracking().catch(() => {});
|
||||
hideSnapOverlay();
|
||||
appWindowRef.current?.toggleMaximize().catch((error) => {
|
||||
log.warn('Failed to toggle maximize:', error);
|
||||
});
|
||||
};
|
||||
|
||||
const close = () => {
|
||||
if (!isWindowsDesktopTauri) return;
|
||||
|
||||
stopWindowTracking().catch(() => {});
|
||||
hideSnapOverlay();
|
||||
appWindowRef.current?.close().catch((error) => {
|
||||
log.warn('Failed to close window:', error);
|
||||
});
|
||||
};
|
||||
|
||||
const showSnapOverlay = () => {
|
||||
if (!isWindowsDesktopTauri) return;
|
||||
|
||||
if (snapTimerRef.current !== undefined) {
|
||||
window.clearTimeout(snapTimerRef.current);
|
||||
}
|
||||
stopWindowTracking().catch(() => {});
|
||||
|
||||
snapTimerRef.current = window.setTimeout(() => {
|
||||
appWindowRef.current
|
||||
?.setFocus()
|
||||
.then(() => showSnapOverlayCommand())
|
||||
.catch((error) => {
|
||||
log.warn('Failed to show snap overlay:', error);
|
||||
});
|
||||
}, SNAP_OVERLAY_DELAY_MS);
|
||||
};
|
||||
|
||||
const cancelSnapOverlay = () => {
|
||||
if (!isWindowsDesktopTauri) return;
|
||||
|
||||
if (snapTimerRef.current !== undefined) {
|
||||
window.clearTimeout(snapTimerRef.current);
|
||||
snapTimerRef.current = undefined;
|
||||
}
|
||||
|
||||
stopWindowTracking()
|
||||
.then(() =>
|
||||
startWindowTrackingWithTarget({
|
||||
target: {
|
||||
window_class: SNAP_POPUP_WINDOW_CLASS,
|
||||
exe_name: SNAP_POPUP_EXE,
|
||||
},
|
||||
})
|
||||
)
|
||||
.catch((error) => {
|
||||
log.warn('Failed to start snap popup tracking:', error);
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<nav className="tauri-titlebar">
|
||||
<div className="tauri-titlebar__drag" data-tauri-drag-region>
|
||||
<span className="tauri-titlebar__title" data-tauri-drag-region>
|
||||
sable
|
||||
</span>
|
||||
</div>
|
||||
<div className="tauri-titlebar__status" data-tauri-drag-region>
|
||||
<SyncConnectionStatusTitlebar status={titlebarStatus} />
|
||||
</div>
|
||||
|
||||
<div className="tauri-titlebar__controls">
|
||||
<button
|
||||
type="button"
|
||||
className="tauri-titlebar__control"
|
||||
onClick={minimize}
|
||||
aria-label="Minimize"
|
||||
>
|
||||
<MinimizeIcon />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="tauri-titlebar__control"
|
||||
onClick={toggleMaximize}
|
||||
onMouseEnter={showSnapOverlay}
|
||||
onMouseLeave={cancelSnapOverlay}
|
||||
aria-label={maximized ? 'Restore' : 'Maximize'}
|
||||
>
|
||||
{maximized ? <RestoreIcon /> : <MaximizeIcon />}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="tauri-titlebar__control tauri-titlebar__control--close"
|
||||
onClick={close}
|
||||
aria-label="Close"
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
</nav>
|
||||
);
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { Check, Download, Link, Star, Warning, sizedIcon } from '$components/ico
|
||||
|
||||
import { useTimeoutToggle } from '$hooks/useTimeoutToggle';
|
||||
import { copyToClipboard } from '$utils/dom';
|
||||
import { getCspNonce } from '$utils/cspNonce';
|
||||
import { buildPreviewStyleBlock, extractSafePreviewCustomProperties } from '../../theme/previewCss';
|
||||
import { CssViewerButton } from './CssViewerButton';
|
||||
|
||||
@@ -194,7 +195,7 @@ export function ThemePreviewCard({
|
||||
|
||||
{styleBlock ? (
|
||||
<>
|
||||
<style>{styleBlock}</style>
|
||||
<style nonce={getCspNonce()}>{styleBlock}</style>
|
||||
<Box
|
||||
className={scopeClass}
|
||||
direction="Column"
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { createPortal } from 'react-dom';
|
||||
import { Box, Text, color, config, toRem } from 'folds';
|
||||
|
||||
import { Check, sizedIcon } from '$components/icons/phosphor';
|
||||
import { useToastMessage } from '$state/toast';
|
||||
|
||||
type ToastProps = {
|
||||
container: HTMLElement | null;
|
||||
};
|
||||
|
||||
export function Toast({ container }: ToastProps) {
|
||||
const toast = useToastMessage();
|
||||
if (!toast || !container) return null;
|
||||
|
||||
return createPortal(
|
||||
<div
|
||||
style={{
|
||||
position: 'fixed',
|
||||
left: 0,
|
||||
right: 0,
|
||||
bottom: `calc(env(safe-area-inset-bottom, 0px) + ${toRem(24)})`,
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
pointerEvents: 'none',
|
||||
zIndex: 9999,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
as="div"
|
||||
shrink="No"
|
||||
alignItems="Center"
|
||||
gap="200"
|
||||
style={{
|
||||
padding: `${config.space.S200} ${config.space.S400}`,
|
||||
backgroundColor: color.Success.Container,
|
||||
color: color.Success.OnContainer,
|
||||
borderRadius: config.radii.Pill,
|
||||
boxShadow: config.shadow.E200,
|
||||
maxWidth: '90%',
|
||||
}}
|
||||
>
|
||||
{sizedIcon(Check, '200')}
|
||||
<Text size="T300" truncate>
|
||||
{toast.text}
|
||||
</Text>
|
||||
</Box>
|
||||
</div>,
|
||||
container
|
||||
);
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { encodeBlurHash } from '$utils/blurHash';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import { Attachment, AttachmentBox, AttachmentHeader } from '../message/attachment';
|
||||
import { Image } from '../media';
|
||||
import { UrlPreview } from './UrlPreview';
|
||||
|
||||
@@ -20,6 +20,7 @@ import { ThemePreviewCard } from '../theme/ThemePreviewCard';
|
||||
import { SableChatPreviewPlaceholder } from './SableChatPreviewPlaceholder';
|
||||
import { ThemeThirdPartyBanner } from './ThemeThirdPartyBanner';
|
||||
import { pruneThemeFavorites, themeUrlHostLabel } from '../../theme/themeLibrary';
|
||||
import { fetch } from '$utils/fetch';
|
||||
|
||||
function isHttps(url: string): boolean {
|
||||
return /^https:\/\//i.test(url);
|
||||
|
||||
@@ -15,6 +15,7 @@ import { Check, Link, Star, Warning, sizedIcon } from '$components/icons/phospho
|
||||
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
import { useTimeoutToggle } from '$hooks/useTimeoutToggle';
|
||||
import { getCspNonce } from '$utils/cspNonce';
|
||||
import { usePatchSettings } from '$features/settings/cosmetics/themeSettingsPatch';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom, type ThemeRemoteTweakFavorite } from '$state/settings';
|
||||
@@ -28,6 +29,7 @@ import { SableChatPreviewPlaceholder } from './SableChatPreviewPlaceholder';
|
||||
import { ThemeThirdPartyBanner } from './ThemeThirdPartyBanner';
|
||||
import { CssViewerButton } from '../theme/CssViewerButton';
|
||||
import { pruneThemeTweakFavorites, themeUrlHostLabel } from '../../theme/themeLibrary';
|
||||
import { fetch } from '$utils/fetch';
|
||||
|
||||
function basenameFromFullSableUrl(url: string): string {
|
||||
const tail = url.split('/').pop() ?? url;
|
||||
@@ -346,7 +348,7 @@ export function TweakPreviewUrlCard({ url }: { url: string }) {
|
||||
|
||||
{styleBlock ? (
|
||||
<>
|
||||
<style>{styleBlock}</style>
|
||||
<style nonce={getCspNonce()}>{styleBlock}</style>
|
||||
<Box
|
||||
className={scopeClass}
|
||||
direction="Column"
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { ReactEventHandler, ReactNode } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import classNames from 'classnames';
|
||||
import colorMXID from '$utils/colorMXID';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import * as css from './UserAvatar.css';
|
||||
|
||||
type UserAvatarProps = {
|
||||
@@ -19,6 +20,7 @@ const handleImageLoad: ReactEventHandler<HTMLImageElement> = (evt) => {
|
||||
|
||||
export function UserAvatar({ className, userId, src, alt, renderFallback }: UserAvatarProps) {
|
||||
const [error, setError] = useState(false);
|
||||
const resolvedSrc = useRenderableMediaUrl(src);
|
||||
|
||||
useEffect(() => {
|
||||
setError(false);
|
||||
@@ -38,8 +40,10 @@ export function UserAvatar({ className, userId, src, alt, renderFallback }: User
|
||||
return (
|
||||
<AvatarImage
|
||||
className={classNames(css.UserAvatar, className)}
|
||||
src={src}
|
||||
src={resolvedSrc ?? src}
|
||||
alt={alt}
|
||||
loading="lazy"
|
||||
decoding="async"
|
||||
onError={() => setError(true)}
|
||||
onLoad={handleImageLoad}
|
||||
draggable={false}
|
||||
|
||||
@@ -25,7 +25,7 @@ import { stopPropagation } from '$utils/keyboard';
|
||||
import { useRoom } from '$hooks/useRoom';
|
||||
import { useSableCosmetics } from '$hooks/useSableCosmetics';
|
||||
import { useNickname } from '$hooks/useNickname';
|
||||
import { useBlobCache } from '$hooks/useBlobCache';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import { ImageViewer } from '$components/image-viewer';
|
||||
import { AvatarPresence, PresenceBadge } from '$components/presence';
|
||||
import { UserAvatar } from '$components/user-avatar';
|
||||
@@ -66,8 +66,8 @@ export function UserHero({
|
||||
const [viewAvatar, setViewAvatar] = useState<string>();
|
||||
const [isFullStatus, setIsFullStatus] = useState(false);
|
||||
|
||||
const cachedBannerUrl = useBlobCache(bannerUrl);
|
||||
const cachedAvatarUrl = useBlobCache(avatarUrl);
|
||||
const cachedBannerUrl = useRenderableMediaUrl(bannerUrl);
|
||||
const cachedAvatarUrl = useRenderableMediaUrl(avatarUrl);
|
||||
|
||||
const coverUrl = cachedBannerUrl || cachedAvatarUrl;
|
||||
const isFallbackCover = !cachedBannerUrl && !!cachedAvatarUrl;
|
||||
|
||||
@@ -23,6 +23,7 @@ import * as Sentry from '@sentry/react';
|
||||
import { useCloseBugReportModal, useBugReportModalOpen } from '$state/hooks/bugReportModal';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { getDebugLogger } from '$utils/debugLogger';
|
||||
import { fetch } from '$utils/fetch';
|
||||
|
||||
type ReportType = 'bug' | 'feature';
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ import { SettingTile } from '$components/setting-tile';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import { usePowerLevels } from '$hooks/usePowerLevels';
|
||||
|
||||
import { suffixRename } from '$utils/common';
|
||||
@@ -37,6 +38,11 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { SequenceCardStyle } from '$features/common-settings/styles.css';
|
||||
import { CustomStateEvent } from '$types/matrix/room';
|
||||
|
||||
function PackAvatarImage({ url }: { url: string }) {
|
||||
const resolved = useRenderableMediaUrl(url);
|
||||
return <AvatarImage style={{ objectFit: 'contain' }} src={resolved ?? url} />;
|
||||
}
|
||||
|
||||
type CreatePackTileProps = {
|
||||
packs: ImagePack[];
|
||||
roomId: string;
|
||||
@@ -233,7 +239,7 @@ export function RoomPacks({ onViewPack }: Readonly<RoomPacksProps>) {
|
||||
))}
|
||||
<Avatar size="300" radii="300">
|
||||
{avatarUrl ? (
|
||||
<AvatarImage style={{ objectFit: 'contain' }} src={avatarUrl} />
|
||||
<PackAvatarImage url={avatarUrl} />
|
||||
) : (
|
||||
<AvatarFallback>{composerIcon(Sticker, { weight: 'fill' })}</AvatarFallback>
|
||||
)}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { MouseEventHandler, MouseEvent } from 'react';
|
||||
import { forwardRef, useState, useEffect } from 'react';
|
||||
import { forwardRef, startTransition, useState, useEffect } from 'react';
|
||||
import type { Room } from '$types/matrix-sdk';
|
||||
import { RoomEvent as RoomEventEnum } from '$types/matrix-sdk';
|
||||
import type { RectCords } from 'folds';
|
||||
@@ -359,7 +359,8 @@ export function RoomNavItem({
|
||||
navigateRoom(room.roomId);
|
||||
}
|
||||
} else {
|
||||
navigate(linkPath);
|
||||
// Render the room off the urgent path so the tap doesn't freeze the UI on mount.
|
||||
startTransition(() => navigate(linkPath));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { KeyboardEvent as ReactKeyboardEvent } from 'react';
|
||||
import type { KeyboardEvent as ReactKeyboardEvent, MouseEvent as ReactMouseEvent } from 'react';
|
||||
import { useCallback, useEffect, useMemo } from 'react';
|
||||
import type { Editor } from 'slate';
|
||||
import { Box, config, MenuItem, Text } from 'folds';
|
||||
@@ -92,6 +92,7 @@ export function CommandAutocomplete({
|
||||
onKeyDown={(evt: ReactKeyboardEvent<HTMLButtonElement>) =>
|
||||
onTabPress(evt, () => handleAutocomplete(commandName))
|
||||
}
|
||||
onMouseDown={(evt: ReactMouseEvent<HTMLButtonElement>) => evt.preventDefault()}
|
||||
onClick={() => handleAutocomplete(commandName)}
|
||||
>
|
||||
<Box
|
||||
|
||||
@@ -69,7 +69,13 @@ import type { GifData } from '$components/emoji-board';
|
||||
import { EmojiBoard, EmojiBoardTab } from '$components/emoji-board';
|
||||
import { UseStateProvider } from '$components/UseStateProvider';
|
||||
import type { TUploadContent } from '$utils/matrix';
|
||||
import { encryptFile, getImageInfo, mxcUrlToHttp, toggleReaction } from '$utils/matrix';
|
||||
import {
|
||||
cancelUploadContent,
|
||||
encryptFile,
|
||||
getImageInfo,
|
||||
mxcUrlToHttp,
|
||||
toggleReaction,
|
||||
} from '$utils/matrix';
|
||||
import { useTypingStatusUpdater } from '$hooks/useTypingStatusUpdater';
|
||||
import { useFilePicker } from '$hooks/useFilePicker';
|
||||
import { useFilePasteHandler } from '$hooks/useFilePasteHandler';
|
||||
@@ -86,7 +92,7 @@ import type { UploadBoardImperativeHandlers } from '$components/upload-board';
|
||||
import { UploadBoard, UploadBoardContent, UploadBoardHeader } from '$components/upload-board';
|
||||
import type { Upload, UploadSuccess } from '$state/upload';
|
||||
import { UploadStatus, createUploadFamilyObserverAtom } from '$state/upload';
|
||||
import { getImageUrlBlob, loadImageElement } from '$utils/dom';
|
||||
import { loadImageElementFromMediaUrl } from '$utils/dom';
|
||||
import { safeFile } from '$utils/mimeTypes';
|
||||
import { fulfilledPromiseSettledResult } from '$utils/common';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
@@ -579,7 +585,7 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
const handleCancelUpload = (uploads: Upload[]) => {
|
||||
uploads.forEach((upload) => {
|
||||
if (upload.status === UploadStatus.Loading) {
|
||||
mx.cancelUpload(upload.promise);
|
||||
cancelUploadContent(mx, upload.promise);
|
||||
}
|
||||
});
|
||||
handleRemoveUpload(uploads.map((upload) => upload.file));
|
||||
@@ -1345,10 +1351,8 @@ export const RoomInput = forwardRef<HTMLDivElement, RoomInputProps>(
|
||||
const stickerUrl = mxcUrlToHttp(mx, mxc, useAuthentication);
|
||||
if (!stickerUrl) return;
|
||||
|
||||
const info = getImageInfo(
|
||||
await loadImageElement(stickerUrl),
|
||||
await getImageUrlBlob(stickerUrl)
|
||||
);
|
||||
const { blob, image } = await loadImageElementFromMediaUrl(stickerUrl);
|
||||
const info = getImageInfo(image, blob);
|
||||
|
||||
const content: StickerEventContent & ReplyEventContent & IContent & IGenericMSC4459 = {
|
||||
body: label,
|
||||
|
||||
@@ -35,6 +35,7 @@ export const TimelineFloat = recipe({
|
||||
export type TimelineFloatVariants = RecipeVariants<typeof TimelineFloat>;
|
||||
export const messageList = style({
|
||||
overflowY: 'scroll',
|
||||
touchAction: 'pan-y',
|
||||
scrollbarGutter: 'stable',
|
||||
overflowAnchor: 'none',
|
||||
|
||||
|
||||
@@ -19,7 +19,6 @@ import { useRoomPermissions } from '$hooks/useRoomPermissions';
|
||||
import { useRoomCreators } from '$hooks/useRoomCreators';
|
||||
import { ScreenSize, useScreenSizeContext } from '$hooks/useScreenSize';
|
||||
import { SwipeableChatWrapper } from '$components/SwipeableChatWrapper';
|
||||
import { BackRouteHandler } from '$components/BackRouteHandler';
|
||||
import { useOpenRoomSettings } from '$state/hooks/roomSettings';
|
||||
import { useSpaceOptionally } from '$hooks/useSpace';
|
||||
import { RoomSettingsPage } from '$state/roomSettings';
|
||||
@@ -139,70 +138,66 @@ export function RoomView({ eventId }: { eventId?: string }) {
|
||||
const showCallView = !room.isCallRoom() && (callMembers.length > 0 || isJoinedInThisRoom);
|
||||
|
||||
return (
|
||||
<BackRouteHandler>
|
||||
{(onBack) => (
|
||||
<Page ref={roomViewRef}>
|
||||
<SwipeableChatWrapper onOpenSidebar={onBack} onOpenMembers={handleOpenMembers}>
|
||||
<Box grow="Yes" direction="Column">
|
||||
{showCallView && (
|
||||
<Box shrink="No" style={{ width: '100%', position: 'relative' }}>
|
||||
<CallView resizable />
|
||||
</Box>
|
||||
)}
|
||||
<RoomTimeline
|
||||
key={roomId}
|
||||
room={room}
|
||||
eventId={eventId}
|
||||
editor={editor}
|
||||
onEditorReset={handleResetEditor}
|
||||
onEditLastMessageRef={editLastMessageRef}
|
||||
<Page ref={roomViewRef}>
|
||||
<SwipeableChatWrapper onOpenMembers={handleOpenMembers}>
|
||||
<Box grow="Yes" direction="Column">
|
||||
{showCallView && (
|
||||
<Box shrink="No" style={{ width: '100%', position: 'relative' }}>
|
||||
<CallView resizable />
|
||||
</Box>
|
||||
)}
|
||||
<RoomTimeline
|
||||
key={roomId}
|
||||
room={room}
|
||||
eventId={eventId}
|
||||
editor={editor}
|
||||
onEditorReset={handleResetEditor}
|
||||
onEditLastMessageRef={editLastMessageRef}
|
||||
/>
|
||||
<div style={{ position: 'relative', flexShrink: 0 }}>
|
||||
<RoomViewTyping room={room} />
|
||||
</div>
|
||||
<GlobalModalManager />
|
||||
</Box>
|
||||
<Box shrink="No" direction="Column">
|
||||
{canMessage && delayedEventsSupported && (
|
||||
<ScheduledMessagesList room={room} onEditMessage={handleEditMessage} />
|
||||
)}
|
||||
<div style={{ padding: `0 ${config.space.S400}` }}>
|
||||
{tombstoneEvent ? (
|
||||
<RoomTombstone
|
||||
roomId={roomId}
|
||||
body={tombstoneEvent.getContent().body}
|
||||
replacementRoomId={tombstoneEvent.getContent().replacement_room}
|
||||
/>
|
||||
<div style={{ position: 'relative', flexShrink: 0 }}>
|
||||
<RoomViewTyping room={room} />
|
||||
</div>
|
||||
<GlobalModalManager />
|
||||
</Box>
|
||||
<Box shrink="No" direction="Column">
|
||||
{canMessage && delayedEventsSupported && (
|
||||
<ScheduledMessagesList room={room} onEditMessage={handleEditMessage} />
|
||||
)}
|
||||
<div style={{ padding: `0 ${config.space.S400}` }}>
|
||||
{tombstoneEvent ? (
|
||||
<RoomTombstone
|
||||
) : (
|
||||
<>
|
||||
{canMessage && (
|
||||
<RoomInput
|
||||
key={`${roomId}-${editorResetKey}`}
|
||||
room={room}
|
||||
editor={editor}
|
||||
roomId={roomId}
|
||||
body={tombstoneEvent.getContent().body}
|
||||
replacementRoomId={tombstoneEvent.getContent().replacement_room}
|
||||
fileDropContainerRef={roomViewRef}
|
||||
ref={roomInputRef}
|
||||
onEditLastMessage={() => editLastMessageRef.current?.()}
|
||||
/>
|
||||
) : (
|
||||
<>
|
||||
{canMessage && (
|
||||
<RoomInput
|
||||
key={`${roomId}-${editorResetKey}`}
|
||||
room={room}
|
||||
editor={editor}
|
||||
roomId={roomId}
|
||||
fileDropContainerRef={roomViewRef}
|
||||
ref={roomInputRef}
|
||||
onEditLastMessage={() => editLastMessageRef.current?.()}
|
||||
/>
|
||||
)}
|
||||
{!canMessage && (
|
||||
<RoomInputPlaceholder
|
||||
style={{ padding: config.space.S200 }}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
>
|
||||
<Text align="Center">You do not have permission to post in this room</Text>
|
||||
</RoomInputPlaceholder>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{hideReads ? <RoomViewFollowingPlaceholder /> : <RoomViewFollowing room={room} />}
|
||||
</div>
|
||||
</Box>
|
||||
</SwipeableChatWrapper>
|
||||
</Page>
|
||||
)}
|
||||
</BackRouteHandler>
|
||||
{!canMessage && (
|
||||
<RoomInputPlaceholder
|
||||
style={{ padding: config.space.S200 }}
|
||||
alignItems="Center"
|
||||
justifyContent="Center"
|
||||
>
|
||||
<Text align="Center">You do not have permission to post in this room</Text>
|
||||
</RoomInputPlaceholder>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{hideReads ? <RoomViewFollowingPlaceholder /> : <RoomViewFollowing room={room} />}
|
||||
</div>
|
||||
</Box>
|
||||
</SwipeableChatWrapper>
|
||||
</Page>
|
||||
);
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
import { ClipboardIcon, MapPinAreaIcon, MapPinLineIcon } from '@phosphor-icons/react';
|
||||
import { chipIcon, composerIcon, Warning, X } from '$components/icons/phosphor';
|
||||
import { stopPropagation } from '$utils/keyboard';
|
||||
import { readClipboardText } from '$utils/dom';
|
||||
import type { IContent, MatrixClient, Room } from 'matrix-js-sdk';
|
||||
import * as css from './LocationDialog.css';
|
||||
import type { IReplyDraft } from '$state/room/roomInputDrafts';
|
||||
@@ -195,8 +196,7 @@ export function LocationDialog({
|
||||
}
|
||||
|
||||
function getClipboard() {
|
||||
navigator.clipboard
|
||||
.readText()
|
||||
readClipboardText()
|
||||
.then((result: string) => {
|
||||
const coords = filterLocationString(result);
|
||||
storeLocation(coords);
|
||||
|
||||
@@ -50,7 +50,6 @@ import { mobileOrTablet } from '$utils/user-agent';
|
||||
import { useUserProfile } from '$hooks/useUserProfile';
|
||||
import { useRoomMemberHydration } from '$hooks/useRoomMemberHydration';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { useBlobCache } from '$hooks/useBlobCache';
|
||||
import { filterPronounsByLanguage, getParsedPronouns } from '$utils/pronouns';
|
||||
import type { PronounSet } from '$utils/pronouns';
|
||||
import { useMentionClickHandler } from '$hooks/useMentionClickHandler';
|
||||
@@ -60,6 +59,7 @@ import { MessageEditor } from './MessageEditor';
|
||||
import * as css from './styles.css';
|
||||
import { modalAtom, ModalType } from '$state/modal';
|
||||
import { OptionQuickMenu } from '$components/message/modals/Options';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
|
||||
export type ReactionHandler = (keyOrMxc: string, shortcode: string) => void;
|
||||
|
||||
@@ -474,7 +474,7 @@ function MessageInternal(
|
||||
return mxc ? mxcUrlToHttp(mx, mxc, useAuthentication, 48, 48, 'crop') : undefined;
|
||||
}, [pmp, memberAvatarMxc, profile.avatarUrl, mx, useAuthentication]);
|
||||
|
||||
const cachedAvatar = useBlobCache(avatarUrl ?? undefined);
|
||||
const cachedAvatar = useRenderableMediaUrl(avatarUrl ?? undefined);
|
||||
|
||||
// UI State
|
||||
const [isDesktopHover, setIsDesktopHover] = useState(false);
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
getThumbnailContent,
|
||||
getVideoInfo,
|
||||
mxcUrlToHttp,
|
||||
uploadContentToServer,
|
||||
} from '$utils/matrix';
|
||||
import { mimeTypeToExt } from '$utils/mimeTypes';
|
||||
import type { TUploadItem } from '$state/room/roomInputDrafts';
|
||||
@@ -43,7 +44,7 @@ const generateThumbnailContent = async (
|
||||
const thumbnailFile = encThumbData?.file ?? thumbnail;
|
||||
if (!thumbnailFile) throw new Error('Can not create thumbnail!');
|
||||
|
||||
const data = await mx.uploadContent(thumbnailFile);
|
||||
const data = await uploadContentToServer(mx, thumbnailFile);
|
||||
const thumbMxc = data?.content_uri;
|
||||
if (!thumbMxc) throw new Error('Failed when uploading thumbnail!');
|
||||
const thumbnailContent = getThumbnailContent({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useMemo, useState } from 'react';
|
||||
import type { ComponentType } from 'react';
|
||||
import type { IconProps } from '@phosphor-icons/react';
|
||||
import { DesktopIcon, type IconProps } from '@phosphor-icons/react';
|
||||
import {
|
||||
Avatar,
|
||||
Box,
|
||||
@@ -61,6 +61,7 @@ import { settingsHeader } from './styles.css';
|
||||
import { useSettingsFocus } from './useSettingsFocus';
|
||||
import { SettingsLinkProvider } from './SettingsLinkContext';
|
||||
import { useSettingsLinkBaseUrl } from './useSettingsLinkBaseUrl';
|
||||
import { Desktop } from './desktop';
|
||||
|
||||
export enum SettingsPages {
|
||||
GeneralPage,
|
||||
@@ -68,6 +69,7 @@ export enum SettingsPages {
|
||||
PerMessageProfilesPage,
|
||||
NotificationPage,
|
||||
DevicesPage,
|
||||
DesktopPage,
|
||||
EmojisStickersPage,
|
||||
CosmeticsPage,
|
||||
DeveloperToolsPage,
|
||||
@@ -95,6 +97,7 @@ export const settingsMenuIcons: Record<
|
||||
appearance: { icon: Palette },
|
||||
notifications: { icon: Bell },
|
||||
devices: { icon: DevicesIcon },
|
||||
desktop: { icon: DesktopIcon },
|
||||
emojis: { icon: Smiley },
|
||||
'developer-tools': { icon: Terminal },
|
||||
experimental: { icon: Flask },
|
||||
@@ -108,6 +111,7 @@ const settingsPageToSectionId: Record<SettingsPages, SettingsSectionId> = {
|
||||
[SettingsPages.PerMessageProfilesPage]: 'persona',
|
||||
[SettingsPages.NotificationPage]: 'notifications',
|
||||
[SettingsPages.DevicesPage]: 'devices',
|
||||
[SettingsPages.DesktopPage]: 'desktop',
|
||||
[SettingsPages.EmojisStickersPage]: 'emojis',
|
||||
[SettingsPages.CosmeticsPage]: 'appearance',
|
||||
[SettingsPages.DeveloperToolsPage]: 'developer-tools',
|
||||
@@ -123,6 +127,7 @@ const settingsSectionIdToPage: Record<SettingsSectionId, SettingsPages> = {
|
||||
appearance: SettingsPages.CosmeticsPage,
|
||||
notifications: SettingsPages.NotificationPage,
|
||||
devices: SettingsPages.DevicesPage,
|
||||
desktop: SettingsPages.DesktopPage,
|
||||
emojis: SettingsPages.EmojisStickersPage,
|
||||
'developer-tools': SettingsPages.DeveloperToolsPage,
|
||||
experimental: SettingsPages.ExperimentalPage,
|
||||
@@ -132,7 +137,7 @@ const settingsSectionIdToPage: Record<SettingsSectionId, SettingsPages> = {
|
||||
|
||||
const settingsSectionComponents: Record<
|
||||
SettingsSectionId,
|
||||
(props: { requestBack?: () => void; requestClose: () => void }) => JSX.Element
|
||||
(props: { requestBack?: () => void; requestClose: () => void }) => JSX.Element | null
|
||||
> = {
|
||||
general: General,
|
||||
account: Account,
|
||||
@@ -140,6 +145,7 @@ const settingsSectionComponents: Record<
|
||||
appearance: Cosmetics,
|
||||
notifications: Notifications,
|
||||
devices: Devices,
|
||||
desktop: Desktop,
|
||||
emojis: EmojisStickers,
|
||||
'developer-tools': DeveloperTools,
|
||||
experimental: Experimental,
|
||||
|
||||
@@ -617,7 +617,9 @@ describe('SettingsRoute', () => {
|
||||
getSettingsPath('notifications')
|
||||
)
|
||||
);
|
||||
expect(screen.getByRole('heading', { name: 'Notifications section' })).toBeInTheDocument();
|
||||
expect(
|
||||
await screen.findByRole('heading', { name: 'Notifications section' })
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not push history when the active section is reselected', async () => {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { type ChangeEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTimeoutToggle } from '$hooks/useTimeoutToggle';
|
||||
import { copyToClipboard, downloadTextFile } from '$utils/dom';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import {
|
||||
Box,
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type * as Folds from 'folds';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
import { ScreenSize, ScreenSizeProvider } from '$hooks/useScreenSize';
|
||||
import { Desktop } from './Desktop';
|
||||
|
||||
const {
|
||||
mockUseDesktopSetting,
|
||||
mockUseDesktopSettingsReady,
|
||||
mockUseDesktopRuntimeState,
|
||||
mockUseDesktopSettingsSyncing,
|
||||
} = vi.hoisted(() => ({
|
||||
mockUseDesktopSetting: vi.fn<
|
||||
(key: 'closeToBackgroundOnClose' | 'showSystemTrayIcon') => readonly [boolean, () => void]
|
||||
>((key) => {
|
||||
if (key === 'closeToBackgroundOnClose') return [true, vi.fn<() => void>()] as const;
|
||||
return [true, vi.fn<() => void>()] as const;
|
||||
}),
|
||||
mockUseDesktopSettingsReady: vi.fn<() => boolean>(() => true),
|
||||
mockUseDesktopSettingsSyncing: vi.fn<() => boolean>(() => false),
|
||||
mockUseDesktopRuntimeState: vi.fn<() => { trayAvailable: boolean }>(() => ({
|
||||
trayAvailable: false,
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/api/core', () => ({
|
||||
isTauri: () => true,
|
||||
}));
|
||||
|
||||
vi.mock('@tauri-apps/plugin-os', () => ({
|
||||
type: vi.fn<() => string>(() => 'linux'),
|
||||
}));
|
||||
|
||||
vi.mock('$state/hooks/desktopSettings', () => ({
|
||||
useDesktopSetting: mockUseDesktopSetting,
|
||||
useDesktopSettingsReady: mockUseDesktopSettingsReady,
|
||||
useDesktopSettingsSyncing: mockUseDesktopSettingsSyncing,
|
||||
useDesktopRuntimeState: mockUseDesktopRuntimeState,
|
||||
}));
|
||||
|
||||
vi.mock('folds', async () => {
|
||||
const actual = await vi.importActual<typeof Folds>('folds');
|
||||
return {
|
||||
...actual,
|
||||
Switch: ({
|
||||
value,
|
||||
onChange,
|
||||
disabled,
|
||||
'aria-label': ariaLabel,
|
||||
}: {
|
||||
value: boolean;
|
||||
onChange: (nextValue: boolean) => void;
|
||||
disabled?: boolean;
|
||||
'aria-label'?: string;
|
||||
}) => (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-label={ariaLabel}
|
||||
aria-checked={value}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(!value)}
|
||||
/>
|
||||
),
|
||||
};
|
||||
});
|
||||
|
||||
describe('Desktop', () => {
|
||||
const renderDesktop = () =>
|
||||
render(
|
||||
<ScreenSizeProvider value={ScreenSize.Desktop}>
|
||||
<Desktop requestClose={vi.fn<() => void>()} />
|
||||
</ScreenSizeProvider>
|
||||
);
|
||||
|
||||
it('renders explicit close behavior and tray settings', () => {
|
||||
mockUseDesktopRuntimeState.mockReturnValueOnce({
|
||||
trayAvailable: true,
|
||||
});
|
||||
|
||||
const { container } = renderDesktop();
|
||||
|
||||
expect(screen.getByText('Close button keeps Sable running')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(
|
||||
'When enabled, closing the window keeps Sable running instead of exiting. If the tray icon is enabled and available, Sable stays in the system tray. Otherwise it continues running in the background.'
|
||||
)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByText('Show system tray icon')).toBeInTheDocument();
|
||||
expect(
|
||||
screen.getByText(
|
||||
'Show a system tray icon while Sable is running. Disable this if you want Sable to stay available without a tray icon.'
|
||||
)
|
||||
).toBeInTheDocument();
|
||||
expect(container.getElementsByClassName(SequenceCardStyle)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('shows fallback copy while the tray icon is enabled but unavailable', () => {
|
||||
renderDesktop();
|
||||
|
||||
expect(
|
||||
screen.getByText(
|
||||
'System tray is unavailable on this system. Sable can still keep running in the background without it.'
|
||||
)
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByRole('switch', { name: 'show-system-tray-icon' })).toBeDisabled();
|
||||
});
|
||||
|
||||
it('does not show fallback copy while tray availability is still syncing', () => {
|
||||
mockUseDesktopSettingsSyncing.mockReturnValueOnce(true);
|
||||
|
||||
renderDesktop();
|
||||
|
||||
expect(
|
||||
screen.queryByText(
|
||||
'System tray is unavailable on this system. Sable can still keep running in the background without it.'
|
||||
)
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides the tray-unavailable note when the tray is available', () => {
|
||||
mockUseDesktopRuntimeState.mockReturnValueOnce({
|
||||
trayAvailable: true,
|
||||
});
|
||||
|
||||
renderDesktop();
|
||||
|
||||
expect(
|
||||
screen.queryByText(
|
||||
'System tray is unavailable on this system. Sable can still keep running in the background without it.'
|
||||
)
|
||||
).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { Box, Text, Scroll, Switch, color } from 'folds';
|
||||
import { PageContent } from '$components/page';
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import {
|
||||
useDesktopRuntimeState,
|
||||
useDesktopSetting,
|
||||
useDesktopSettingsReady,
|
||||
useDesktopSettingsSyncing,
|
||||
} from '$state/hooks/desktopSettings';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
import { SettingsSectionPage } from '../SettingsSectionPage';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
|
||||
type DesktopProps = {
|
||||
requestBack?: () => void;
|
||||
requestClose: () => void;
|
||||
};
|
||||
|
||||
export function Desktop({ requestBack, requestClose }: DesktopProps) {
|
||||
const ready = useDesktopSettingsReady();
|
||||
const syncing = useDesktopSettingsSyncing();
|
||||
const runtimeState = useDesktopRuntimeState();
|
||||
const [closeToBackgroundOnClose, setCloseToBackgroundOnClose] = useDesktopSetting(
|
||||
'closeToBackgroundOnClose'
|
||||
);
|
||||
const [showSystemTrayIcon, setShowSystemTrayIcon] = useDesktopSetting('showSystemTrayIcon');
|
||||
|
||||
if (!isTauri() || !ready) return null;
|
||||
|
||||
let type = osType();
|
||||
if (type === 'android' || type === 'ios') return null;
|
||||
|
||||
const trayFallback = showSystemTrayIcon && !runtimeState.trayAvailable && !syncing;
|
||||
|
||||
return (
|
||||
<SettingsSectionPage title="Desktop" requestBack={requestBack} requestClose={requestClose}>
|
||||
<Box grow="Yes">
|
||||
<Scroll hideTrack visibility="Hover">
|
||||
<PageContent>
|
||||
<Box direction="Column" gap="700">
|
||||
<Box direction="Column" gap="100">
|
||||
<Text size="L400">Window</Text>
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Close button keeps Sable running"
|
||||
focusId="close-to-background-on-close"
|
||||
description="When enabled, closing the window keeps Sable running instead of exiting. If the tray icon is enabled and available, Sable stays in the system tray. Otherwise it continues running in the background."
|
||||
after={
|
||||
<Switch
|
||||
aria-label="close-to-background-on-close"
|
||||
value={closeToBackgroundOnClose}
|
||||
onChange={setCloseToBackgroundOnClose}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
{type !== 'macos' && (
|
||||
<SequenceCard
|
||||
className={SequenceCardStyle}
|
||||
variant="SurfaceVariant"
|
||||
direction="Column"
|
||||
gap="400"
|
||||
>
|
||||
<SettingTile
|
||||
title="Show system tray icon"
|
||||
focusId="show-system-tray-icon"
|
||||
description={
|
||||
trayFallback ? (
|
||||
<Text as="span" style={{ color: color.Warning.Main }} size="T200">
|
||||
System tray is unavailable on this system. Sable can still keep running
|
||||
in the background without it.
|
||||
</Text>
|
||||
) : (
|
||||
'Show a system tray icon while Sable is running. Disable this if you want Sable to stay available without a tray icon.'
|
||||
)
|
||||
}
|
||||
after={
|
||||
<Switch
|
||||
aria-label="show-system-tray-icon"
|
||||
value={!trayFallback ? showSystemTrayIcon : false}
|
||||
disabled={trayFallback}
|
||||
onChange={setShowSystemTrayIcon}
|
||||
/>
|
||||
}
|
||||
/>
|
||||
</SequenceCard>
|
||||
)}
|
||||
</Box>
|
||||
</Box>
|
||||
</PageContent>
|
||||
</Scroll>
|
||||
</Box>
|
||||
</SettingsSectionPage>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './Desktop';
|
||||
@@ -8,6 +8,7 @@ import { SequenceCard } from '$components/sequence-card';
|
||||
import { debugLoggerEnabledAtom, debugLogsAtom, clearDebugLogsAtom } from '$state/debugLogger';
|
||||
import type { LogEntry, LogLevel, LogCategory } from '$utils/debugLogger';
|
||||
import { getDebugLogger } from '$utils/debugLogger';
|
||||
import { copyToClipboard } from '$utils/dom';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
|
||||
const formatTimestamp = (timestamp: number): string => {
|
||||
@@ -267,7 +268,7 @@ export function DebugLogViewer() {
|
||||
jsonData = debugLogger.exportLogs();
|
||||
}
|
||||
|
||||
navigator.clipboard.writeText(jsonData);
|
||||
void copyToClipboard(jsonData);
|
||||
},
|
||||
[filterLevel, filterCategory]
|
||||
);
|
||||
|
||||
@@ -2,7 +2,7 @@ import type { FormEventHandler } from 'react';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { Box, Button, color, Spinner, Text, toRem } from 'folds';
|
||||
import { ArrowRight, CaretDown, CaretUp, File, menuIcon, X } from '$components/icons/phosphor';
|
||||
import FileSaver from 'file-saver';
|
||||
import { saveFileToDevice } from '$utils/download';
|
||||
import { SequenceCard } from '$components/sequence-card';
|
||||
import { SettingTile } from '$components/setting-tile';
|
||||
import { PasswordInput } from '$components/password-input';
|
||||
@@ -44,7 +44,7 @@ function ExportKeys() {
|
||||
const blob = new Blob([encKeys], {
|
||||
type: 'text/plain;charset=us-ascii',
|
||||
});
|
||||
FileSaver.saveAs(blob, 'cinny-keys.txt');
|
||||
await saveFileToDevice(blob, 'cinny-keys.txt');
|
||||
},
|
||||
[mx]
|
||||
)
|
||||
|
||||
@@ -7,6 +7,7 @@ import { ImagePack, ImageUsage } from '$plugins/custom-emoji';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { mxcUrlToHttp } from '$utils/matrix';
|
||||
import { useMediaAuthentication } from '$hooks/useMediaAuthentication';
|
||||
import { useRenderableMediaUrl } from '$hooks/useRenderableMediaUrl';
|
||||
import { SequenceCardStyle } from '$features/settings/styles.css';
|
||||
|
||||
type UserPackProps = {
|
||||
@@ -19,6 +20,7 @@ export function UserPack({ onViewPack }: UserPackProps) {
|
||||
const userPack = useUserImagePack();
|
||||
const avatarMxc = userPack?.getAvatarUrl(ImageUsage.Emoticon);
|
||||
const avatarUrl = avatarMxc ? mxcUrlToHttp(mx, avatarMxc, useAuthentication) : undefined;
|
||||
const resolvedAvatarUrl = useRenderableMediaUrl(avatarUrl ?? undefined);
|
||||
|
||||
const handleView = () => {
|
||||
if (userPack) {
|
||||
@@ -45,7 +47,10 @@ export function UserPack({ onViewPack }: UserPackProps) {
|
||||
before={
|
||||
<Avatar size="300" radii="300">
|
||||
{avatarUrl ? (
|
||||
<AvatarImage style={{ objectFit: 'contain' }} src={avatarUrl} />
|
||||
<AvatarImage
|
||||
style={{ objectFit: 'contain' }}
|
||||
src={resolvedAvatarUrl ?? avatarUrl}
|
||||
/>
|
||||
) : (
|
||||
<AvatarFallback>{composerIcon(Sticker, { weight: 'fill' })}</AvatarFallback>
|
||||
)}
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
disableNativePush,
|
||||
enableNativePush,
|
||||
ensureNativePushRegistered,
|
||||
isNativePushPermissionGranted,
|
||||
requestNativePushPermission,
|
||||
} from './NativePushNotifications';
|
||||
import * as NativePushNotifications from './NativePushNotifications';
|
||||
|
||||
const nativePushApi = vi.hoisted(() => ({
|
||||
isPermissionGranted: vi.fn<() => Promise<boolean>>(),
|
||||
requestPermission: vi.fn<() => Promise<string>>(),
|
||||
registerForPushNotifications: vi.fn<() => Promise<string>>(),
|
||||
unregisterForPushNotifications: vi.fn<() => Promise<void>>(),
|
||||
}));
|
||||
|
||||
const getNativePushNotificationsApi = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<typeof nativePushApi>>().mockResolvedValue(nativePushApi)
|
||||
);
|
||||
|
||||
const matrixClient = vi.hoisted(() => ({
|
||||
setPusher: vi.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
getDeviceId: vi.fn<() => string>(() => 'DEVICE'),
|
||||
getDevice: vi
|
||||
.fn<() => Promise<{ display_name: string }>>()
|
||||
.mockResolvedValue({ display_name: 'Pixel' }),
|
||||
getPushers: vi
|
||||
.fn<() => Promise<{ pushers: Array<unknown> }>>()
|
||||
.mockResolvedValue({ pushers: [] }),
|
||||
}));
|
||||
|
||||
const nativePushClientConfig = {
|
||||
pushNotificationDetails: {
|
||||
nativePushAppID: 'moe.sable.mobile',
|
||||
pushNotifyUrl: 'https://sygnal.example/_matrix/push/v1/notify',
|
||||
},
|
||||
} as const;
|
||||
|
||||
vi.mock('./NativePushNotificationsApiClient', () => ({
|
||||
getNativePushNotificationsApi,
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('native push permission flow', () => {
|
||||
it('does not expose the test-only api seam', () => {
|
||||
expect('setNativePushNotificationsApiForTesting' in NativePushNotifications).toBe(false);
|
||||
});
|
||||
|
||||
it('reports false when native permission is not yet granted', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(false);
|
||||
|
||||
await expect(isNativePushPermissionGranted()).resolves.toBe(false);
|
||||
});
|
||||
|
||||
it('forwards a permission request explicitly', async () => {
|
||||
nativePushApi.requestPermission.mockResolvedValue('granted');
|
||||
|
||||
await expect(requestNativePushPermission()).resolves.toBe('granted');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ensureNativePushRegistered', () => {
|
||||
it('registers immediately when permission is already granted', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
nativePushApi.registerForPushNotifications.mockResolvedValue('native-token');
|
||||
|
||||
await expect(ensureNativePushRegistered()).resolves.toEqual({
|
||||
permission: 'granted',
|
||||
token: 'native-token',
|
||||
});
|
||||
expect(nativePushApi.requestPermission).not.toHaveBeenCalled();
|
||||
expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('requests permission before registering and returns a token on grant', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(false);
|
||||
nativePushApi.requestPermission.mockResolvedValue('granted');
|
||||
nativePushApi.registerForPushNotifications.mockResolvedValue('native-token');
|
||||
|
||||
await expect(ensureNativePushRegistered()).resolves.toEqual({
|
||||
permission: 'granted',
|
||||
token: 'native-token',
|
||||
});
|
||||
expect(nativePushApi.requestPermission).toHaveBeenCalledOnce();
|
||||
expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('returns denied without registering when permission is denied', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(false);
|
||||
nativePushApi.requestPermission.mockResolvedValue('denied');
|
||||
|
||||
await expect(ensureNativePushRegistered()).resolves.toEqual({
|
||||
permission: 'denied',
|
||||
token: null,
|
||||
});
|
||||
expect(nativePushApi.registerForPushNotifications).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('preserves a default permission result from the permission request', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(false);
|
||||
nativePushApi.requestPermission.mockResolvedValue('default');
|
||||
|
||||
await expect(ensureNativePushRegistered()).resolves.toEqual({
|
||||
permission: 'default',
|
||||
token: null,
|
||||
});
|
||||
expect(nativePushApi.registerForPushNotifications).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('native push pusher registration', () => {
|
||||
it('registers a Matrix pusher with the native device token', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
nativePushApi.registerForPushNotifications.mockResolvedValue('native-token');
|
||||
|
||||
await expect(enableNativePush(matrixClient as never, nativePushClientConfig)).resolves.toBe(
|
||||
'native-token'
|
||||
);
|
||||
expect(localStorage.getItem('nativePushToken')).toBe('native-token');
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'http',
|
||||
app_id: 'moe.sable.mobile',
|
||||
pushkey: 'native-token',
|
||||
data: expect.objectContaining({
|
||||
url: 'https://sygnal.example/_matrix/push/v1/notify',
|
||||
format: 'event_id_only',
|
||||
}),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('rejects native push enablement when the app id is missing', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
nativePushApi.registerForPushNotifications.mockResolvedValue('native-token');
|
||||
|
||||
await expect(
|
||||
enableNativePush(matrixClient as never, {
|
||||
pushNotificationDetails: {
|
||||
pushNotifyUrl: 'https://sygnal.example/_matrix/push/v1/notify',
|
||||
},
|
||||
})
|
||||
).rejects.toThrow('nativePushAppID');
|
||||
});
|
||||
|
||||
it('removes native pushers and unregisters the platform token', async () => {
|
||||
localStorage.setItem('nativePushToken', 'native-token');
|
||||
|
||||
await expect(
|
||||
disableNativePush(matrixClient as never, nativePushClientConfig)
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: null,
|
||||
app_id: 'moe.sable.mobile',
|
||||
pushkey: 'native-token',
|
||||
})
|
||||
);
|
||||
expect(nativePushApi.unregisterForPushNotifications).toHaveBeenCalledOnce();
|
||||
expect(localStorage.getItem('nativePushToken')).toBeNull();
|
||||
});
|
||||
|
||||
it('recovers the current token before removing the Matrix pusher when local storage is empty', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
nativePushApi.registerForPushNotifications.mockResolvedValue('native-token');
|
||||
|
||||
await expect(
|
||||
disableNativePush(matrixClient as never, nativePushClientConfig)
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(nativePushApi.registerForPushNotifications).toHaveBeenCalledOnce();
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: null,
|
||||
app_id: 'moe.sable.mobile',
|
||||
pushkey: 'native-token',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to removing current-device pushers when the token cannot be recovered', async () => {
|
||||
nativePushApi.isPermissionGranted.mockResolvedValue(false);
|
||||
matrixClient.getPushers.mockResolvedValue({
|
||||
pushers: [
|
||||
{
|
||||
app_id: 'moe.sable.mobile',
|
||||
pushkey: 'stale-native-token',
|
||||
device_display_name: 'Pixel',
|
||||
kind: 'http',
|
||||
},
|
||||
{
|
||||
app_id: 'moe.sable.mobile',
|
||||
pushkey: 'other-device-token',
|
||||
device_display_name: 'Other Phone',
|
||||
kind: 'http',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await expect(
|
||||
disableNativePush(matrixClient as never, nativePushClientConfig)
|
||||
).resolves.toBeUndefined();
|
||||
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledTimes(1);
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: null,
|
||||
app_id: 'moe.sable.mobile',
|
||||
pushkey: 'stale-native-token',
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import type { IPusherRequest, MatrixClient } from '$types/matrix-sdk';
|
||||
import type { ClientConfig } from '$hooks/useClientConfig';
|
||||
import { getNativePushNotificationsApi } from './NativePushNotificationsApiClient';
|
||||
|
||||
const NATIVE_PUSH_TOKEN_STORAGE_KEY = 'nativePushToken';
|
||||
|
||||
export type NativePushRegistrationResult =
|
||||
| {
|
||||
permission: 'granted';
|
||||
token: string;
|
||||
}
|
||||
| {
|
||||
permission: 'default' | 'denied';
|
||||
token: null;
|
||||
};
|
||||
|
||||
export type { NativePushNotificationsApi } from './NativePushNotificationsApiClient';
|
||||
|
||||
function storeNativePushToken(token: string): void {
|
||||
localStorage.setItem(NATIVE_PUSH_TOKEN_STORAGE_KEY, token);
|
||||
}
|
||||
|
||||
function getStoredNativePushToken(): string | null {
|
||||
return localStorage.getItem(NATIVE_PUSH_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
function clearStoredNativePushToken(): void {
|
||||
localStorage.removeItem(NATIVE_PUSH_TOKEN_STORAGE_KEY);
|
||||
}
|
||||
|
||||
function getNativePushAppId(clientConfig: ClientConfig): string {
|
||||
const appId = clientConfig.pushNotificationDetails?.nativePushAppID;
|
||||
if (!appId) {
|
||||
throw new Error('Native push requires pushNotificationDetails.nativePushAppID in config.json.');
|
||||
}
|
||||
return appId;
|
||||
}
|
||||
|
||||
function getPushGatewayUrl(clientConfig: ClientConfig): string {
|
||||
const pushGatewayUrl = clientConfig.pushNotificationDetails?.pushNotifyUrl;
|
||||
if (!pushGatewayUrl) {
|
||||
throw new Error('Native push requires pushNotificationDetails.pushNotifyUrl in config.json.');
|
||||
}
|
||||
return pushGatewayUrl;
|
||||
}
|
||||
|
||||
export async function isNativePushPermissionGranted(): Promise<boolean> {
|
||||
const api = await getNativePushNotificationsApi();
|
||||
return api.isPermissionGranted();
|
||||
}
|
||||
|
||||
export async function requestNativePushPermission(): Promise<NotificationPermission> {
|
||||
const api = await getNativePushNotificationsApi();
|
||||
return api.requestPermission();
|
||||
}
|
||||
|
||||
export async function ensureNativePushRegistered(): Promise<NativePushRegistrationResult> {
|
||||
const permission = (await isNativePushPermissionGranted())
|
||||
? 'granted'
|
||||
: await requestNativePushPermission();
|
||||
|
||||
if (permission !== 'granted') {
|
||||
return {
|
||||
permission,
|
||||
token: null,
|
||||
};
|
||||
}
|
||||
|
||||
const api = await getNativePushNotificationsApi();
|
||||
const token = await api.registerForPushNotifications();
|
||||
return {
|
||||
permission: 'granted',
|
||||
token,
|
||||
};
|
||||
}
|
||||
|
||||
export async function ensureNativePushUnregistered(): Promise<void> {
|
||||
const api = await getNativePushNotificationsApi();
|
||||
await api.unregisterForPushNotifications();
|
||||
}
|
||||
|
||||
async function getCurrentNativePushToken(): Promise<string | null> {
|
||||
const storedToken = getStoredNativePushToken();
|
||||
if (storedToken) {
|
||||
return storedToken;
|
||||
}
|
||||
|
||||
if (!(await isNativePushPermissionGranted())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const api = await getNativePushNotificationsApi();
|
||||
const token = await api.registerForPushNotifications();
|
||||
if (!token) {
|
||||
return null;
|
||||
}
|
||||
|
||||
storeNativePushToken(token);
|
||||
return token;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function removeNativePushersForCurrentDevice(mx: MatrixClient, appId: string): Promise<void> {
|
||||
const deviceId = mx.getDeviceId() ?? '';
|
||||
if (!deviceId) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentDevice = await mx.getDevice(deviceId);
|
||||
const deviceDisplayName = currentDevice?.display_name;
|
||||
if (!deviceDisplayName) {
|
||||
return;
|
||||
}
|
||||
|
||||
const response = await mx.getPushers();
|
||||
const pushers = response.pushers ?? [];
|
||||
const currentDevicePushers = pushers.filter(
|
||||
(pusher) =>
|
||||
pusher.app_id === appId &&
|
||||
pusher.device_display_name === deviceDisplayName &&
|
||||
pusher.kind === 'http'
|
||||
);
|
||||
|
||||
if (currentDevicePushers.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.allSettled(
|
||||
currentDevicePushers.map((pusher) =>
|
||||
mx.setPusher({
|
||||
kind: null,
|
||||
app_id: pusher.app_id,
|
||||
pushkey: pusher.pushkey,
|
||||
} as unknown as IPusherRequest)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
export async function enableNativePush(
|
||||
mx: MatrixClient,
|
||||
clientConfig: ClientConfig
|
||||
): Promise<string> {
|
||||
const registration = await ensureNativePushRegistered();
|
||||
|
||||
if (registration.permission !== 'granted' || !registration.token) {
|
||||
throw new Error(
|
||||
registration.permission === 'denied'
|
||||
? 'Native push permission denied'
|
||||
: 'Native push permission dismissed'
|
||||
);
|
||||
}
|
||||
|
||||
const appId = getNativePushAppId(clientConfig);
|
||||
const pushGatewayUrl = getPushGatewayUrl(clientConfig);
|
||||
|
||||
await mx.setPusher({
|
||||
kind: 'http',
|
||||
app_id: appId,
|
||||
pushkey: registration.token,
|
||||
app_display_name: 'Sable (Native Push)',
|
||||
device_display_name:
|
||||
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Mobile Device',
|
||||
lang: navigator.language || 'en',
|
||||
data: {
|
||||
url: pushGatewayUrl,
|
||||
format: 'event_id_only',
|
||||
},
|
||||
append: false,
|
||||
} as unknown as IPusherRequest);
|
||||
|
||||
storeNativePushToken(registration.token);
|
||||
return registration.token;
|
||||
}
|
||||
|
||||
export async function disableNativePush(
|
||||
mx: MatrixClient,
|
||||
clientConfig: ClientConfig
|
||||
): Promise<void> {
|
||||
const appId = clientConfig.pushNotificationDetails?.nativePushAppID;
|
||||
if (appId) {
|
||||
const token = await getCurrentNativePushToken();
|
||||
|
||||
if (token) {
|
||||
await mx.setPusher({
|
||||
kind: null,
|
||||
app_id: appId,
|
||||
pushkey: token,
|
||||
} as unknown as IPusherRequest);
|
||||
} else {
|
||||
await removeNativePushersForCurrentDevice(mx, appId);
|
||||
}
|
||||
}
|
||||
|
||||
await ensureNativePushUnregistered();
|
||||
clearStoredNativePushToken();
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
export type NativePushNotificationsApi = {
|
||||
isPermissionGranted: () => Promise<boolean>;
|
||||
requestPermission: () => Promise<NotificationPermission>;
|
||||
registerForPushNotifications: () => Promise<string>;
|
||||
unregisterForPushNotifications: () => Promise<void>;
|
||||
};
|
||||
|
||||
let nativePushNotificationsApiPromise: Promise<NativePushNotificationsApi> | null = null;
|
||||
|
||||
export async function getNativePushNotificationsApi(): Promise<NativePushNotificationsApi> {
|
||||
if (!nativePushNotificationsApiPromise) {
|
||||
nativePushNotificationsApiPromise =
|
||||
import('@choochmeque/tauri-plugin-notifications-api') as unknown as Promise<NativePushNotificationsApi>;
|
||||
}
|
||||
|
||||
return nativePushNotificationsApiPromise;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { mergePushConfig, resolveNotificationTransport } from './NotificationTransport';
|
||||
|
||||
describe('resolveNotificationTransport', () => {
|
||||
it('returns no provider when background push is disabled', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'android',
|
||||
enabled: false,
|
||||
mode: 'auto',
|
||||
unifiedPush: { available: true, status: 'ready' },
|
||||
nativePush: { available: true, status: 'ready' },
|
||||
webPush: { available: true, status: 'ready' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBeNull();
|
||||
expect(result.status).toBe('unavailable');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
it('prefers UnifiedPush on Android auto when it is available', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'android',
|
||||
enabled: true,
|
||||
mode: 'auto',
|
||||
unifiedPush: { available: true, status: 'ready' },
|
||||
nativePush: { available: true, status: 'ready' },
|
||||
webPush: { available: false, status: 'unavailable' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBe('unifiedpush');
|
||||
expect(result.status).toBe('ready');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
it('falls back to native push when UnifiedPush hard-fails', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'android',
|
||||
enabled: true,
|
||||
mode: 'auto',
|
||||
unifiedPush: { available: true, status: 'hard-failed' },
|
||||
nativePush: { available: true, status: 'ready' },
|
||||
webPush: { available: false, status: 'unavailable' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBe('native');
|
||||
expect(result.status).toBe('ready');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
it('does not fall back on temporary UnifiedPush unavailability', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'android',
|
||||
enabled: true,
|
||||
mode: 'auto',
|
||||
unifiedPush: { available: true, status: 'temp-unavailable' },
|
||||
nativePush: { available: true, status: 'ready' },
|
||||
webPush: { available: false, status: 'unavailable' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBe('unifiedpush');
|
||||
expect(result.status).toBe('temp-unavailable');
|
||||
expect(result.degraded).toBe(true);
|
||||
});
|
||||
|
||||
it('does not treat desktop auto mode as web push', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'desktop',
|
||||
enabled: true,
|
||||
mode: 'auto',
|
||||
unifiedPush: { available: false, status: 'unavailable' },
|
||||
nativePush: { available: false, status: 'unavailable' },
|
||||
webPush: { available: true, status: 'ready' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBeNull();
|
||||
expect(result.status).toBe('unavailable');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
it('resolves browser web auto mode to web push when available', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'web',
|
||||
enabled: true,
|
||||
mode: 'auto',
|
||||
unifiedPush: { available: false, status: 'unavailable' },
|
||||
nativePush: { available: false, status: 'unavailable' },
|
||||
webPush: { available: true, status: 'ready' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBe('web');
|
||||
expect(result.status).toBe('ready');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
it('resolves iOS auto mode to native push when available', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'ios',
|
||||
enabled: true,
|
||||
mode: 'auto',
|
||||
unifiedPush: { available: false, status: 'unavailable' },
|
||||
nativePush: { available: true, status: 'ready' },
|
||||
webPush: { available: false, status: 'unavailable' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBe('native');
|
||||
expect(result.status).toBe('ready');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
it('does not resolve explicit native mode when native push is unavailable', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'ios',
|
||||
enabled: true,
|
||||
mode: 'native',
|
||||
unifiedPush: { available: false, status: 'unavailable' },
|
||||
nativePush: { available: false, status: 'unavailable' },
|
||||
webPush: { available: false, status: 'unavailable' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBeNull();
|
||||
expect(result.status).toBe('unavailable');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
|
||||
it('does not resolve explicit web mode when web push is unavailable', () => {
|
||||
const result = resolveNotificationTransport({
|
||||
platform: 'desktop',
|
||||
enabled: true,
|
||||
mode: 'web',
|
||||
unifiedPush: { available: false, status: 'unavailable' },
|
||||
nativePush: { available: false, status: 'unavailable' },
|
||||
webPush: { available: false, status: 'unavailable' },
|
||||
});
|
||||
|
||||
expect(result.provider).toBeNull();
|
||||
expect(result.status).toBe('unavailable');
|
||||
expect(result.degraded).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('mergePushConfig', () => {
|
||||
it('keeps config.json defaults until a user override exists', () => {
|
||||
expect(
|
||||
mergePushConfig(
|
||||
{ unifiedPushGatewayUrl: 'https://up.default.example', unifiedPushAppID: 'moe.sable.up' },
|
||||
{ unifiedPushGatewayUrl: 'https://up.user.example' }
|
||||
)
|
||||
).toEqual({
|
||||
unifiedPushGatewayUrl: 'https://up.user.example',
|
||||
unifiedPushAppID: 'moe.sable.up',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,187 @@
|
||||
export type NotificationTransportMode = 'auto' | 'unifiedpush' | 'native' | 'web';
|
||||
|
||||
export type NotificationTransportProvider = 'unifiedpush' | 'native' | 'web';
|
||||
|
||||
export type NotificationTransportPlatform = 'android' | 'ios' | 'desktop' | 'web';
|
||||
|
||||
export type NotificationTransportStatus =
|
||||
| 'ready'
|
||||
| 'temp-unavailable'
|
||||
| 'hard-failed'
|
||||
| 'unavailable';
|
||||
|
||||
export type PushTransportConfig = {
|
||||
mode?: NotificationTransportMode;
|
||||
unifiedPushGatewayUrl?: string;
|
||||
unifiedPushAppID?: string;
|
||||
unifiedPushDistributor?: string;
|
||||
};
|
||||
|
||||
export type PushTransportOverrides = Omit<PushTransportConfig, 'mode'>;
|
||||
|
||||
export type PushTransportAvailability = {
|
||||
available: boolean;
|
||||
status: NotificationTransportStatus;
|
||||
};
|
||||
|
||||
export type ResolveNotificationTransportInput = {
|
||||
platform: NotificationTransportPlatform;
|
||||
enabled: boolean;
|
||||
mode: NotificationTransportMode;
|
||||
unifiedPush: PushTransportAvailability;
|
||||
nativePush: PushTransportAvailability;
|
||||
webPush: PushTransportAvailability;
|
||||
};
|
||||
|
||||
export type ResolvedNotificationTransport = {
|
||||
provider: NotificationTransportProvider | null;
|
||||
status: NotificationTransportStatus;
|
||||
degraded: boolean;
|
||||
};
|
||||
|
||||
export type {
|
||||
NativePushNotificationsApi,
|
||||
NativePushRegistrationResult,
|
||||
} from './NativePushNotifications';
|
||||
|
||||
export {
|
||||
disableNativePush,
|
||||
enableNativePush,
|
||||
ensureNativePushRegistered,
|
||||
ensureNativePushUnregistered,
|
||||
isNativePushPermissionGranted,
|
||||
requestNativePushPermission,
|
||||
} from './NativePushNotifications';
|
||||
|
||||
export function getSupportedNotificationTransportModes(
|
||||
platform: NotificationTransportPlatform
|
||||
): NotificationTransportMode[] {
|
||||
if (platform === 'android') {
|
||||
return ['auto', 'unifiedpush', 'native'];
|
||||
}
|
||||
|
||||
if (platform === 'ios') {
|
||||
return ['auto', 'native'];
|
||||
}
|
||||
|
||||
if (platform === 'web') {
|
||||
return ['auto', 'web'];
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
export function normalizeNotificationTransportMode(
|
||||
mode: NotificationTransportMode,
|
||||
platform: NotificationTransportPlatform
|
||||
): NotificationTransportMode {
|
||||
const supportedModes = getSupportedNotificationTransportModes(platform);
|
||||
if (supportedModes.includes(mode)) return mode;
|
||||
return supportedModes[0] ?? 'auto';
|
||||
}
|
||||
|
||||
export function resolvePreferredNotificationTransportProvider(
|
||||
mode: NotificationTransportMode,
|
||||
platform: NotificationTransportPlatform
|
||||
): NotificationTransportProvider | null {
|
||||
const normalizedMode = normalizeNotificationTransportMode(mode, platform);
|
||||
|
||||
if (platform === 'desktop') return null;
|
||||
|
||||
if (normalizedMode === 'web') return 'web';
|
||||
if (normalizedMode === 'native') return 'native';
|
||||
if (normalizedMode === 'unifiedpush') return 'unifiedpush';
|
||||
if (platform === 'web') return 'web';
|
||||
if (platform === 'android') return 'unifiedpush';
|
||||
if (platform === 'ios') return 'native';
|
||||
return null;
|
||||
}
|
||||
|
||||
export function deriveLegacyPushFlags(
|
||||
enabled: boolean,
|
||||
provider: NotificationTransportProvider | null
|
||||
): {
|
||||
usePushNotifications: boolean;
|
||||
useUnifiedPush: boolean;
|
||||
} {
|
||||
return {
|
||||
usePushNotifications: enabled && provider === 'web',
|
||||
useUnifiedPush: enabled && provider === 'unifiedpush',
|
||||
};
|
||||
}
|
||||
|
||||
export function mergePushConfig(
|
||||
defaults: PushTransportConfig,
|
||||
overrides: Partial<PushTransportConfig>
|
||||
): PushTransportConfig {
|
||||
return {
|
||||
mode: overrides.mode ?? defaults.mode,
|
||||
unifiedPushGatewayUrl: overrides.unifiedPushGatewayUrl ?? defaults.unifiedPushGatewayUrl,
|
||||
unifiedPushAppID: overrides.unifiedPushAppID ?? defaults.unifiedPushAppID,
|
||||
unifiedPushDistributor: overrides.unifiedPushDistributor ?? defaults.unifiedPushDistributor,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveProvider(
|
||||
availability: PushTransportAvailability,
|
||||
provider: ResolvedNotificationTransport['provider']
|
||||
): ResolvedNotificationTransport {
|
||||
if (!availability.available) {
|
||||
return {
|
||||
provider: null,
|
||||
status: 'unavailable',
|
||||
degraded: false,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
provider,
|
||||
status: availability.status,
|
||||
degraded: availability.status === 'temp-unavailable',
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveNotificationTransport(
|
||||
input: ResolveNotificationTransportInput
|
||||
): ResolvedNotificationTransport {
|
||||
if (!input.enabled) {
|
||||
return { provider: null, status: 'unavailable', degraded: false };
|
||||
}
|
||||
|
||||
if (input.mode === 'web') {
|
||||
return resolveProvider(input.webPush, 'web');
|
||||
}
|
||||
|
||||
if (input.mode === 'native') {
|
||||
return resolveProvider(input.nativePush, 'native');
|
||||
}
|
||||
|
||||
if (input.mode === 'unifiedpush') {
|
||||
return resolveProvider(input.unifiedPush, 'unifiedpush');
|
||||
}
|
||||
|
||||
if (input.platform === 'android') {
|
||||
if (
|
||||
input.unifiedPush.available &&
|
||||
(input.unifiedPush.status === 'ready' || input.unifiedPush.status === 'temp-unavailable')
|
||||
) {
|
||||
return resolveProvider(input.unifiedPush, 'unifiedpush');
|
||||
}
|
||||
|
||||
if (input.unifiedPush.status === 'hard-failed' && input.nativePush.available) {
|
||||
return resolveProvider(input.nativePush, 'native');
|
||||
}
|
||||
|
||||
return resolveProvider(input.nativePush, 'native');
|
||||
}
|
||||
|
||||
if (input.platform === 'ios') {
|
||||
return resolveProvider(input.nativePush, 'native');
|
||||
}
|
||||
|
||||
if (input.platform === 'web') {
|
||||
return resolveProvider(input.webPush, 'web');
|
||||
}
|
||||
|
||||
return { provider: null, status: 'unavailable', degraded: false };
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type {
|
||||
NotificationTransportListenerHandle,
|
||||
NotificationTransportRuntimeContext,
|
||||
} from './NotificationTransportRuntime';
|
||||
import { NotificationTransportRuntime } from './NotificationTransportRuntime';
|
||||
|
||||
const unifiedPushListener = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<NotificationTransportListenerHandle>>()
|
||||
);
|
||||
const unifiedPushUnregister = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<void>>().mockResolvedValue(undefined)
|
||||
);
|
||||
|
||||
vi.mock('./UnifiedPushNotifications', () => ({
|
||||
listenForUnifiedPushMessages: unifiedPushListener,
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
function createContext(): NotificationTransportRuntimeContext {
|
||||
return {
|
||||
mx: {} as never,
|
||||
showMessageContent: true,
|
||||
showEncryptedMessageContent: false,
|
||||
notificationSoundEnabled: true,
|
||||
useInAppNotifications: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe('NotificationTransportRuntime', () => {
|
||||
it('subscribes only to the resolved provider listener', async () => {
|
||||
unifiedPushListener.mockResolvedValueOnce({
|
||||
unregister: unifiedPushUnregister,
|
||||
});
|
||||
|
||||
const runtime = new NotificationTransportRuntime({
|
||||
unifiedpush: unifiedPushListener,
|
||||
});
|
||||
|
||||
await runtime.sync('unifiedpush', () => createContext());
|
||||
|
||||
expect(unifiedPushListener).toHaveBeenCalledOnce();
|
||||
expect(unifiedPushListener).toHaveBeenCalledWith(expect.any(Function));
|
||||
expect(unifiedPushUnregister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('cleans up the active listener when the provider changes', async () => {
|
||||
unifiedPushListener.mockResolvedValueOnce({
|
||||
unregister: unifiedPushUnregister,
|
||||
});
|
||||
|
||||
const runtime = new NotificationTransportRuntime({
|
||||
unifiedpush: unifiedPushListener,
|
||||
});
|
||||
|
||||
await runtime.sync('unifiedpush', () => createContext());
|
||||
await runtime.sync('native', () => createContext());
|
||||
|
||||
expect(unifiedPushUnregister).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not recreate the listener when the provider stays the same', async () => {
|
||||
unifiedPushListener.mockResolvedValueOnce({
|
||||
unregister: unifiedPushUnregister,
|
||||
});
|
||||
|
||||
const runtime = new NotificationTransportRuntime({
|
||||
unifiedpush: unifiedPushListener,
|
||||
});
|
||||
|
||||
await runtime.sync('unifiedpush', () => createContext());
|
||||
await runtime.sync('unifiedpush', () => ({
|
||||
...createContext(),
|
||||
notificationSoundEnabled: false,
|
||||
}));
|
||||
|
||||
expect(unifiedPushListener).toHaveBeenCalledOnce();
|
||||
expect(unifiedPushUnregister).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('disposes a stale listener registration when the provider changes mid-startup', async () => {
|
||||
let resolveListener: (() => void) | undefined;
|
||||
const lateUnregister = vi.fn<() => Promise<void>>().mockResolvedValue(undefined);
|
||||
const lateListener = new Promise<{ unregister: typeof lateUnregister }>((resolve) => {
|
||||
resolveListener = () => resolve({ unregister: lateUnregister });
|
||||
});
|
||||
const slowListener = vi
|
||||
.fn<() => Promise<NotificationTransportListenerHandle>>()
|
||||
.mockReturnValueOnce(lateListener);
|
||||
|
||||
const runtime = new NotificationTransportRuntime({
|
||||
unifiedpush: slowListener,
|
||||
});
|
||||
|
||||
const firstSync = runtime.sync('unifiedpush', () => createContext());
|
||||
const secondSync = runtime.sync('native', () => createContext());
|
||||
resolveListener?.();
|
||||
|
||||
await Promise.all([firstSync, secondSync]);
|
||||
|
||||
expect(lateUnregister).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('disposes the active listener when stopped', async () => {
|
||||
unifiedPushListener.mockResolvedValueOnce({
|
||||
unregister: unifiedPushUnregister,
|
||||
});
|
||||
|
||||
const runtime = new NotificationTransportRuntime({
|
||||
unifiedpush: unifiedPushListener,
|
||||
});
|
||||
|
||||
await runtime.sync('unifiedpush', () => createContext());
|
||||
await runtime.dispose();
|
||||
|
||||
expect(unifiedPushUnregister).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('does not treat providers without listener factories as active', async () => {
|
||||
const nativeListener = vi
|
||||
.fn<() => Promise<NotificationTransportListenerHandle>>()
|
||||
.mockResolvedValue({
|
||||
unregister: vi.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
});
|
||||
const listenerFactories: Record<string, typeof nativeListener> = {};
|
||||
const runtime = new NotificationTransportRuntime(listenerFactories);
|
||||
|
||||
await runtime.sync('native', () => createContext());
|
||||
|
||||
listenerFactories.native = nativeListener;
|
||||
await runtime.sync('native', () => createContext());
|
||||
|
||||
expect(nativeListener).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,89 @@
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
|
||||
export type NotificationTransportProvider = 'unifiedpush' | 'native' | 'web';
|
||||
|
||||
export type NotificationTransportRuntimeContext = {
|
||||
mx: MatrixClient;
|
||||
showMessageContent: boolean;
|
||||
showEncryptedMessageContent: boolean;
|
||||
notificationSoundEnabled: boolean;
|
||||
useInAppNotifications: boolean;
|
||||
};
|
||||
|
||||
export type NotificationTransportListenerHandle = {
|
||||
unregister: () => Promise<void> | void;
|
||||
};
|
||||
|
||||
export type NotificationTransportListenerFactory = (
|
||||
getContext: () => NotificationTransportRuntimeContext
|
||||
) => Promise<NotificationTransportListenerHandle>;
|
||||
|
||||
export type NotificationTransportListenerFactories = Partial<
|
||||
Record<NotificationTransportProvider, NotificationTransportListenerFactory>
|
||||
>;
|
||||
|
||||
type NotificationTransportListenerCleanup = () => Promise<void> | void;
|
||||
|
||||
const defaultListenerFactories: NotificationTransportListenerFactories = {
|
||||
unifiedpush: async (getContext) => {
|
||||
const { listenForUnifiedPushMessages } = await import('./UnifiedPushNotifications');
|
||||
return listenForUnifiedPushMessages(getContext);
|
||||
},
|
||||
};
|
||||
|
||||
export class NotificationTransportRuntime {
|
||||
#listenerFactories: NotificationTransportListenerFactories;
|
||||
|
||||
#activeProvider: NotificationTransportProvider | null = null;
|
||||
|
||||
#activeGeneration = 0;
|
||||
|
||||
#cleanup: NotificationTransportListenerCleanup | null = null;
|
||||
|
||||
constructor(
|
||||
listenerFactories: NotificationTransportListenerFactories = defaultListenerFactories
|
||||
) {
|
||||
this.#listenerFactories = listenerFactories;
|
||||
}
|
||||
|
||||
async sync(
|
||||
provider: NotificationTransportProvider | null,
|
||||
getContext: () => NotificationTransportRuntimeContext
|
||||
): Promise<void> {
|
||||
if (provider === this.#activeProvider) return;
|
||||
|
||||
const listenerFactory = provider ? this.#listenerFactories[provider] : undefined;
|
||||
const nextActiveProvider = listenerFactory ? provider : null;
|
||||
|
||||
const generation = this.#activeGeneration + 1;
|
||||
this.#activeGeneration = generation;
|
||||
const previousCleanup = this.#cleanup;
|
||||
this.#cleanup = null;
|
||||
this.#activeProvider = nextActiveProvider;
|
||||
|
||||
if (previousCleanup) {
|
||||
await Promise.resolve(previousCleanup()).catch(() => undefined);
|
||||
}
|
||||
|
||||
if (generation !== this.#activeGeneration) return;
|
||||
if (!listenerFactory) return;
|
||||
|
||||
const listener = await listenerFactory(getContext);
|
||||
if (generation !== this.#activeGeneration || nextActiveProvider !== this.#activeProvider) {
|
||||
await Promise.resolve(listener.unregister()).catch(() => undefined);
|
||||
return;
|
||||
}
|
||||
|
||||
this.#cleanup = () => listener.unregister();
|
||||
}
|
||||
|
||||
async dispose(): Promise<void> {
|
||||
this.#activeGeneration += 1;
|
||||
const cleanup = this.#cleanup;
|
||||
this.#cleanup = null;
|
||||
this.#activeProvider = null;
|
||||
|
||||
if (!cleanup) return;
|
||||
await Promise.resolve(cleanup()).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useEffect, useMemo, useRef } from 'react';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { createLogger } from '$utils/debug';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
import { useMatrixClient } from '$hooks/useMatrixClient';
|
||||
import { useClientConfig } from '$hooks/useClientConfig';
|
||||
import { useSetting } from '$state/hooks/settings';
|
||||
import { settingsAtom } from '$state/settings';
|
||||
import { enableUnifiedPush } from './UnifiedPushNotifications';
|
||||
import {
|
||||
NotificationTransportRuntime,
|
||||
type NotificationTransportRuntimeContext,
|
||||
} from './NotificationTransportRuntime';
|
||||
import {
|
||||
type NotificationTransportPlatform,
|
||||
normalizeNotificationTransportMode,
|
||||
resolvePreferredNotificationTransportProvider,
|
||||
} from './NotificationTransport';
|
||||
|
||||
const log = createLogger('NotificationTransportRuntimeFeature');
|
||||
|
||||
function currentPlatform(): NotificationTransportPlatform {
|
||||
if (!isTauri()) return 'web';
|
||||
const platform = osType();
|
||||
if (platform === 'android') return 'android';
|
||||
if (platform === 'ios') return 'ios';
|
||||
return 'desktop';
|
||||
}
|
||||
|
||||
export function NotificationTransportRuntimeFeature() {
|
||||
const mx = useMatrixClient();
|
||||
const clientConfig = useClientConfig();
|
||||
const [backgroundPushEnabled] = useSetting(settingsAtom, 'backgroundPushEnabled');
|
||||
const [backgroundPushProvider] = useSetting(settingsAtom, 'backgroundPushProvider');
|
||||
const [pushTransportMode] = useSetting(settingsAtom, 'pushTransportMode');
|
||||
const [pushTransportOverride] = useSetting(settingsAtom, 'pushTransportOverride');
|
||||
const [useInAppNotifications] = useSetting(settingsAtom, 'useInAppNotifications');
|
||||
const [isNotificationSounds] = useSetting(settingsAtom, 'isNotificationSounds');
|
||||
const [showMessageContent] = useSetting(settingsAtom, 'showMessageContentInNotifications');
|
||||
const [showEncryptedMessageContent] = useSetting(
|
||||
settingsAtom,
|
||||
'showMessageContentInEncryptedNotifications'
|
||||
);
|
||||
|
||||
const runtimeRef = useRef<NotificationTransportRuntime>();
|
||||
if (!runtimeRef.current) runtimeRef.current = new NotificationTransportRuntime();
|
||||
|
||||
// Read fresh by the listener for each incoming push, so toggling display
|
||||
// settings doesn't tear the listener down.
|
||||
const contextRef = useRef<NotificationTransportRuntimeContext>({
|
||||
mx,
|
||||
showMessageContent,
|
||||
showEncryptedMessageContent,
|
||||
notificationSoundEnabled: isNotificationSounds,
|
||||
useInAppNotifications,
|
||||
});
|
||||
contextRef.current = {
|
||||
mx,
|
||||
showMessageContent,
|
||||
showEncryptedMessageContent,
|
||||
notificationSoundEnabled: isNotificationSounds,
|
||||
useInAppNotifications,
|
||||
};
|
||||
|
||||
const platform = currentPlatform();
|
||||
const provider = useMemo(() => {
|
||||
if (!backgroundPushEnabled) return null;
|
||||
const preferred = resolvePreferredNotificationTransportProvider(
|
||||
normalizeNotificationTransportMode(pushTransportMode, platform),
|
||||
platform
|
||||
);
|
||||
return backgroundPushProvider ?? preferred;
|
||||
}, [backgroundPushEnabled, backgroundPushProvider, pushTransportMode, platform]);
|
||||
|
||||
useEffect(() => {
|
||||
void runtimeRef.current?.sync(provider, () => contextRef.current);
|
||||
}, [provider]);
|
||||
|
||||
const upConfigRef = useRef<{ unifiedPushAppID?: string; unifiedPushGatewayUrl?: string }>({});
|
||||
upConfigRef.current = {
|
||||
unifiedPushAppID:
|
||||
pushTransportOverride?.unifiedPushAppID ??
|
||||
clientConfig.pushNotificationDetails?.unifiedPushAppID,
|
||||
unifiedPushGatewayUrl:
|
||||
pushTransportOverride?.unifiedPushGatewayUrl ??
|
||||
clientConfig.pushNotificationDetails?.unifiedPushGatewayUrl,
|
||||
};
|
||||
|
||||
// Keep the pusher current: establish it when UnifiedPush becomes the active
|
||||
// transport (so it survives a fresh install/session, not just a manual toggle)
|
||||
// and refresh it whenever the distributor rotates the endpoint. Deduped by
|
||||
// endpoint so re-registration can't loop.
|
||||
const lastEndpointRef = useRef<string | null>(null);
|
||||
useEffect(() => {
|
||||
if (provider !== 'unifiedpush' || !mx) return undefined;
|
||||
|
||||
const establish = () => {
|
||||
enableUnifiedPush(mx, upConfigRef.current)
|
||||
.then((result) => {
|
||||
lastEndpointRef.current = result.endpoint;
|
||||
})
|
||||
.catch((error) => {
|
||||
log.warn('UnifiedPush pusher registration failed at startup', error);
|
||||
});
|
||||
};
|
||||
|
||||
establish();
|
||||
|
||||
return () => {};
|
||||
}, [provider, mx]);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
void runtimeRef.current?.dispose();
|
||||
},
|
||||
[]
|
||||
);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import type { ClientConfig } from '../../../hooks/useClientConfig';
|
||||
|
||||
const debugLog = createDebugLogger('PushNotifications');
|
||||
@@ -32,6 +33,9 @@ export async function enablePushNotifications(
|
||||
clientConfig: ClientConfig,
|
||||
pushSubscriptionAtom: PushSubscriptionState
|
||||
): Promise<void> {
|
||||
if (isTauri()) {
|
||||
throw new Error('Push notifications are disabled in Tauri runtime.');
|
||||
}
|
||||
if (!('serviceWorker' in navigator) || !('PushManager' in window)) {
|
||||
debugLog.error(
|
||||
'notification',
|
||||
@@ -135,6 +139,8 @@ export async function disablePushNotifications(
|
||||
clientConfig: ClientConfig,
|
||||
pushSubscriptionAtom: PushSubscriptionState
|
||||
): Promise<void> {
|
||||
if (isTauri()) return;
|
||||
|
||||
debugLog.info('notification', 'Disabling push notifications');
|
||||
const [pushSubAtom] = pushSubscriptionAtom;
|
||||
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,106 @@
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { type as osType } from '@tauri-apps/plugin-os';
|
||||
|
||||
export type NotificationPluginListener = {
|
||||
unregister: () => Promise<void> | void;
|
||||
};
|
||||
|
||||
export type TauriNotificationsApi = {
|
||||
Importance: {
|
||||
readonly None: 0;
|
||||
readonly Min: 1;
|
||||
readonly Low: 2;
|
||||
readonly Default: 3;
|
||||
readonly High: 4;
|
||||
};
|
||||
createChannel: (channel: {
|
||||
id: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
importance?: number;
|
||||
vibration?: boolean;
|
||||
}) => Promise<void>;
|
||||
isPermissionGranted: () => Promise<boolean>;
|
||||
requestPermission: () => Promise<NotificationPermission>;
|
||||
sendNotification: (payload: Record<string, unknown>) => Promise<void>;
|
||||
removeActive: (payload: Array<{ id: number; tag?: string }>) => Promise<void>;
|
||||
onNotificationReceived: (
|
||||
listener: (notification: Record<string, unknown>) => void
|
||||
) => Promise<NotificationPluginListener>;
|
||||
onNotificationClicked: (
|
||||
listener: (data: { id: number; data?: Record<string, string> }) => void
|
||||
) => Promise<NotificationPluginListener>;
|
||||
};
|
||||
|
||||
let notificationsApiPromise: Promise<TauriNotificationsApi> | null = null;
|
||||
|
||||
export async function getTauriNotificationsApi(): Promise<TauriNotificationsApi> {
|
||||
if (!notificationsApiPromise) {
|
||||
notificationsApiPromise =
|
||||
import('@choochmeque/tauri-plugin-notifications-api') as unknown as Promise<TauriNotificationsApi>;
|
||||
}
|
||||
|
||||
return notificationsApiPromise;
|
||||
}
|
||||
|
||||
let permissionPromise: Promise<boolean> | null = null;
|
||||
|
||||
export async function ensureTauriNotificationPermission(): Promise<boolean> {
|
||||
if (!permissionPromise) {
|
||||
permissionPromise = (async () => {
|
||||
const api = await getTauriNotificationsApi();
|
||||
if (await api.isPermissionGranted()) return true;
|
||||
return (await api.requestPermission()) === 'granted';
|
||||
})();
|
||||
permissionPromise.then(
|
||||
(granted) => {
|
||||
if (!granted) permissionPromise = null;
|
||||
},
|
||||
() => {
|
||||
permissionPromise = null;
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return permissionPromise;
|
||||
}
|
||||
|
||||
// Desktop webviews can't show web notifications (WKWebView lacks the API; the
|
||||
// Linux CEF runtime never grants it), so desktop routes through the native plugin.
|
||||
const DESKTOP_TAURI_OS = new Set(['linux', 'macos', 'windows']);
|
||||
export const isDesktopTauri = (): boolean => isTauri() && DESKTOP_TAURI_OS.has(osType());
|
||||
export const isIosTauri = (): boolean => isTauri() && osType() === 'ios';
|
||||
// Platforms where OS notifications go through the native plugin instead of web APIs.
|
||||
export const isNativeNotificationTauri = (): boolean => isDesktopTauri() || isIosTauri();
|
||||
|
||||
let nativeNotificationSeq = 1;
|
||||
const nextNativeNotificationId = (): number => {
|
||||
const id = nativeNotificationSeq;
|
||||
nativeNotificationSeq = nativeNotificationSeq >= 2_000_000_000 ? 1 : nativeNotificationSeq + 1;
|
||||
return id;
|
||||
};
|
||||
|
||||
export type NativeTauriNotification = {
|
||||
title: string;
|
||||
body?: string;
|
||||
silent?: boolean;
|
||||
/** Attached to the notification and handed back by onNotificationClicked. */
|
||||
extra?: Record<string, string>;
|
||||
};
|
||||
|
||||
export async function sendNativeTauriNotification({
|
||||
title,
|
||||
body,
|
||||
silent,
|
||||
extra,
|
||||
}: NativeTauriNotification): Promise<void> {
|
||||
if (!(await ensureTauriNotificationPermission())) return;
|
||||
const api = await getTauriNotificationsApi();
|
||||
await api.sendNotification({
|
||||
id: nextNativeNotificationId(),
|
||||
title,
|
||||
body,
|
||||
silent: silent ?? false,
|
||||
extra,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
createUnifiedPushMessageListener,
|
||||
parseUnifiedPushMessage,
|
||||
} from './UnifiedPushMessageListener';
|
||||
|
||||
describe('createUnifiedPushMessageListener', () => {
|
||||
it('catches rejected payload handlers instead of leaking unhandled rejections', async () => {
|
||||
const onError = vi.fn<(error: unknown) => void>();
|
||||
const listener = createUnifiedPushMessageListener(async () => {
|
||||
throw new Error('boom');
|
||||
}, onError);
|
||||
|
||||
expect(listener({})).toBeUndefined();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: 'boom' }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseUnifiedPushMessage', () => {
|
||||
it('unwraps the Matrix notification from the message JSON string', () => {
|
||||
const raw = {
|
||||
message: JSON.stringify({
|
||||
notification: { type: 'm.room.message', room_id: '!r:server', event_id: '$e' },
|
||||
}),
|
||||
};
|
||||
|
||||
expect(parseUnifiedPushMessage(raw)).toEqual({
|
||||
type: 'm.room.message',
|
||||
room_id: '!r:server',
|
||||
event_id: '$e',
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the payload as-is when there is no notification wrapper', () => {
|
||||
const raw = { message: JSON.stringify({ event_id: '$e', room_id: '!r:server' }) };
|
||||
|
||||
expect(parseUnifiedPushMessage(raw)).toEqual({ event_id: '$e', room_id: '!r:server' });
|
||||
});
|
||||
|
||||
it('returns null for a missing or non-JSON message', () => {
|
||||
expect(parseUnifiedPushMessage({})).toBeNull();
|
||||
expect(parseUnifiedPushMessage({ message: 'not json' })).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
export type UnifiedPushMessageHandler = (data: Record<string, unknown>) => Promise<void>;
|
||||
export type UnifiedPushMessageErrorHandler = (error: unknown) => void;
|
||||
|
||||
export function createUnifiedPushMessageListener(
|
||||
handler: UnifiedPushMessageHandler,
|
||||
onError: UnifiedPushMessageErrorHandler
|
||||
) {
|
||||
return (data: Record<string, unknown>) => {
|
||||
handler(data).catch(onError);
|
||||
};
|
||||
}
|
||||
|
||||
export function parseUnifiedPushMessage(raw: unknown): Record<string, unknown> | null {
|
||||
const message = (raw as { message?: unknown })?.message;
|
||||
if (typeof message !== 'string') return null;
|
||||
|
||||
let payload: unknown;
|
||||
try {
|
||||
payload = JSON.parse(message);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
|
||||
const notification = (payload as { notification?: unknown }).notification;
|
||||
if (notification && typeof notification === 'object') {
|
||||
return notification as Record<string, unknown>;
|
||||
}
|
||||
return payload as Record<string, unknown>;
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
DEFAULT_UNIFIED_PUSH_APP_ID,
|
||||
disableUnifiedPush,
|
||||
tryEnableUnifiedPush,
|
||||
} from './UnifiedPushNotifications';
|
||||
|
||||
const notificationsApi = vi.hoisted(() => ({
|
||||
sendNotification: vi.fn<() => void>(),
|
||||
removeActive: vi.fn<() => void>(),
|
||||
createChannel: vi.fn<() => void>(),
|
||||
Importance: {
|
||||
Default: 3,
|
||||
},
|
||||
}));
|
||||
|
||||
const unifiedPushTransport = vi.hoisted(() => ({
|
||||
getUnifiedPushDistributor: vi.fn<() => void>(),
|
||||
getUnifiedPushDistributors: vi.fn<() => void>(),
|
||||
registerUnifiedPushTransport: vi.fn<() => Promise<unknown>>(),
|
||||
saveUnifiedPushDistributor: vi.fn<() => void>(),
|
||||
unregisterUnifiedPushTransport: vi.fn<() => Promise<void>>(),
|
||||
}));
|
||||
|
||||
const getTauriNotificationsApi = vi.hoisted(() =>
|
||||
vi.fn<() => Promise<typeof notificationsApi>>().mockResolvedValue(notificationsApi)
|
||||
);
|
||||
|
||||
const matrixClient = vi.hoisted(() => ({
|
||||
setPusher: vi.fn<() => Promise<void>>().mockResolvedValue(undefined),
|
||||
getDeviceId: vi.fn<() => string>(() => 'DEVICE'),
|
||||
getDevice: vi
|
||||
.fn<() => Promise<{ display_name: string }>>()
|
||||
.mockResolvedValue({ display_name: 'Pixel' }),
|
||||
getPushers: vi
|
||||
.fn<() => Promise<{ pushers: Array<unknown> }>>()
|
||||
.mockResolvedValue({ pushers: [] }),
|
||||
}));
|
||||
|
||||
vi.mock('./UnifiedPushTransport', () => unifiedPushTransport);
|
||||
|
||||
vi.mock('./TauriNotificationsApiClient', () => ({
|
||||
getTauriNotificationsApi,
|
||||
}));
|
||||
|
||||
vi.mock('$utils/fetch', () => ({
|
||||
fetch: (...args: Parameters<typeof globalThis.fetch>) => globalThis.fetch(...args),
|
||||
}));
|
||||
|
||||
describe('UnifiedPushNotifications', () => {
|
||||
beforeEach(() => {
|
||||
notificationsApi.createChannel.mockResolvedValue(undefined);
|
||||
getTauriNotificationsApi.mockResolvedValue(notificationsApi);
|
||||
unifiedPushTransport.registerUnifiedPushTransport.mockResolvedValue({
|
||||
status: 'registered',
|
||||
permissionState: 'granted',
|
||||
endpoint: 'https://up.example/device',
|
||||
distributor: 'org.unifiedpush.distributor.ntfy',
|
||||
});
|
||||
unifiedPushTransport.unregisterUnifiedPushTransport.mockResolvedValue(undefined);
|
||||
matrixClient.setPusher.mockClear();
|
||||
matrixClient.getPushers.mockResolvedValue({ pushers: [] });
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn<typeof fetch>().mockRejectedValue(new Error('gateway probe failed'))
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
it('registers the Matrix pusher with the resolved UnifiedPush overrides', async () => {
|
||||
await expect(
|
||||
tryEnableUnifiedPush(matrixClient as never, {
|
||||
unifiedPushAppID: 'com.example.up',
|
||||
unifiedPushGatewayUrl: ' https://gateway.example/_matrix/push/v1/notify ',
|
||||
})
|
||||
).resolves.toMatchObject({
|
||||
status: 'registered',
|
||||
endpoint: 'https://up.example/device',
|
||||
});
|
||||
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: 'http',
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'https://up.example/device',
|
||||
data: expect.objectContaining({
|
||||
url: 'https://gateway.example/_matrix/push/v1/notify',
|
||||
}),
|
||||
})
|
||||
);
|
||||
}, 15_000);
|
||||
|
||||
it('clears the UnifiedPush registration timeout after successful registration', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
try {
|
||||
await expect(tryEnableUnifiedPush(matrixClient as never)).resolves.toMatchObject({
|
||||
status: 'registered',
|
||||
});
|
||||
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
});
|
||||
|
||||
it('falls back to the default UnifiedPush app id when no override is provided', async () => {
|
||||
await tryEnableUnifiedPush(matrixClient as never);
|
||||
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
app_id: DEFAULT_UNIFIED_PUSH_APP_ID,
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('removes current-device UnifiedPush pushers when the cached endpoint is unavailable', async () => {
|
||||
matrixClient.getPushers.mockResolvedValue({
|
||||
pushers: [
|
||||
{
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'stale-endpoint-1',
|
||||
device_display_name: 'Pixel',
|
||||
kind: 'http',
|
||||
},
|
||||
{
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'stale-endpoint-2',
|
||||
device_display_name: 'Pixel',
|
||||
kind: 'http',
|
||||
},
|
||||
{
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'other-device-endpoint',
|
||||
device_display_name: 'Other Phone',
|
||||
kind: 'http',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await disableUnifiedPush(matrixClient as never, {
|
||||
config: {
|
||||
unifiedPushAppID: 'com.example.up',
|
||||
},
|
||||
});
|
||||
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledTimes(2);
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: null,
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'stale-endpoint-1',
|
||||
})
|
||||
);
|
||||
expect(matrixClient.setPusher).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
kind: null,
|
||||
app_id: 'com.example.up',
|
||||
pushkey: 'stale-endpoint-2',
|
||||
})
|
||||
);
|
||||
expect(unifiedPushTransport.unregisterUnifiedPushTransport).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,605 @@
|
||||
import type { IPusherRequest, MatrixClient } from '$types/matrix-sdk';
|
||||
import { EventType } from 'matrix-js-sdk/lib/@types/event';
|
||||
import { resolveNotificationPreviewText } from '$utils/notificationStyle';
|
||||
import { getMxIdLocalPart } from '$utils/matrix';
|
||||
import { getStateEvent, getMemberAvatarMxc } from '$utils/room';
|
||||
import { createDebugLogger } from '$utils/debugLogger';
|
||||
import {
|
||||
getUnifiedPushDistributor,
|
||||
getUnifiedPushDistributors,
|
||||
registerUnifiedPushTransport,
|
||||
saveUnifiedPushDistributor,
|
||||
type UnifiedPushRegistrationResult,
|
||||
unregisterUnifiedPushTransport,
|
||||
} from './UnifiedPushTransport';
|
||||
import {
|
||||
createUnifiedPushMessageListener,
|
||||
parseUnifiedPushMessage,
|
||||
} from './UnifiedPushMessageListener';
|
||||
import { addPluginListener } from '@tauri-apps/api/core';
|
||||
import type { PushTransportConfig } from './NotificationTransport';
|
||||
import { getTauriNotificationsApi } from './TauriNotificationsApiClient';
|
||||
|
||||
export { getUnifiedPushDistributors, getUnifiedPushDistributor, saveUnifiedPushDistributor };
|
||||
|
||||
const UP_PUBLIC_GATEWAY = 'https://matrix.gateway.unifiedpush.org/_matrix/push/v1/notify';
|
||||
export const DEFAULT_UNIFIED_PUSH_APP_ID = 'moe.sable.up';
|
||||
const unifiedPushLog = createDebugLogger('unifiedpush');
|
||||
|
||||
/**
|
||||
* Shape of a UnifiedPush payload delivered to the message listener.
|
||||
* Fields are optional because both rich (full event) and minimal
|
||||
* (event_id + counts) payloads arrive through the same entry point.
|
||||
*/
|
||||
type UnifiedPushPayload = {
|
||||
type?: string;
|
||||
content?: Record<string, unknown>;
|
||||
room_id?: string;
|
||||
room_name?: string;
|
||||
sender_display_name?: string;
|
||||
sender?: string;
|
||||
event_id?: string;
|
||||
user_id?: string;
|
||||
counts?: { unread?: number };
|
||||
notification?: unknown;
|
||||
[key: string]: unknown;
|
||||
};
|
||||
|
||||
const UP_REGISTER_TIMEOUT_MS = 30_000;
|
||||
|
||||
export type UnifiedPushTransportConfigInput = Pick<
|
||||
PushTransportConfig,
|
||||
'unifiedPushGatewayUrl' | 'unifiedPushAppID'
|
||||
>;
|
||||
|
||||
type UnifiedPushPusherConfig = {
|
||||
appId: string;
|
||||
gatewayUrl?: string;
|
||||
};
|
||||
|
||||
function trimConfigValue(value: string | undefined): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed || undefined;
|
||||
}
|
||||
|
||||
function resolveUnifiedPushPusherConfig(
|
||||
config?: UnifiedPushTransportConfigInput
|
||||
): UnifiedPushPusherConfig {
|
||||
return {
|
||||
appId: trimConfigValue(config?.unifiedPushAppID) ?? DEFAULT_UNIFIED_PUSH_APP_ID,
|
||||
gatewayUrl: trimConfigValue(config?.unifiedPushGatewayUrl),
|
||||
};
|
||||
}
|
||||
|
||||
export type EnableUnifiedPushResult =
|
||||
| {
|
||||
status: 'registered';
|
||||
endpoint: string;
|
||||
gatewayUrl: string;
|
||||
distributor: string;
|
||||
}
|
||||
| Exclude<UnifiedPushRegistrationResult, { status: 'registered' }>;
|
||||
|
||||
async function registerUnifiedPushWithTimeout(): Promise<UnifiedPushRegistrationResult> {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timeoutId = setTimeout(() => {
|
||||
reject(new Error('UnifiedPush registration timed out'));
|
||||
}, UP_REGISTER_TIMEOUT_MS);
|
||||
});
|
||||
|
||||
try {
|
||||
return await Promise.race([registerUnifiedPushTransport(), timeout]);
|
||||
} finally {
|
||||
if (timeoutId !== undefined) {
|
||||
clearTimeout(timeoutId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function tryEnableUnifiedPush(
|
||||
mx: MatrixClient,
|
||||
config?: UnifiedPushTransportConfigInput
|
||||
): Promise<EnableUnifiedPushResult> {
|
||||
const notificationsApi = await getTauriNotificationsApi();
|
||||
|
||||
await notificationsApi.createChannel({
|
||||
id: 'messages',
|
||||
name: 'Messages',
|
||||
description: 'Matrix message and invite notifications',
|
||||
importance: notificationsApi.Importance.Default,
|
||||
vibration: true,
|
||||
});
|
||||
|
||||
const registration = await registerUnifiedPushWithTimeout();
|
||||
|
||||
if (registration.status !== 'registered') {
|
||||
return registration;
|
||||
}
|
||||
|
||||
const { endpoint } = registration;
|
||||
const resolvedConfig = resolveUnifiedPushPusherConfig(config);
|
||||
const gatewayUrl = resolvedConfig.gatewayUrl ?? UP_PUBLIC_GATEWAY;
|
||||
|
||||
const pusherData: Record<string, string> = {
|
||||
url: gatewayUrl,
|
||||
};
|
||||
|
||||
await mx.setPusher({
|
||||
kind: 'http',
|
||||
app_id: resolvedConfig.appId,
|
||||
pushkey: endpoint,
|
||||
app_display_name: 'Sable (UnifiedPush)',
|
||||
device_display_name:
|
||||
(await mx.getDevice(mx.getDeviceId() ?? ''))?.display_name ?? 'Android Device',
|
||||
lang: navigator.language || 'en',
|
||||
data: pusherData,
|
||||
append: false,
|
||||
} as unknown as IPusherRequest);
|
||||
|
||||
return {
|
||||
status: 'registered',
|
||||
endpoint,
|
||||
gatewayUrl,
|
||||
distributor: registration.distributor,
|
||||
};
|
||||
}
|
||||
|
||||
export async function enableUnifiedPush(
|
||||
mx: MatrixClient,
|
||||
config?: UnifiedPushTransportConfigInput
|
||||
): Promise<{ endpoint: string; gatewayUrl: string }> {
|
||||
const result = await tryEnableUnifiedPush(mx, config);
|
||||
if (result.status !== 'registered') {
|
||||
throw new Error(result.error ?? 'UnifiedPush registration failed');
|
||||
}
|
||||
|
||||
return {
|
||||
endpoint: result.endpoint,
|
||||
gatewayUrl: result.gatewayUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function isNonEmptyString(value: unknown): value is string {
|
||||
return typeof value === 'string' && value.trim().length > 0;
|
||||
}
|
||||
|
||||
async function getCurrentDeviceUnifiedPushPushkeys(
|
||||
mx: MatrixClient,
|
||||
appId: string
|
||||
): Promise<string[]> {
|
||||
const deviceId = mx.getDeviceId() ?? '';
|
||||
if (!deviceId) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const currentDevice = await mx.getDevice(deviceId);
|
||||
const deviceDisplayName = currentDevice?.display_name;
|
||||
if (!deviceDisplayName) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const response = await mx.getPushers();
|
||||
const pushers = response.pushers ?? [];
|
||||
return pushers
|
||||
.filter(
|
||||
(pusher) =>
|
||||
pusher.app_id === appId &&
|
||||
pusher.device_display_name === deviceDisplayName &&
|
||||
pusher.kind === 'http' &&
|
||||
isNonEmptyString(pusher.pushkey)
|
||||
)
|
||||
.map((pusher) => pusher.pushkey);
|
||||
}
|
||||
|
||||
async function getUnifiedPushCleanupPushkeys(
|
||||
mx: MatrixClient,
|
||||
appId: string,
|
||||
pushkey?: string
|
||||
): Promise<string[]> {
|
||||
const pushkeys = new Set<string>();
|
||||
|
||||
if (isNonEmptyString(pushkey)) {
|
||||
pushkeys.add(pushkey);
|
||||
}
|
||||
|
||||
const currentDevicePushkeys = await getCurrentDeviceUnifiedPushPushkeys(mx, appId);
|
||||
currentDevicePushkeys.forEach((candidate) => pushkeys.add(candidate));
|
||||
|
||||
return Array.from(pushkeys);
|
||||
}
|
||||
|
||||
export type DisableUnifiedPushOptions = {
|
||||
config?: UnifiedPushTransportConfigInput;
|
||||
pushkey?: string;
|
||||
};
|
||||
|
||||
export async function disableUnifiedPush(
|
||||
mx: MatrixClient,
|
||||
options: DisableUnifiedPushOptions = {}
|
||||
): Promise<void> {
|
||||
const { appId } = resolveUnifiedPushPusherConfig(options.config);
|
||||
const pushkeys = await getUnifiedPushCleanupPushkeys(mx, appId, options.pushkey);
|
||||
|
||||
await Promise.allSettled(
|
||||
pushkeys.map((pushkey) =>
|
||||
mx.setPusher({
|
||||
kind: null,
|
||||
app_id: appId,
|
||||
pushkey,
|
||||
} as unknown as IPusherRequest)
|
||||
)
|
||||
);
|
||||
|
||||
await unregisterUnifiedPushTransport();
|
||||
}
|
||||
|
||||
type NotificationSettings = {
|
||||
mx: MatrixClient;
|
||||
showMessageContent: boolean;
|
||||
showEncryptedMessageContent: boolean;
|
||||
notificationSoundEnabled: boolean;
|
||||
useInAppNotifications: boolean;
|
||||
};
|
||||
|
||||
const NOTIF_GROUP_KEY = 'matrix_messages';
|
||||
const MAX_MESSAGES = 10;
|
||||
|
||||
type NotifPerson = {
|
||||
name: string;
|
||||
key?: string;
|
||||
iconUrl?: string;
|
||||
};
|
||||
|
||||
type NotifMessage = {
|
||||
text: string;
|
||||
timestamp: number;
|
||||
sender?: NotifPerson;
|
||||
};
|
||||
|
||||
function hashCode(str: string): number {
|
||||
let hash = 0;
|
||||
for (let i = 0; i < str.length; i += 1) {
|
||||
// eslint-disable-next-line no-bitwise
|
||||
hash = (Math.imul(31, hash) + str.charCodeAt(i)) | 0;
|
||||
}
|
||||
return Math.abs(hash);
|
||||
}
|
||||
|
||||
const roomNotifId = (roomId: string) => hashCode(roomId);
|
||||
const SUMMARY_NOTIF_ID = hashCode('sable-group-summary');
|
||||
|
||||
type RoomNotifCache = {
|
||||
roomName: string;
|
||||
messages: NotifMessage[];
|
||||
seenEventIds: Set<string>;
|
||||
isGroupConversation: boolean;
|
||||
latestEventId?: string;
|
||||
};
|
||||
|
||||
const roomNotifCaches = new Map<string, RoomNotifCache>();
|
||||
|
||||
function resolveAvatarUrl(mx: MatrixClient, roomId: string, userId: string): string | undefined {
|
||||
const room = mx.getRoom(roomId);
|
||||
if (!room) return undefined;
|
||||
const mxcUrl = getMemberAvatarMxc(room, userId);
|
||||
if (!mxcUrl) return undefined;
|
||||
return mx.mxcUrlToHttp(mxcUrl, 96, 96, 'crop', false, true, true) ?? undefined;
|
||||
}
|
||||
|
||||
function getOrCreateRoomCache(roomId: string, roomName: string): RoomNotifCache {
|
||||
let cache = roomNotifCaches.get(roomId);
|
||||
if (!cache) {
|
||||
cache = { roomName, messages: [], seenEventIds: new Set(), isGroupConversation: false };
|
||||
roomNotifCaches.set(roomId, cache);
|
||||
}
|
||||
cache.roomName = roomName;
|
||||
return cache;
|
||||
}
|
||||
|
||||
/** Clears accumulated messages for a room and dismisses its notification. */
|
||||
export async function clearRoomNotification(roomId: string) {
|
||||
roomNotifCaches.delete(roomId);
|
||||
try {
|
||||
const notificationsApi = await getTauriNotificationsApi();
|
||||
await notificationsApi.removeActive([{ id: roomNotifId(roomId) }]);
|
||||
} catch {
|
||||
// already dismissed
|
||||
}
|
||||
if (roomNotifCaches.size <= 1) {
|
||||
try {
|
||||
const notificationsApi = await getTauriNotificationsApi();
|
||||
await notificationsApi.removeActive([{ id: SUMMARY_NOTIF_ID }]);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function postRoomNotification(
|
||||
roomId: string,
|
||||
cache: RoomNotifCache,
|
||||
isSilent: boolean,
|
||||
extra: Record<string, unknown>
|
||||
) {
|
||||
const notificationsApi = await getTauriNotificationsApi();
|
||||
const { messages, roomName } = cache;
|
||||
const latestMsg = messages[messages.length - 1];
|
||||
const latestBody = latestMsg ? `${latestMsg.sender?.name ?? 'You'}: ${latestMsg.text}` : '';
|
||||
|
||||
const inboxLines = messages.slice(-5).map((m) => `${m.sender?.name ?? 'You'}: ${m.text}`);
|
||||
|
||||
await notificationsApi.sendNotification({
|
||||
id: roomNotifId(roomId),
|
||||
title: roomName,
|
||||
body: latestBody,
|
||||
channelId: 'messages',
|
||||
group: NOTIF_GROUP_KEY,
|
||||
icon: 'notification_icon',
|
||||
silent: isSilent,
|
||||
autoCancel: true,
|
||||
extra,
|
||||
inboxLines: inboxLines.length > 1 ? inboxLines : undefined,
|
||||
});
|
||||
|
||||
const roomCount = roomNotifCaches.size;
|
||||
if (roomCount > 1) {
|
||||
const totalMessages = Array.from(roomNotifCaches.values()).reduce(
|
||||
(sum, c) => sum + c.messages.length,
|
||||
0
|
||||
);
|
||||
const summaryText = `${totalMessages} messages in ${roomCount} chats`;
|
||||
const summaryLines: string[] = [];
|
||||
Array.from(roomNotifCaches.values()).forEach((c) => {
|
||||
const latest = c.messages[c.messages.length - 1];
|
||||
if (latest) {
|
||||
summaryLines.push(`${c.roomName}: ${latest.sender?.name ?? 'You'}: ${latest.text}`);
|
||||
}
|
||||
});
|
||||
await notificationsApi.sendNotification({
|
||||
id: SUMMARY_NOTIF_ID,
|
||||
title: summaryText,
|
||||
body: '',
|
||||
summary: summaryText,
|
||||
inboxLines: summaryLines.slice(-5),
|
||||
channelId: 'messages',
|
||||
group: NOTIF_GROUP_KEY,
|
||||
groupSummary: true,
|
||||
icon: 'notification_icon',
|
||||
silent: true,
|
||||
autoCancel: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Handles a rich push payload containing full event details (type, room_name, content, etc.). */
|
||||
async function handleRichPushPayload(pushData: UnifiedPushPayload, settings: NotificationSettings) {
|
||||
const eventType = pushData.type as EventType;
|
||||
|
||||
switch (eventType) {
|
||||
case EventType.RoomMessage:
|
||||
case EventType.Sticker:
|
||||
case EventType.RoomMessageEncrypted: {
|
||||
const isEncrypted = eventType === EventType.RoomMessageEncrypted;
|
||||
|
||||
const previewText = resolveNotificationPreviewText({
|
||||
content: pushData?.content,
|
||||
eventType: pushData?.type,
|
||||
isEncryptedRoom: isEncrypted,
|
||||
showMessageContent: settings.showMessageContent,
|
||||
showEncryptedMessageContent: settings.showEncryptedMessageContent,
|
||||
});
|
||||
|
||||
const roomId: string | undefined = pushData?.room_id;
|
||||
const roomName: string = pushData?.room_name ?? 'Unknown Room';
|
||||
const senderName: string | undefined = pushData?.sender_display_name;
|
||||
const senderId: string | undefined = pushData?.sender;
|
||||
const isSilent = !settings.notificationSoundEnabled;
|
||||
|
||||
if (!roomId) {
|
||||
const notificationsApi = await getTauriNotificationsApi();
|
||||
await notificationsApi.sendNotification({
|
||||
title: roomName,
|
||||
body: senderName ? `${senderName}: ${previewText}` : previewText,
|
||||
channelId: 'messages',
|
||||
icon: 'notification_icon',
|
||||
silent: isSilent,
|
||||
autoCancel: true,
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
const sender: NotifPerson | undefined = senderName
|
||||
? {
|
||||
name: senderName,
|
||||
key: senderId,
|
||||
iconUrl: senderId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const message: NotifMessage = {
|
||||
text: previewText,
|
||||
timestamp: Date.now(),
|
||||
sender,
|
||||
};
|
||||
|
||||
const cache = getOrCreateRoomCache(roomId, roomName);
|
||||
|
||||
const eventId: string | undefined = pushData?.event_id;
|
||||
if (eventId && cache.seenEventIds.has(eventId)) break;
|
||||
if (eventId) cache.seenEventIds.add(eventId);
|
||||
|
||||
cache.messages.push(message);
|
||||
if (cache.messages.length > MAX_MESSAGES) {
|
||||
cache.messages = cache.messages.slice(-MAX_MESSAGES);
|
||||
}
|
||||
cache.latestEventId = eventId;
|
||||
|
||||
const room = settings.mx.getRoom(roomId);
|
||||
if (room) {
|
||||
cache.isGroupConversation = (room.getJoinedMemberCount() ?? 0) > 2;
|
||||
}
|
||||
|
||||
await postRoomNotification(roomId, cache, isSilent, {
|
||||
room_id: roomId,
|
||||
event_id: pushData?.event_id,
|
||||
user_id: pushData?.user_id,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case EventType.RoomMember: {
|
||||
if (pushData?.content?.membership !== 'invite') break;
|
||||
const senderName: string | undefined = pushData?.sender_display_name;
|
||||
const roomName: string | undefined = pushData?.room_name;
|
||||
let body = '';
|
||||
if (senderName && roomName) body = `${senderName} invites you to ${roomName}`;
|
||||
else if (senderName) body = `from ${senderName}`;
|
||||
else if (roomName) body = `to ${roomName}`;
|
||||
|
||||
const notificationsApi = await getTauriNotificationsApi();
|
||||
await notificationsApi.sendNotification({
|
||||
title: 'New Invitation',
|
||||
body,
|
||||
channelId: 'messages',
|
||||
group: NOTIF_GROUP_KEY,
|
||||
icon: 'notification_icon',
|
||||
autoCancel: true,
|
||||
extra: {
|
||||
room_id: pushData?.room_id,
|
||||
event_id: pushData?.event_id,
|
||||
user_id: pushData?.user_id,
|
||||
},
|
||||
});
|
||||
break;
|
||||
}
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles a minimal push payload (event_id + room_id + counts) from
|
||||
* the public UnifiedPush gateway, looking up context from local SDK state.
|
||||
*/
|
||||
async function handleMinimalPushPayload(
|
||||
pushData: UnifiedPushPayload,
|
||||
settings: NotificationSettings
|
||||
) {
|
||||
const roomId: string | undefined = pushData?.room_id;
|
||||
const eventId: string | undefined = pushData?.event_id;
|
||||
const unread: number | undefined =
|
||||
typeof pushData?.counts?.unread === 'number' ? pushData.counts.unread : undefined;
|
||||
|
||||
if (!roomId) return;
|
||||
|
||||
// Unread count of zero means the room was read — dismiss the notification.
|
||||
if (unread === 0) {
|
||||
await clearRoomNotification(roomId);
|
||||
return;
|
||||
}
|
||||
|
||||
const room = settings.mx.getRoom(roomId);
|
||||
const roomName = room?.name ?? 'Unknown Room';
|
||||
const isEncryptedRoom = room ? !!getStateEvent(room, EventType.RoomEncryption) : false;
|
||||
|
||||
let senderName: string | undefined;
|
||||
let senderId: string | undefined;
|
||||
let previewText: string | undefined;
|
||||
if (room && eventId) {
|
||||
const timeline = room.getLiveTimeline().getEvents();
|
||||
const mEvent = timeline.find((e) => e.getId() === eventId);
|
||||
if (mEvent) {
|
||||
const sender = mEvent.getSender();
|
||||
if (sender) {
|
||||
const member = room.getMember(sender);
|
||||
senderName = member?.name ?? getMxIdLocalPart(sender) ?? sender;
|
||||
senderId = sender;
|
||||
}
|
||||
|
||||
previewText = resolveNotificationPreviewText({
|
||||
content: mEvent.getContent(),
|
||||
eventType: mEvent.getType(),
|
||||
isEncryptedRoom,
|
||||
showMessageContent: settings.showMessageContent,
|
||||
showEncryptedMessageContent: settings.showEncryptedMessageContent,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!previewText) {
|
||||
previewText = isEncryptedRoom ? 'Encrypted message' : 'New message';
|
||||
}
|
||||
|
||||
const sender: NotifPerson | undefined = senderName
|
||||
? {
|
||||
name: senderName,
|
||||
key: senderId,
|
||||
iconUrl: senderId && roomId ? resolveAvatarUrl(settings.mx, roomId, senderId) : undefined,
|
||||
}
|
||||
: undefined;
|
||||
|
||||
const message: NotifMessage = {
|
||||
text: previewText,
|
||||
timestamp: Date.now(),
|
||||
sender,
|
||||
};
|
||||
|
||||
const cache = getOrCreateRoomCache(roomId, roomName);
|
||||
|
||||
if (eventId && cache.seenEventIds.has(eventId)) return;
|
||||
if (eventId) cache.seenEventIds.add(eventId);
|
||||
|
||||
cache.messages.push(message);
|
||||
if (cache.messages.length > MAX_MESSAGES) {
|
||||
cache.messages = cache.messages.slice(-MAX_MESSAGES);
|
||||
}
|
||||
cache.latestEventId = eventId;
|
||||
|
||||
if (room) {
|
||||
cache.isGroupConversation = (room.getJoinedMemberCount() ?? 0) > 2;
|
||||
}
|
||||
|
||||
await postRoomNotification(roomId, cache, !settings.notificationSoundEnabled, {
|
||||
room_id: roomId,
|
||||
event_id: eventId,
|
||||
});
|
||||
}
|
||||
|
||||
async function handleUnifiedPushPayload(
|
||||
raw: Record<string, unknown>,
|
||||
getSettings: () => NotificationSettings
|
||||
) {
|
||||
const settings = getSettings();
|
||||
|
||||
// Skip system notification when in-app banners are active and visible.
|
||||
if (document.visibilityState === 'visible' && settings.useInAppNotifications) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pushData = (raw.extra ?? raw) as UnifiedPushPayload;
|
||||
const eventType = pushData?.type as EventType | undefined;
|
||||
|
||||
if (eventType) {
|
||||
await handleRichPushPayload(pushData, settings);
|
||||
} else {
|
||||
await handleMinimalPushPayload(pushData, settings);
|
||||
}
|
||||
}
|
||||
|
||||
export function listenForUnifiedPushMessages(getSettings: () => NotificationSettings) {
|
||||
const dispatch = createUnifiedPushMessageListener(
|
||||
(notification) => handleUnifiedPushPayload(notification, getSettings),
|
||||
(error) => {
|
||||
unifiedPushLog.error(
|
||||
'notification',
|
||||
'UnifiedPush payload handling failed',
|
||||
error instanceof Error ? error : new Error(String(error))
|
||||
);
|
||||
}
|
||||
);
|
||||
|
||||
return addPluginListener('unifiedpush', 'push-message', (data: unknown) => {
|
||||
const notification = parseUnifiedPushMessage(data);
|
||||
if (notification) dispatch(notification);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import {
|
||||
classifyUnifiedPushFailure,
|
||||
ensureUnifiedPushDistributorSelection,
|
||||
loadUnifiedPushDistributorState,
|
||||
registerUnifiedPushTransport,
|
||||
switchUnifiedPushDistributorSelection,
|
||||
setUnifiedPushDistributorSelection,
|
||||
} from './UnifiedPushTransport';
|
||||
|
||||
const unifiedPushApi = vi.hoisted(() => ({
|
||||
isPermissionGranted: vi.fn<() => Promise<boolean>>(),
|
||||
requestPermission: vi.fn<() => Promise<string>>(),
|
||||
registerForPushNotifications: vi.fn<() => Promise<string>>(),
|
||||
unregisterForPushNotifications: vi.fn<() => Promise<void>>(),
|
||||
listDistributors: vi.fn<() => Promise<string[]>>(),
|
||||
setDistributor: vi.fn<(name: string) => Promise<void>>(),
|
||||
setToken: vi.fn<(token: string) => Promise<void>>(),
|
||||
}));
|
||||
|
||||
vi.mock('./UnifiedPushTransportApiClient', () => ({
|
||||
getUnifiedPushTransportApi: vi
|
||||
.fn<() => Promise<typeof unifiedPushApi>>()
|
||||
.mockResolvedValue(unifiedPushApi),
|
||||
}));
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
localStorage.clear();
|
||||
});
|
||||
|
||||
describe('classifyUnifiedPushFailure', () => {
|
||||
it('treats temporary unavailability as a distinct failure', () => {
|
||||
expect(
|
||||
classifyUnifiedPushFailure(new Error('UnifiedPush registration temporarily unavailable'))
|
||||
).toBe('temp-unavailable');
|
||||
});
|
||||
|
||||
it('treats missing distributors as a distinct failure', () => {
|
||||
expect(classifyUnifiedPushFailure(new Error('No UnifiedPush distributor installed'))).toBe(
|
||||
'missing-distributor'
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('registerUnifiedPushTransport', () => {
|
||||
it('requests permission before registering and saves the only available distributor', async () => {
|
||||
unifiedPushApi.isPermissionGranted.mockResolvedValue(false);
|
||||
unifiedPushApi.requestPermission.mockResolvedValue('granted');
|
||||
localStorage.removeItem('unifiedpush_distributor');
|
||||
unifiedPushApi.listDistributors.mockResolvedValue(['org.unifiedpush.distributor.ntfy']);
|
||||
unifiedPushApi.registerForPushNotifications.mockResolvedValue('https://up.example/endpoint');
|
||||
|
||||
await expect(registerUnifiedPushTransport()).resolves.toEqual({
|
||||
status: 'registered',
|
||||
permissionState: 'granted',
|
||||
endpoint: 'https://up.example/endpoint',
|
||||
distributor: 'org.unifiedpush.distributor.ntfy',
|
||||
});
|
||||
expect(unifiedPushApi.requestPermission).toHaveBeenCalledOnce();
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenCalledOnce();
|
||||
expect(unifiedPushApi.registerForPushNotifications).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('returns denied without registering when permission is denied', async () => {
|
||||
unifiedPushApi.isPermissionGranted.mockResolvedValue(false);
|
||||
unifiedPushApi.requestPermission.mockResolvedValue('denied');
|
||||
|
||||
await expect(registerUnifiedPushTransport()).resolves.toEqual({
|
||||
status: 'denied',
|
||||
permissionState: 'denied',
|
||||
error: 'UnifiedPush permission denied',
|
||||
});
|
||||
expect(unifiedPushApi.registerForPushNotifications).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns missing-distributor without registering when none are available', async () => {
|
||||
unifiedPushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
localStorage.removeItem('unifiedpush_distributor');
|
||||
unifiedPushApi.listDistributors.mockResolvedValue([]);
|
||||
|
||||
await expect(registerUnifiedPushTransport()).resolves.toEqual({
|
||||
status: 'missing-distributor',
|
||||
permissionState: 'granted',
|
||||
distributors: [],
|
||||
error: 'No UnifiedPush distributor installed',
|
||||
});
|
||||
expect(unifiedPushApi.registerForPushNotifications).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('classifies temporary-unavailable registration failures distinctly', async () => {
|
||||
unifiedPushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
localStorage.setItem('unifiedpush_distributor', 'org.example.up');
|
||||
unifiedPushApi.listDistributors.mockResolvedValue(['org.example.up']);
|
||||
unifiedPushApi.registerForPushNotifications.mockRejectedValue(
|
||||
new Error('UnifiedPush registration temporarily unavailable')
|
||||
);
|
||||
|
||||
await expect(registerUnifiedPushTransport()).resolves.toEqual({
|
||||
status: 'temp-unavailable',
|
||||
permissionState: 'granted',
|
||||
distributor: 'org.example.up',
|
||||
error: 'UnifiedPush registration temporarily unavailable',
|
||||
});
|
||||
});
|
||||
|
||||
it('treats missing endpoint data as a hard failure', async () => {
|
||||
unifiedPushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
localStorage.setItem('unifiedpush_distributor', 'org.example.up');
|
||||
unifiedPushApi.listDistributors.mockResolvedValue(['org.example.up']);
|
||||
unifiedPushApi.registerForPushNotifications.mockResolvedValue('');
|
||||
|
||||
await expect(registerUnifiedPushTransport()).resolves.toMatchObject({
|
||||
status: 'hard-failure',
|
||||
error: 'UnifiedPush registration returned an invalid endpoint',
|
||||
distributor: 'org.example.up',
|
||||
});
|
||||
});
|
||||
|
||||
it('treats a blank-only endpoint as a hard failure', async () => {
|
||||
unifiedPushApi.isPermissionGranted.mockResolvedValue(true);
|
||||
localStorage.setItem('unifiedpush_distributor', 'org.example.up');
|
||||
unifiedPushApi.listDistributors.mockResolvedValue(['org.example.up']);
|
||||
unifiedPushApi.registerForPushNotifications.mockResolvedValue(' ');
|
||||
|
||||
await expect(registerUnifiedPushTransport()).resolves.toMatchObject({
|
||||
status: 'hard-failure',
|
||||
error: 'UnifiedPush registration returned an invalid endpoint',
|
||||
distributor: 'org.example.up',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('UnifiedPush distributor state helpers', () => {
|
||||
it('loads distributor state and auto-saves the sole available distributor', async () => {
|
||||
localStorage.removeItem('unifiedpush_distributor');
|
||||
unifiedPushApi.listDistributors.mockResolvedValue(['org.unifiedpush.distributor.ntfy']);
|
||||
|
||||
await expect(loadUnifiedPushDistributorState()).resolves.toEqual({
|
||||
distributors: ['org.unifiedpush.distributor.ntfy'],
|
||||
selectedDistributor: 'org.unifiedpush.distributor.ntfy',
|
||||
});
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('drops a stale saved distributor that is no longer installed', async () => {
|
||||
localStorage.setItem('unifiedpush_distributor', 'org.unifiedpush.distributor.removed');
|
||||
unifiedPushApi.listDistributors.mockResolvedValue(['org.unifiedpush.distributor.ntfy']);
|
||||
|
||||
await expect(loadUnifiedPushDistributorState()).resolves.toEqual({
|
||||
distributors: ['org.unifiedpush.distributor.ntfy'],
|
||||
selectedDistributor: 'org.unifiedpush.distributor.ntfy',
|
||||
});
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenCalledWith('org.unifiedpush.distributor.ntfy');
|
||||
});
|
||||
|
||||
it('ensures a distributor selection by auto-saving the first available distributor', async () => {
|
||||
unifiedPushApi.setDistributor.mockResolvedValue(undefined);
|
||||
await expect(
|
||||
ensureUnifiedPushDistributorSelection(
|
||||
['org.unifiedpush.distributor.ntfy', 'org.unifiedpush.distributor.nextpush'],
|
||||
''
|
||||
)
|
||||
).resolves.toBe('org.unifiedpush.distributor.ntfy');
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it('replaces a stale selected distributor with the first available one', async () => {
|
||||
unifiedPushApi.setDistributor.mockResolvedValue(undefined);
|
||||
await expect(
|
||||
ensureUnifiedPushDistributorSelection(
|
||||
['org.unifiedpush.distributor.ntfy', 'org.unifiedpush.distributor.nextpush'],
|
||||
'org.unifiedpush.distributor.removed'
|
||||
)
|
||||
).resolves.toBe('org.unifiedpush.distributor.ntfy');
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenCalledWith('org.unifiedpush.distributor.ntfy');
|
||||
});
|
||||
|
||||
it('persists a selected distributor through the transport helper', async () => {
|
||||
unifiedPushApi.setDistributor.mockResolvedValue(undefined);
|
||||
await expect(
|
||||
setUnifiedPushDistributorSelection('org.unifiedpush.distributor.nextpush')
|
||||
).resolves.toBeUndefined();
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenCalledWith(
|
||||
'org.unifiedpush.distributor.nextpush'
|
||||
);
|
||||
});
|
||||
|
||||
it('returns empty distributors when the backend is unavailable', async () => {
|
||||
localStorage.removeItem('unifiedpush_distributor');
|
||||
unifiedPushApi.listDistributors.mockRejectedValue(new Error('backend unavailable'));
|
||||
|
||||
const result = await loadUnifiedPushDistributorState();
|
||||
expect(result.distributors).toEqual([]);
|
||||
expect(result.selectedDistributor).toBe('');
|
||||
});
|
||||
|
||||
it('restores the previous distributor when a switch registration fails', async () => {
|
||||
unifiedPushApi.setDistributor.mockResolvedValue(undefined);
|
||||
const register = vi
|
||||
.fn<() => Promise<void>>()
|
||||
.mockRejectedValue(new Error('registration failed'));
|
||||
|
||||
await expect(
|
||||
switchUnifiedPushDistributorSelection(
|
||||
'org.unifiedpush.distributor.ntfy',
|
||||
'org.unifiedpush.distributor.nextpush',
|
||||
register
|
||||
)
|
||||
).rejects.toThrow('registration failed');
|
||||
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'org.unifiedpush.distributor.ntfy'
|
||||
);
|
||||
expect(unifiedPushApi.setDistributor).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'org.unifiedpush.distributor.nextpush'
|
||||
);
|
||||
expect(register).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,257 @@
|
||||
import { getUnifiedPushTransportApi } from './UnifiedPushTransportApiClient';
|
||||
|
||||
export type UnifiedPushPermissionState = 'granted' | 'denied' | 'default';
|
||||
|
||||
export type UnifiedPushRegistrationStatus =
|
||||
| 'registered'
|
||||
| 'temp-unavailable'
|
||||
| 'hard-failure'
|
||||
| 'denied'
|
||||
| 'missing-distributor';
|
||||
|
||||
export type UnifiedPushDistributorState = {
|
||||
distributors: string[];
|
||||
selectedDistributor: string;
|
||||
};
|
||||
|
||||
export type UnifiedPushRegistrationResult =
|
||||
| {
|
||||
status: 'registered';
|
||||
permissionState: 'granted';
|
||||
endpoint: string;
|
||||
distributor: string;
|
||||
}
|
||||
| {
|
||||
status: 'temp-unavailable';
|
||||
permissionState: UnifiedPushPermissionState;
|
||||
distributor?: string;
|
||||
error: string;
|
||||
}
|
||||
| {
|
||||
status: 'hard-failure';
|
||||
permissionState: UnifiedPushPermissionState;
|
||||
distributor?: string;
|
||||
error: string;
|
||||
}
|
||||
| {
|
||||
status: 'missing-distributor';
|
||||
permissionState: UnifiedPushPermissionState;
|
||||
distributors: string[];
|
||||
error: string;
|
||||
distributor?: string;
|
||||
}
|
||||
| {
|
||||
status: 'denied';
|
||||
permissionState: Exclude<UnifiedPushPermissionState, 'granted'>;
|
||||
error: string;
|
||||
};
|
||||
|
||||
const DISTRIBUTUTOR_STORAGE_KEY = 'unifiedpush_distributor';
|
||||
|
||||
export function normalizeErrorMessage(error: unknown): string {
|
||||
if (error instanceof Error) return error.message;
|
||||
if (typeof error === 'string') return error;
|
||||
if (error && typeof error === 'object') {
|
||||
const message = 'message' in error ? (error as { message?: unknown }).message : undefined;
|
||||
if (typeof message === 'string') return message;
|
||||
const code = 'code' in error ? (error as { code?: unknown }).code : undefined;
|
||||
if (typeof code === 'string') return code;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
function normalizeErrorCode(error: unknown): string {
|
||||
if (!error || typeof error !== 'object') return '';
|
||||
if ('code' in error && typeof (error as { code?: unknown }).code === 'string') {
|
||||
return String((error as { code?: string }).code).toLowerCase();
|
||||
}
|
||||
if ('name' in error && typeof (error as { name?: unknown }).name === 'string') {
|
||||
return String((error as { name?: string }).name).toLowerCase();
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function classifyUnifiedPushFailure(
|
||||
error: unknown
|
||||
): Exclude<UnifiedPushRegistrationStatus, 'registered' | 'denied'> {
|
||||
const message = normalizeErrorMessage(error).toLowerCase();
|
||||
const code = normalizeErrorCode(error);
|
||||
|
||||
if (
|
||||
code.includes('temp_unavailable') ||
|
||||
code.includes('temporary_unavailable') ||
|
||||
message.includes('temp-unavailable') ||
|
||||
message.includes('temp unavailable') ||
|
||||
message.includes('temporarily unavailable')
|
||||
) {
|
||||
return 'temp-unavailable';
|
||||
}
|
||||
|
||||
if (
|
||||
code.includes('missing_distributor') ||
|
||||
message.includes('missing distributor') ||
|
||||
message.includes('no unifiedpush distributor') ||
|
||||
message.includes('no distributor') ||
|
||||
message.includes('distributor parameter is required')
|
||||
) {
|
||||
return 'missing-distributor';
|
||||
}
|
||||
|
||||
return 'hard-failure';
|
||||
}
|
||||
|
||||
async function getUnifiedPushPermissionState(): Promise<UnifiedPushPermissionState> {
|
||||
const api = await getUnifiedPushTransportApi();
|
||||
if (await api.isPermissionGranted()) return 'granted';
|
||||
|
||||
const permission = await api.requestPermission();
|
||||
return permission === 'granted' ? 'granted' : permission;
|
||||
}
|
||||
|
||||
export async function getUnifiedPushDistributors(): Promise<string[]> {
|
||||
const api = await getUnifiedPushTransportApi();
|
||||
return api.listDistributors();
|
||||
}
|
||||
|
||||
export async function getUnifiedPushDistributor(): Promise<{ distributor: string }> {
|
||||
const distributor = localStorage.getItem(DISTRIBUTUTOR_STORAGE_KEY) ?? '';
|
||||
return { distributor };
|
||||
}
|
||||
|
||||
export async function saveUnifiedPushDistributor(distributor: string): Promise<void> {
|
||||
localStorage.setItem(DISTRIBUTUTOR_STORAGE_KEY, distributor);
|
||||
const api = await getUnifiedPushTransportApi();
|
||||
await api.setDistributor(distributor);
|
||||
}
|
||||
|
||||
export async function loadUnifiedPushDistributorState(): Promise<UnifiedPushDistributorState> {
|
||||
const [distributorResult, distributorsResult] = await Promise.allSettled([
|
||||
getUnifiedPushDistributor(),
|
||||
getUnifiedPushDistributors(),
|
||||
]);
|
||||
|
||||
const savedDistributor =
|
||||
distributorsResult.status === 'fulfilled'
|
||||
? distributorResult.status === 'fulfilled'
|
||||
? distributorResult.value.distributor
|
||||
: ''
|
||||
: '';
|
||||
const distributors = distributorsResult.status === 'fulfilled' ? distributorsResult.value : [];
|
||||
|
||||
if (savedDistributor && distributors.includes(savedDistributor)) {
|
||||
return { distributors, selectedDistributor: savedDistributor };
|
||||
}
|
||||
|
||||
if (distributors.length === 1) {
|
||||
const [onlyDistributor] = distributors;
|
||||
if (onlyDistributor) {
|
||||
await saveUnifiedPushDistributor(onlyDistributor);
|
||||
return { distributors, selectedDistributor: onlyDistributor };
|
||||
}
|
||||
}
|
||||
|
||||
return { distributors, selectedDistributor: '' };
|
||||
}
|
||||
|
||||
export async function ensureUnifiedPushDistributorSelection(
|
||||
distributors: string[],
|
||||
selectedDistributor: string
|
||||
): Promise<string> {
|
||||
const distributor =
|
||||
selectedDistributor && distributors.includes(selectedDistributor)
|
||||
? selectedDistributor
|
||||
: distributors[0];
|
||||
|
||||
if (!distributor) return '';
|
||||
|
||||
await saveUnifiedPushDistributor(distributor);
|
||||
return distributor;
|
||||
}
|
||||
|
||||
export async function setUnifiedPushDistributorSelection(distributor: string): Promise<void> {
|
||||
await saveUnifiedPushDistributor(distributor);
|
||||
}
|
||||
|
||||
export async function switchUnifiedPushDistributorSelection<T>(
|
||||
nextDistributor: string,
|
||||
previousDistributor: string,
|
||||
register: () => Promise<T>
|
||||
): Promise<T> {
|
||||
if (nextDistributor === previousDistributor) {
|
||||
return register();
|
||||
}
|
||||
|
||||
await saveUnifiedPushDistributor(nextDistributor);
|
||||
|
||||
try {
|
||||
return await register();
|
||||
} catch (error) {
|
||||
await saveUnifiedPushDistributor(previousDistributor);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function registerUnifiedPushTransport(): Promise<UnifiedPushRegistrationResult> {
|
||||
let permissionState: UnifiedPushPermissionState = 'default';
|
||||
let selectedDistributor: string | undefined;
|
||||
|
||||
try {
|
||||
permissionState = await getUnifiedPushPermissionState();
|
||||
if (permissionState !== 'granted') {
|
||||
return {
|
||||
status: 'denied',
|
||||
permissionState,
|
||||
error:
|
||||
permissionState === 'denied'
|
||||
? 'UnifiedPush permission denied'
|
||||
: 'UnifiedPush permission dismissed',
|
||||
};
|
||||
}
|
||||
|
||||
const { distributors, selectedDistributor: distributor } =
|
||||
await loadUnifiedPushDistributorState();
|
||||
selectedDistributor = distributor || undefined;
|
||||
if (!distributor) {
|
||||
return {
|
||||
status: 'missing-distributor',
|
||||
permissionState: 'granted',
|
||||
distributors,
|
||||
error:
|
||||
distributors.length === 0
|
||||
? 'No UnifiedPush distributor installed'
|
||||
: 'No UnifiedPush distributor selected',
|
||||
};
|
||||
}
|
||||
|
||||
const api = await getUnifiedPushTransportApi();
|
||||
const endpoint = await api.registerForPushNotifications();
|
||||
if (!endpoint || !endpoint.trim()) {
|
||||
return {
|
||||
status: 'hard-failure',
|
||||
permissionState: 'granted',
|
||||
error: 'UnifiedPush registration returned an invalid endpoint',
|
||||
...(selectedDistributor ? { distributor: selectedDistributor } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
status: 'registered',
|
||||
permissionState: 'granted',
|
||||
endpoint,
|
||||
distributor,
|
||||
};
|
||||
} catch (error) {
|
||||
const failureStatus = classifyUnifiedPushFailure(error);
|
||||
return {
|
||||
status: failureStatus,
|
||||
permissionState,
|
||||
error: normalizeErrorMessage(error),
|
||||
...(selectedDistributor ? { distributor: selectedDistributor } : {}),
|
||||
} as UnifiedPushRegistrationResult;
|
||||
}
|
||||
}
|
||||
|
||||
export async function unregisterUnifiedPushTransport(): Promise<void> {
|
||||
const api = await getUnifiedPushTransportApi();
|
||||
await api.unregisterForPushNotifications();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
export type UnifiedPushTransportApi = {
|
||||
isPermissionGranted: () => Promise<boolean>;
|
||||
requestPermission: () => Promise<NotificationPermission>;
|
||||
registerForPushNotifications: () => Promise<string>;
|
||||
unregisterForPushNotifications: () => Promise<void>;
|
||||
listDistributors: () => Promise<string[]>;
|
||||
setDistributor: (name: string) => Promise<void>;
|
||||
setToken: (token: string) => Promise<void>;
|
||||
};
|
||||
|
||||
export async function getUnifiedPushTransportApi(): Promise<UnifiedPushTransportApi> {
|
||||
const notificationsApi = await import('@choochmeque/tauri-plugin-notifications-api');
|
||||
return {
|
||||
isPermissionGranted: notificationsApi.isPermissionGranted,
|
||||
requestPermission: notificationsApi.requestPermission,
|
||||
registerForPushNotifications: notificationsApi.registerForPushNotifications,
|
||||
unregisterForPushNotifications: notificationsApi.unregisterForPushNotifications,
|
||||
listDistributors: notificationsApi.listDistributors,
|
||||
setDistributor: notificationsApi.setDistributor,
|
||||
setToken: notificationsApi.setToken,
|
||||
};
|
||||
}
|
||||
@@ -5,6 +5,7 @@ export type SettingsSectionId =
|
||||
| 'appearance'
|
||||
| 'notifications'
|
||||
| 'devices'
|
||||
| 'desktop'
|
||||
| 'emojis'
|
||||
| 'developer-tools'
|
||||
| 'experimental'
|
||||
@@ -23,6 +24,7 @@ export const settingsSections = [
|
||||
{ id: 'appearance', label: 'Appearance' },
|
||||
{ id: 'notifications', label: 'Notifications' },
|
||||
{ id: 'devices', label: 'Devices' },
|
||||
{ id: 'desktop', label: 'Desktop' },
|
||||
{ id: 'emojis', label: 'Emojis & Stickers' },
|
||||
{ id: 'developer-tools', label: 'Developer Tools' },
|
||||
{ id: 'experimental', label: 'Experimental' },
|
||||
|
||||
@@ -189,6 +189,7 @@ const settingsLinkFocusIdsBySection: Record<SettingsSectionId, readonly string[]
|
||||
'export-messages-data',
|
||||
'import-messages-data',
|
||||
],
|
||||
desktop: [],
|
||||
emojis: ['default-pack', 'select-pack'],
|
||||
'developer-tools': [
|
||||
'access-token',
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
OpenIDRequestState,
|
||||
} from 'matrix-widget-api';
|
||||
import type { MatrixClient, Room } from '$types/matrix-sdk';
|
||||
import { uploadContentToServer } from '$utils/matrix';
|
||||
import {
|
||||
EventType,
|
||||
type IContent,
|
||||
@@ -332,7 +333,7 @@ export class GenericWidgetDriver extends WidgetDriver {
|
||||
}
|
||||
|
||||
public async uploadFile(file: XMLHttpRequestBodyInit): Promise<{ contentUri: string }> {
|
||||
const uploadResult = await this.mxClient.uploadContent(file);
|
||||
const uploadResult = await uploadContentToServer(this.mxClient, file);
|
||||
return { contentUri: uploadResult.content_uri };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
/**
|
||||
* Auto-generated TypeScript bindings for Tauri commands
|
||||
* Generated by tauri-typegen v0.5.0
|
||||
* Generated at: 2026-07-18T21:46:21.964297+00:00
|
||||
* Generator: none
|
||||
*
|
||||
* Do not edit manually - regenerate using: cargo tauri-typegen generate
|
||||
*/
|
||||
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import * as types from './types';
|
||||
|
||||
export async function abortLoopbackFetch(params: types.AbortLoopbackFetchParams): Promise<void> {
|
||||
return invoke('abort_loopback_fetch', params);
|
||||
}
|
||||
|
||||
export async function clearMediaSession(): Promise<void> {
|
||||
return invoke('clear_media_session');
|
||||
}
|
||||
|
||||
export async function getDesktopRuntimeState(): Promise<types.DesktopRuntimeState> {
|
||||
return invoke('get_desktop_runtime_state');
|
||||
}
|
||||
|
||||
export async function hideSnapOverlay(): Promise<void> {
|
||||
return invoke('hide_snap_overlay');
|
||||
}
|
||||
|
||||
export async function isWindowTrackingActive(): Promise<boolean> {
|
||||
return invoke('is_window_tracking_active');
|
||||
}
|
||||
|
||||
export async function loopbackFetch(params: types.LoopbackFetchParams): Promise<types.LoopbackFetchResponse> {
|
||||
return invoke('loopback_fetch', params);
|
||||
}
|
||||
|
||||
export async function saveDownload(params: types.SaveDownloadParams): Promise<boolean> {
|
||||
return invoke('save_download', params);
|
||||
}
|
||||
|
||||
export async function setMediaSession(params: types.SetMediaSessionParams): Promise<void> {
|
||||
return invoke('set_media_session', params);
|
||||
}
|
||||
|
||||
export async function setNavigationBarColor(params: types.SetNavigationBarColorParams): Promise<void> {
|
||||
return invoke('set_navigation_bar_color', params);
|
||||
}
|
||||
|
||||
export async function setStatusBarColor(params: types.SetStatusBarColorParams): Promise<void> {
|
||||
return invoke('set_status_bar_color', params);
|
||||
}
|
||||
|
||||
export async function showSnapOverlay(): Promise<void> {
|
||||
return invoke('show_snap_overlay');
|
||||
}
|
||||
|
||||
export async function startWindowTrackingWithTarget(params: types.StartWindowTrackingWithTargetParams): Promise<void> {
|
||||
return invoke('start_window_tracking_with_target', params);
|
||||
}
|
||||
|
||||
export async function stopWindowTracking(): Promise<void> {
|
||||
return invoke('stop_window_tracking');
|
||||
}
|
||||
|
||||
export async function syncDesktopSettings(params: types.SyncDesktopSettingsParams): Promise<types.DesktopRuntimeState> {
|
||||
return invoke('sync_desktop_settings', params);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type DesktopRuntimeState = { trayAvailable: boolean };
|
||||
@@ -0,0 +1,3 @@
|
||||
// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.
|
||||
|
||||
export type DesktopSettings = { closeToBackgroundOnClose: boolean; showSystemTrayIcon: boolean };
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* Auto-generated TypeScript bindings for Tauri commands
|
||||
* Generated by tauri-typegen v0.5.0
|
||||
* Generated at: 2026-07-18T21:46:21.964597+00:00
|
||||
* Generator: none
|
||||
*
|
||||
* Do not edit manually - regenerate using: cargo tauri-typegen generate
|
||||
*/
|
||||
|
||||
export * from './types';
|
||||
export * from './commands';
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* Auto-generated TypeScript bindings for Tauri commands
|
||||
* Generated by tauri-typegen v0.5.0
|
||||
* Generated at: 2026-07-18T21:46:21.963724+00:00
|
||||
* Generator: none
|
||||
*
|
||||
* Do not edit manually - regenerate using: cargo tauri-typegen generate
|
||||
*/
|
||||
|
||||
export interface DesktopRuntimeState {
|
||||
trayAvailable: boolean;
|
||||
}
|
||||
|
||||
export interface DesktopSettings {
|
||||
closeToBackgroundOnClose: boolean;
|
||||
showSystemTrayIcon: boolean;
|
||||
}
|
||||
|
||||
export interface LoopbackFetchRequest {
|
||||
requestId: string;
|
||||
method: string;
|
||||
url: string;
|
||||
headers: [string, string][];
|
||||
body?: number[] | null;
|
||||
}
|
||||
|
||||
export interface LoopbackFetchResponse {
|
||||
status: number;
|
||||
statusText: string;
|
||||
url: string;
|
||||
headers: [string, string][];
|
||||
body: number[];
|
||||
}
|
||||
|
||||
export interface WindowTarget {
|
||||
window_class?: string | null;
|
||||
exe_name?: string | null;
|
||||
}
|
||||
|
||||
export interface AbortLoopbackFetchParams {
|
||||
requestId: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface LoopbackFetchParams {
|
||||
request: LoopbackFetchRequest;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface SaveDownloadParams {
|
||||
filename: string;
|
||||
bytes: number[];
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface SetMediaSessionParams {
|
||||
baseUrl: string;
|
||||
token: string;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface SetNavigationBarColorParams {
|
||||
color: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface SetStatusBarColorParams {
|
||||
color: number;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface StartWindowTrackingWithTargetParams {
|
||||
target: WindowTarget;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
export interface SyncDesktopSettingsParams {
|
||||
settings: DesktopSettings;
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -1,78 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
|
||||
const imageBlobCache = new Map<string, string>();
|
||||
const inflightRequests = new Map<string, Promise<string>>();
|
||||
|
||||
export function getBlobCacheStats(): { cacheSize: number; inflightCount: number } {
|
||||
return { cacheSize: imageBlobCache.size, inflightCount: inflightRequests.size };
|
||||
}
|
||||
|
||||
export function useBlobCache(url?: string): string | undefined {
|
||||
const [cacheState, setCacheState] = useState<{ sourceUrl?: string; blobUrl?: string }>({
|
||||
sourceUrl: url,
|
||||
blobUrl: url ? imageBlobCache.get(url) : undefined,
|
||||
});
|
||||
|
||||
if (url !== cacheState.sourceUrl) {
|
||||
setCacheState({
|
||||
sourceUrl: url,
|
||||
blobUrl: url ? imageBlobCache.get(url) : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!url || imageBlobCache.has(url)) return undefined;
|
||||
|
||||
let isMounted = true;
|
||||
|
||||
const fetchBlob = async () => {
|
||||
if (inflightRequests.has(url)) {
|
||||
try {
|
||||
const existingBlobUrl = await inflightRequests.get(url);
|
||||
if (isMounted) setCacheState({ sourceUrl: url, blobUrl: existingBlobUrl });
|
||||
} catch {
|
||||
// Inflight request failed, silently ignore (consistent with fetchBlob behavior)
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const requestPromise = (async () => {
|
||||
try {
|
||||
const res = await fetch(url, { mode: 'cors' });
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch blob: ${res.status} ${res.statusText}`);
|
||||
}
|
||||
const blob = await res.blob();
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
|
||||
imageBlobCache.set(url, objectUrl);
|
||||
return objectUrl;
|
||||
} catch (e) {
|
||||
inflightRequests.delete(url);
|
||||
throw e;
|
||||
}
|
||||
})();
|
||||
|
||||
inflightRequests.set(url, requestPromise);
|
||||
|
||||
try {
|
||||
const finalBlobUrl = await requestPromise;
|
||||
if (isMounted) {
|
||||
setCacheState({ sourceUrl: url, blobUrl: finalBlobUrl });
|
||||
}
|
||||
} catch {
|
||||
// silency fail... mrow
|
||||
} finally {
|
||||
inflightRequests.delete(url);
|
||||
}
|
||||
};
|
||||
|
||||
fetchBlob();
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [url]);
|
||||
|
||||
return cacheState.blobUrl || url;
|
||||
}
|
||||
@@ -175,8 +175,26 @@ export const useCallEmbedPlacementSync = (containerViewRef: RefObject<HTMLDivEle
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
syncCallEmbedPlacement();
|
||||
window.addEventListener('scroll', syncCallEmbedPlacement, true);
|
||||
return () => window.removeEventListener('scroll', syncCallEmbedPlacement, true);
|
||||
}, [syncCallEmbedPlacement]);
|
||||
let raf = 0;
|
||||
let last = '';
|
||||
const tick = () => {
|
||||
const embedEl = callEmbedRef.current;
|
||||
const container = containerViewRef.current;
|
||||
if (embedEl && container) {
|
||||
const rect = container.getBoundingClientRect();
|
||||
const key = `${rect.top}|${rect.left}|${rect.width}|${rect.height}`;
|
||||
if (key !== last) {
|
||||
last = key;
|
||||
embedEl.style.position = 'fixed';
|
||||
embedEl.style.top = `${rect.top}px`;
|
||||
embedEl.style.left = `${rect.left}px`;
|
||||
embedEl.style.width = `${rect.width}px`;
|
||||
embedEl.style.height = `${rect.height}px`;
|
||||
}
|
||||
}
|
||||
raf = requestAnimationFrame(tick);
|
||||
};
|
||||
raf = requestAnimationFrame(tick);
|
||||
return () => cancelAnimationFrame(raf);
|
||||
}, [callEmbedRef, containerViewRef]);
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createContext, useContext } from 'react';
|
||||
import type { PushTransportConfig } from '$features/settings/notifications/NotificationTransport';
|
||||
|
||||
import type { Settings } from '$state/settings';
|
||||
|
||||
@@ -25,6 +26,23 @@ export type ClientConfig = {
|
||||
pushNotifyUrl?: string;
|
||||
vapidPublicKey?: string;
|
||||
webPushAppID?: string;
|
||||
nativePushAppID?: string;
|
||||
unifiedPushAppID?: string;
|
||||
unifiedPushGatewayUrl?: string;
|
||||
};
|
||||
|
||||
pushTransport?: PushTransportConfig;
|
||||
|
||||
slidingSync?: {
|
||||
enabled?: boolean;
|
||||
proxyBaseUrl?: string;
|
||||
bootstrapClassicOnColdCache?: boolean;
|
||||
listPageSize?: number;
|
||||
timelineLimit?: number;
|
||||
pollTimeoutMs?: number;
|
||||
maxRooms?: number;
|
||||
includeInviteList?: boolean;
|
||||
probeTimeoutMs?: number;
|
||||
};
|
||||
|
||||
featuredCommunities?: {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import type { MatrixClient } from '$types/matrix-sdk';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import { useMatrixClient } from './useMatrixClient';
|
||||
|
||||
export interface IntegrationManager {
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import type { ReactNode } from 'react';
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import { Provider, createStore } from 'jotai';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const platform = vi.hoisted(() => ({
|
||||
hasServiceWorker: vi.fn<() => boolean>(),
|
||||
hasControllingServiceWorker: vi.fn<() => boolean>(),
|
||||
}));
|
||||
|
||||
const mediaTransport = vi.hoisted(() => ({
|
||||
fetchMediaBlob: vi.fn<(url: string) => Promise<Blob>>(),
|
||||
getCurrentMediaSessionScope: vi.fn<() => string>(() => 'anonymous'),
|
||||
}));
|
||||
|
||||
const tauriApi = vi.hoisted(() => ({
|
||||
isTauri: vi.fn<() => boolean>(),
|
||||
convertFileSrc: vi.fn<(url: string, protocol: string) => string>(
|
||||
(url: string, protocol: string) => `${protocol}://${url}`
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock('$utils/platform', () => platform);
|
||||
vi.mock('$utils/mediaTransport', () => mediaTransport);
|
||||
vi.mock('@tauri-apps/api/core', () => tauriApi);
|
||||
|
||||
describe('useRenderableMediaUrl', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
platform.hasServiceWorker.mockReset();
|
||||
platform.hasControllingServiceWorker.mockReset();
|
||||
mediaTransport.fetchMediaBlob.mockReset();
|
||||
mediaTransport.getCurrentMediaSessionScope.mockReset();
|
||||
mediaTransport.getCurrentMediaSessionScope.mockReturnValue('anonymous');
|
||||
tauriApi.isTauri.mockReset();
|
||||
tauriApi.convertFileSrc.mockReset();
|
||||
tauriApi.convertFileSrc.mockImplementation(
|
||||
(url: string, protocol: string) => `${protocol}://${url}`
|
||||
);
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:rendered-media');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
Object.defineProperty(navigator, 'serviceWorker', {
|
||||
configurable: true,
|
||||
value: {
|
||||
controller: null,
|
||||
ready: Promise.resolve({}),
|
||||
addEventListener: vi.fn<(...args: unknown[]) => void>(),
|
||||
removeEventListener: vi.fn<(...args: unknown[]) => void>(),
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('returns the original url when a service worker runtime is available', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(true);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(true);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const { result } = renderHook(() => useRenderableMediaUrl('https://example.org/media.png'));
|
||||
|
||||
expect(result.current).toBe('https://example.org/media.png');
|
||||
expect(mediaTransport.fetchMediaBlob).not.toHaveBeenCalled();
|
||||
}, 20_000);
|
||||
|
||||
it('rejects non-browser-safe media urls in service worker runtimes', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(true);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(true);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
const javascriptUrlValue = ['javascript', 'alert(1)'].join(':');
|
||||
|
||||
const javascriptUrl = renderHook(() => useRenderableMediaUrl(javascriptUrlValue));
|
||||
const mxcUrl = renderHook(() => useRenderableMediaUrl('mxc://example.org/media-id'));
|
||||
const relativeUrl = renderHook(() => useRenderableMediaUrl('/relative/path.png'));
|
||||
|
||||
expect(javascriptUrl.result.current).toBeUndefined();
|
||||
expect(mxcUrl.result.current).toBeUndefined();
|
||||
expect(relativeUrl.result.current).toBeUndefined();
|
||||
expect(mediaTransport.fetchMediaBlob).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns a blob url in no-service-worker runtimes', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(false);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(false);
|
||||
mediaTransport.fetchMediaBlob.mockResolvedValue(new Blob(['media'], { type: 'image/png' }));
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const { result } = renderHook(() => useRenderableMediaUrl('https://example.org/media.png'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBe('blob:rendered-media');
|
||||
});
|
||||
|
||||
expect(mediaTransport.fetchMediaBlob).toHaveBeenCalledWith('https://example.org/media.png');
|
||||
expect(URL.createObjectURL).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('does not fetch invalid media urls in no-service-worker runtimes', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(false);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(false);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const { result } = renderHook(() => useRenderableMediaUrl('data:text/html,boom'));
|
||||
|
||||
expect(result.current).toBeUndefined();
|
||||
expect(mediaTransport.fetchMediaBlob).not.toHaveBeenCalled();
|
||||
expect(URL.createObjectURL).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns existing blob urls unchanged in no-service-worker runtimes', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(false);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(false);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useRenderableMediaUrl('blob:http://localhost:8080/blob-id')
|
||||
);
|
||||
|
||||
expect(result.current).toBe('blob:http://localhost:8080/blob-id');
|
||||
expect(mediaTransport.fetchMediaBlob).not.toHaveBeenCalled();
|
||||
expect(URL.createObjectURL).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('uses the blob-backed path until the service worker controls the page', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(true);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(false);
|
||||
mediaTransport.fetchMediaBlob.mockResolvedValue(new Blob(['media'], { type: 'image/png' }));
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const { result } = renderHook(() => useRenderableMediaUrl('https://example.org/media.png'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBe('blob:rendered-media');
|
||||
});
|
||||
|
||||
expect(mediaTransport.fetchMediaBlob).toHaveBeenCalledWith('https://example.org/media.png');
|
||||
});
|
||||
|
||||
it('refetches blob-backed media when the active session changes', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(false);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(false);
|
||||
mediaTransport.fetchMediaBlob
|
||||
.mockResolvedValueOnce(new Blob(['alice'], { type: 'image/png' }))
|
||||
.mockResolvedValueOnce(new Blob(['bob'], { type: 'image/png' }));
|
||||
vi.mocked(URL.createObjectURL)
|
||||
.mockReturnValueOnce('blob:alice-media')
|
||||
.mockReturnValueOnce('blob:bob-media');
|
||||
|
||||
const { activeSessionIdAtom } = await import('$state/sessions');
|
||||
const store = createStore();
|
||||
store.set(activeSessionIdAtom, '@alice:example.org');
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<Provider store={store}>{children}</Provider>
|
||||
);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const { result } = renderHook(() => useRenderableMediaUrl('https://example.org/media.png'), {
|
||||
wrapper,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBe('blob:alice-media');
|
||||
});
|
||||
|
||||
act(() => {
|
||||
store.set(activeSessionIdAtom, '@bob:example.org');
|
||||
});
|
||||
|
||||
expect(result.current).toBeUndefined();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).toBe('blob:bob-media');
|
||||
});
|
||||
|
||||
expect(mediaTransport.fetchMediaBlob).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'https://example.org/media.png'
|
||||
);
|
||||
expect(mediaTransport.fetchMediaBlob).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'https://example.org/media.png'
|
||||
);
|
||||
});
|
||||
|
||||
it('revokes the object url when the last consumer unmounts', async () => {
|
||||
platform.hasServiceWorker.mockReturnValue(false);
|
||||
platform.hasControllingServiceWorker.mockReturnValue(false);
|
||||
mediaTransport.fetchMediaBlob.mockResolvedValue(new Blob(['media'], { type: 'image/png' }));
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const first = renderHook(() => useRenderableMediaUrl('https://example.org/media.png'));
|
||||
const second = renderHook(() => useRenderableMediaUrl('https://example.org/media.png'));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(first.result.current).toBe('blob:rendered-media');
|
||||
expect(second.result.current).toBe('blob:rendered-media');
|
||||
});
|
||||
|
||||
first.unmount();
|
||||
expect(URL.revokeObjectURL).not.toHaveBeenCalled();
|
||||
|
||||
second.unmount();
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:rendered-media');
|
||||
});
|
||||
|
||||
it('rewrites raw authenticated-media https URLs under Tauri', async () => {
|
||||
tauriApi.isTauri.mockReturnValue(true);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const rawAuthUrl =
|
||||
'https://matrix.example.org/_matrix/client/v1/media/thumbnail/example.org/abc123?width=96&height=96';
|
||||
const { result } = renderHook(() => useRenderableMediaUrl(rawAuthUrl));
|
||||
|
||||
expect(result.current).toBe(`sable-media://${rawAuthUrl}&__sable_media_cache=2`);
|
||||
expect(tauriApi.convertFileSrc).toHaveBeenCalledWith(rawAuthUrl, 'sable-media');
|
||||
});
|
||||
|
||||
it('passes through already-rewritten sable-media:// URLs under Tauri', async () => {
|
||||
tauriApi.isTauri.mockReturnValue(true);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const rewrittenUrl =
|
||||
'sable-media://https://matrix.example.org/_matrix/client/v1/media/thumbnail/example.org/abc123';
|
||||
const { result } = renderHook(() => useRenderableMediaUrl(rewrittenUrl));
|
||||
|
||||
expect(result.current).toBe(`${rewrittenUrl}?__sable_media_cache=2`);
|
||||
expect(tauriApi.convertFileSrc).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes through non-authenticated URLs unchanged under Tauri', async () => {
|
||||
tauriApi.isTauri.mockReturnValue(true);
|
||||
const { useRenderableMediaUrl } = await import('./useRenderableMediaUrl');
|
||||
|
||||
const { result } = renderHook(() => useRenderableMediaUrl('https://example.org/avatar.png'));
|
||||
|
||||
expect(result.current).toBe('https://example.org/avatar.png');
|
||||
expect(tauriApi.convertFileSrc).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,199 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { useAtomValue } from 'jotai';
|
||||
import { isTauri } from '@tauri-apps/api/core';
|
||||
import { activeSessionIdAtom } from '$state/sessions';
|
||||
import { fetchMediaBlob, getCurrentMediaSessionScope } from '$utils/mediaTransport';
|
||||
import { hasControllingServiceWorker, hasServiceWorker } from '$utils/platform';
|
||||
import { rewriteAuthenticatedMediaUrl } from '$utils/matrix';
|
||||
|
||||
type ObjectUrlEntry = {
|
||||
refs: number;
|
||||
settled: boolean;
|
||||
objectUrl?: string;
|
||||
promise: Promise<string>;
|
||||
};
|
||||
|
||||
type ResolvedMediaUrlState = {
|
||||
cacheKey?: string;
|
||||
url?: string;
|
||||
};
|
||||
|
||||
const objectUrlCache = new Map<string, ObjectUrlEntry>();
|
||||
const inflightRequests = new Map<string, Promise<string>>();
|
||||
|
||||
function getObjectUrlCacheKey(sessionScope: string, url: string): string {
|
||||
return `${sessionScope}\x00${url}`;
|
||||
}
|
||||
|
||||
function normalizeRenderableMediaUrl(url: string | undefined): string | undefined {
|
||||
if (!url) return undefined;
|
||||
if (url.startsWith('blob:')) return url;
|
||||
|
||||
try {
|
||||
const parsed = new URL(url);
|
||||
if (parsed.protocol === 'http:' || parsed.protocol === 'https:') {
|
||||
return parsed.toString();
|
||||
}
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function createObjectUrlEntry(cacheKey: string, url: string): ObjectUrlEntry {
|
||||
const entry = {
|
||||
refs: 0,
|
||||
settled: false,
|
||||
objectUrl: undefined,
|
||||
promise: Promise.resolve(''),
|
||||
} as ObjectUrlEntry;
|
||||
|
||||
entry.promise = fetchMediaBlob(url)
|
||||
.then((blob) => {
|
||||
const objectUrl = URL.createObjectURL(blob);
|
||||
entry.objectUrl = objectUrl;
|
||||
return objectUrl;
|
||||
})
|
||||
.finally(() => {
|
||||
entry.settled = true;
|
||||
inflightRequests.delete(cacheKey);
|
||||
if (entry.refs === 0 && entry.objectUrl) {
|
||||
URL.revokeObjectURL(entry.objectUrl);
|
||||
objectUrlCache.delete(cacheKey);
|
||||
}
|
||||
});
|
||||
|
||||
objectUrlCache.set(cacheKey, entry);
|
||||
inflightRequests.set(cacheKey, entry.promise);
|
||||
|
||||
return entry;
|
||||
}
|
||||
|
||||
function retainObjectUrlEntry(cacheKey: string, url: string): ObjectUrlEntry {
|
||||
const entry = objectUrlCache.get(cacheKey) ?? createObjectUrlEntry(cacheKey, url);
|
||||
entry.refs += 1;
|
||||
return entry;
|
||||
}
|
||||
|
||||
function releaseObjectUrlEntry(cacheKey: string): void {
|
||||
const entry = objectUrlCache.get(cacheKey);
|
||||
if (!entry) return;
|
||||
|
||||
entry.refs -= 1;
|
||||
if (entry.refs > 0 || !entry.settled) return;
|
||||
if (entry.objectUrl) {
|
||||
URL.revokeObjectURL(entry.objectUrl);
|
||||
}
|
||||
objectUrlCache.delete(cacheKey);
|
||||
}
|
||||
|
||||
export function getRenderableMediaUrlStats(): { cacheSize: number; inflightCount: number } {
|
||||
return { cacheSize: objectUrlCache.size, inflightCount: inflightRequests.size };
|
||||
}
|
||||
|
||||
export function useRenderableMediaUrl(url: string | undefined): string | undefined {
|
||||
const tauri = isTauri();
|
||||
const activeSessionId = useAtomValue(activeSessionIdAtom);
|
||||
const sessionScope = activeSessionId ?? getCurrentMediaSessionScope();
|
||||
const renderableUrl = normalizeRenderableMediaUrl(url);
|
||||
const objectUrlCacheKey =
|
||||
renderableUrl && !renderableUrl.startsWith('blob:')
|
||||
? getObjectUrlCacheKey(sessionScope, renderableUrl)
|
||||
: undefined;
|
||||
const [usesControlledServiceWorker, setUsesControlledServiceWorker] = useState(() =>
|
||||
hasControllingServiceWorker()
|
||||
);
|
||||
const needsBlob = !usesControlledServiceWorker;
|
||||
const usesExistingObjectUrl = renderableUrl?.startsWith('blob:') ?? false;
|
||||
const [resolvedState, setResolvedState] = useState<ResolvedMediaUrlState>(() => ({
|
||||
cacheKey: objectUrlCacheKey,
|
||||
url: needsBlob && !usesExistingObjectUrl ? undefined : renderableUrl,
|
||||
}));
|
||||
|
||||
useEffect(() => {
|
||||
if (tauri) return undefined;
|
||||
if (!hasServiceWorker()) {
|
||||
setUsesControlledServiceWorker(false);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { serviceWorker } = navigator;
|
||||
if (!serviceWorker) {
|
||||
setUsesControlledServiceWorker(false);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const updateControlState = () => {
|
||||
setUsesControlledServiceWorker(hasControllingServiceWorker());
|
||||
};
|
||||
|
||||
updateControlState();
|
||||
serviceWorker.addEventListener('controllerchange', updateControlState);
|
||||
serviceWorker.ready.then(updateControlState).catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
serviceWorker.removeEventListener('controllerchange', updateControlState);
|
||||
};
|
||||
}, [tauri]);
|
||||
|
||||
useEffect(() => {
|
||||
if (tauri) return undefined;
|
||||
if (!renderableUrl) {
|
||||
setResolvedState({ cacheKey: undefined, url: undefined });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!needsBlob) {
|
||||
setResolvedState({ cacheKey: undefined, url: renderableUrl });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (usesExistingObjectUrl) {
|
||||
setResolvedState({ cacheKey: undefined, url: renderableUrl });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!objectUrlCacheKey) {
|
||||
setResolvedState({ cacheKey: undefined, url: undefined });
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const entry = retainObjectUrlEntry(objectUrlCacheKey, renderableUrl);
|
||||
let cancelled = false;
|
||||
const { objectUrl } = entry;
|
||||
|
||||
setResolvedState({ cacheKey: objectUrlCacheKey, url: objectUrl });
|
||||
|
||||
entry.promise
|
||||
.then((resolvedObjectUrl) => {
|
||||
if (!cancelled) {
|
||||
setResolvedState({ cacheKey: objectUrlCacheKey, url: resolvedObjectUrl });
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
if (!cancelled) {
|
||||
setResolvedState({ cacheKey: objectUrlCacheKey, url: undefined });
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
releaseObjectUrlEntry(objectUrlCacheKey);
|
||||
};
|
||||
}, [needsBlob, objectUrlCacheKey, renderableUrl, tauri, usesExistingObjectUrl]);
|
||||
|
||||
if (tauri) {
|
||||
return rewriteAuthenticatedMediaUrl(url ?? null) ?? undefined;
|
||||
}
|
||||
|
||||
if (!needsBlob || usesExistingObjectUrl) {
|
||||
return renderableUrl;
|
||||
}
|
||||
|
||||
if (resolvedState.cacheKey !== objectUrlCacheKey) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return resolvedState.url;
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback } from 'react';
|
||||
import { startTransition, useCallback } from 'react';
|
||||
import type { NavigateOptions } from 'react-router-dom';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useAtomValue } from 'jotai';
|
||||
@@ -28,7 +28,8 @@ export const useRoomNavigate = () => {
|
||||
const navigateSpace = useCallback(
|
||||
(roomId: string) => {
|
||||
const roomIdOrAlias = getCanonicalAliasOrRoomId(mx, roomId);
|
||||
navigate(getSpacePath(roomIdOrAlias));
|
||||
// Render the (heavy) destination off the urgent path so the tap doesn't freeze the UI.
|
||||
startTransition(() => navigate(getSpacePath(roomIdOrAlias)));
|
||||
},
|
||||
[mx, navigate]
|
||||
);
|
||||
@@ -49,19 +50,21 @@ export const useRoomNavigate = () => {
|
||||
|
||||
const pSpaceIdOrAlias = getCanonicalAliasOrRoomId(mx, parentSpace);
|
||||
|
||||
navigate(
|
||||
getSpaceRoomPath(pSpaceIdOrAlias, openSpaceTimeline ? roomId : roomIdOrAlias, eventId),
|
||||
opts
|
||||
startTransition(() =>
|
||||
navigate(
|
||||
getSpaceRoomPath(pSpaceIdOrAlias, openSpaceTimeline ? roomId : roomIdOrAlias, eventId),
|
||||
opts
|
||||
)
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (mDirects.has(roomId)) {
|
||||
navigate(getDirectRoomPath(roomIdOrAlias, eventId), opts);
|
||||
startTransition(() => navigate(getDirectRoomPath(roomIdOrAlias, eventId), opts));
|
||||
return;
|
||||
}
|
||||
|
||||
navigate(getHomeRoomPath(roomIdOrAlias, eventId), opts);
|
||||
startTransition(() => navigate(getHomeRoomPath(roomIdOrAlias, eventId), opts));
|
||||
},
|
||||
[mx, navigate, spaceSelectedId, roomToParents, mDirects, developerTools]
|
||||
);
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Session } from '$state/sessions';
|
||||
|
||||
const mediaTransport = vi.hoisted(() => ({
|
||||
fetchMediaBlob: vi.fn<(url: string) => Promise<Blob>>(),
|
||||
}));
|
||||
|
||||
vi.mock('$utils/mediaTransport', () => mediaTransport);
|
||||
|
||||
describe('useSessionProfiles', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
mediaTransport.fetchMediaBlob.mockReset();
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async (input: RequestInfo | URL) => {
|
||||
const url =
|
||||
typeof input === 'string' ? input : input instanceof URL ? input.href : input.url;
|
||||
|
||||
if (url.endsWith('/_matrix/client/v3/profile/%40alice%3Aexample.org')) {
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
displayname: 'Alice',
|
||||
avatar_url: 'mxc://example.org/avatar',
|
||||
}),
|
||||
{
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return new Response('', { status: 404 });
|
||||
})
|
||||
);
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:session-avatar');
|
||||
vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('fetches session avatar thumbnails through the media transport with session-scoped auth', async () => {
|
||||
const avatarBlob = new Blob(['avatar'], { type: 'image/png' });
|
||||
mediaTransport.fetchMediaBlob.mockResolvedValue(avatarBlob);
|
||||
|
||||
const sessions: Session[] = [
|
||||
{
|
||||
baseUrl: 'https://matrix.example.org',
|
||||
userId: '@alice:example.org',
|
||||
deviceId: 'DEVICE',
|
||||
accessToken: 'alice-token',
|
||||
},
|
||||
];
|
||||
|
||||
const { useSessionProfiles } = await import('./useSessionProfiles');
|
||||
const { result } = renderHook(() => useSessionProfiles(sessions));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current['@alice:example.org']).toEqual({
|
||||
displayName: 'Alice',
|
||||
avatarHttpUrl: 'blob:session-avatar',
|
||||
});
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledTimes(1);
|
||||
expect(mediaTransport.fetchMediaBlob).toHaveBeenCalledWith(
|
||||
'https://matrix.example.org/_matrix/client/v1/media/thumbnail/example.org/avatar?width=96&height=96&method=crop',
|
||||
{
|
||||
accessToken: 'alice-token',
|
||||
sessionScope: '@alice:example.org',
|
||||
}
|
||||
);
|
||||
expect(URL.createObjectURL).toHaveBeenCalledWith(avatarBlob);
|
||||
});
|
||||
|
||||
it('refetches profiles when the same user session is reauthenticated', async () => {
|
||||
mediaTransport.fetchMediaBlob
|
||||
.mockResolvedValueOnce(new Blob(['avatar-1'], { type: 'image/png' }))
|
||||
.mockResolvedValueOnce(new Blob(['avatar-2'], { type: 'image/png' }));
|
||||
vi.mocked(URL.createObjectURL)
|
||||
.mockReturnValueOnce('blob:session-avatar-1')
|
||||
.mockReturnValueOnce('blob:session-avatar-2');
|
||||
|
||||
const { useSessionProfiles } = await import('./useSessionProfiles');
|
||||
const { result, rerender } = renderHook(
|
||||
({ sessions }: { sessions: Session[] }) => useSessionProfiles(sessions),
|
||||
{
|
||||
initialProps: {
|
||||
sessions: [
|
||||
{
|
||||
baseUrl: 'https://matrix.example.org',
|
||||
userId: '@alice:example.org',
|
||||
deviceId: 'DEVICE',
|
||||
accessToken: 'alice-token-1',
|
||||
},
|
||||
],
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current['@alice:example.org']).toEqual({
|
||||
displayName: 'Alice',
|
||||
avatarHttpUrl: 'blob:session-avatar-1',
|
||||
});
|
||||
});
|
||||
|
||||
rerender({
|
||||
sessions: [
|
||||
{
|
||||
baseUrl: 'https://matrix.example.org',
|
||||
userId: '@alice:example.org',
|
||||
deviceId: 'DEVICE',
|
||||
accessToken: 'alice-token-2',
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current['@alice:example.org']).toEqual({
|
||||
displayName: 'Alice',
|
||||
avatarHttpUrl: 'blob:session-avatar-2',
|
||||
});
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
expect(mediaTransport.fetchMediaBlob).toHaveBeenNthCalledWith(
|
||||
1,
|
||||
'https://matrix.example.org/_matrix/client/v1/media/thumbnail/example.org/avatar?width=96&height=96&method=crop',
|
||||
{
|
||||
accessToken: 'alice-token-1',
|
||||
sessionScope: '@alice:example.org',
|
||||
}
|
||||
);
|
||||
expect(mediaTransport.fetchMediaBlob).toHaveBeenNthCalledWith(
|
||||
2,
|
||||
'https://matrix.example.org/_matrix/client/v1/media/thumbnail/example.org/avatar?width=96&height=96&method=crop',
|
||||
{
|
||||
accessToken: 'alice-token-2',
|
||||
sessionScope: '@alice:example.org',
|
||||
}
|
||||
);
|
||||
});
|
||||
|
||||
it('revokes avatar blob urls on unmount', async () => {
|
||||
mediaTransport.fetchMediaBlob.mockResolvedValue(new Blob(['avatar'], { type: 'image/png' }));
|
||||
|
||||
const sessions: Session[] = [
|
||||
{
|
||||
baseUrl: 'https://matrix.example.org',
|
||||
userId: '@alice:example.org',
|
||||
deviceId: 'DEVICE',
|
||||
accessToken: 'alice-token',
|
||||
},
|
||||
];
|
||||
|
||||
const { useSessionProfiles } = await import('./useSessionProfiles');
|
||||
const { result, unmount } = renderHook(() => useSessionProfiles(sessions));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current['@alice:example.org']).toEqual({
|
||||
displayName: 'Alice',
|
||||
avatarHttpUrl: 'blob:session-avatar',
|
||||
});
|
||||
});
|
||||
|
||||
unmount();
|
||||
|
||||
expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:session-avatar');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,7 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import type { Session } from '$state/sessions';
|
||||
import { fetch } from '$utils/fetch';
|
||||
import { fetchMediaBlob } from '$utils/mediaTransport';
|
||||
|
||||
export type SessionProfile = {
|
||||
displayName?: string;
|
||||
@@ -18,8 +20,7 @@ const parseMxc = (mxcUrl: string): { serverName: string; mediaId: string } | und
|
||||
};
|
||||
|
||||
const fetchAvatarBlobUrl = async (
|
||||
baseUrl: string,
|
||||
accessToken: string,
|
||||
session: Session,
|
||||
mxcUrl: string
|
||||
): Promise<string | undefined> => {
|
||||
const parsed = parseMxc(mxcUrl);
|
||||
@@ -27,22 +28,21 @@ const fetchAvatarBlobUrl = async (
|
||||
const { serverName, mediaId } = parsed;
|
||||
|
||||
const tryFetch = async (url: string) => {
|
||||
const res = await fetch(url, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
const blob = await fetchMediaBlob(url, {
|
||||
accessToken: session.accessToken,
|
||||
sessionScope: session.userId,
|
||||
});
|
||||
if (!res.ok) throw new Error(`${res.status}`);
|
||||
const blob = await res.blob();
|
||||
return URL.createObjectURL(blob);
|
||||
};
|
||||
|
||||
try {
|
||||
return await tryFetch(
|
||||
`${baseUrl}/_matrix/client/v1/media/thumbnail/${serverName}/${mediaId}?width=96&height=96&method=crop`
|
||||
`${session.baseUrl}/_matrix/client/v1/media/thumbnail/${encodeURIComponent(serverName)}/${encodeURIComponent(mediaId)}?width=96&height=96&method=crop`
|
||||
);
|
||||
} catch {
|
||||
try {
|
||||
return await tryFetch(
|
||||
`${baseUrl}/_matrix/media/v3/thumbnail/${serverName}/${mediaId}?width=96&height=96&method=crop`
|
||||
`${session.baseUrl}/_matrix/media/v3/thumbnail/${encodeURIComponent(serverName)}/${encodeURIComponent(mediaId)}?width=96&height=96&method=crop`
|
||||
);
|
||||
} catch {
|
||||
return undefined;
|
||||
@@ -52,12 +52,15 @@ const fetchAvatarBlobUrl = async (
|
||||
|
||||
export const useSessionProfiles = (sessions: Session[]): SessionProfiles => {
|
||||
const [profiles, setProfiles] = useState<SessionProfiles>({});
|
||||
const blobUrlsRef = useRef<string[]>([]);
|
||||
|
||||
const sessionsRef = useRef(sessions);
|
||||
sessionsRef.current = sessions;
|
||||
|
||||
const sessionKey = sessions.map((s) => s.userId).join('\x00');
|
||||
const sessionIdentityKey = sessions
|
||||
.map((session) =>
|
||||
[session.userId, session.baseUrl, session.accessToken, session.deviceId].join('\x01')
|
||||
)
|
||||
.join('\x00');
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
@@ -75,11 +78,7 @@ export const useSessionProfiles = (sessions: Session[]): SessionProfiles => {
|
||||
|
||||
let avatarHttpUrl: string | undefined;
|
||||
if (data.avatar_url) {
|
||||
avatarHttpUrl = await fetchAvatarBlobUrl(
|
||||
session.baseUrl,
|
||||
session.accessToken,
|
||||
data.avatar_url
|
||||
);
|
||||
avatarHttpUrl = await fetchAvatarBlobUrl(session, data.avatar_url);
|
||||
if (avatarHttpUrl) newBlobUrls.push(avatarHttpUrl);
|
||||
}
|
||||
|
||||
@@ -102,10 +101,9 @@ export const useSessionProfiles = (sessions: Session[]): SessionProfiles => {
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
blobUrlsRef.current.forEach((u) => URL.revokeObjectURL(u));
|
||||
blobUrlsRef.current = newBlobUrls;
|
||||
newBlobUrls.forEach((url) => URL.revokeObjectURL(url));
|
||||
};
|
||||
}, [sessionKey]);
|
||||
}, [sessionIdentityKey]);
|
||||
|
||||
return profiles;
|
||||
};
|
||||
Loaded 100 of 356 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user