add leave rooms and subspaces button to leave space confirmation

This commit is contained in:
7w1 committed 2026-06-16 19:30:08 -05:00
1 parent de08fc744f
commit 85d69185eb
4 files changed
+311 -26

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
default: patch
---
Added a button to leave all rooms/subspaces within a space in the leave space confirmation dialog. Also has text to show number of children.
@@ -1,4 +1,4 @@
import { useCallback, useEffect } from 'react';
import { useCallback, useEffect, useMemo } from 'react';
import FocusTrap from 'focus-trap-react';
import {
Dialog,
@@ -19,30 +19,76 @@ import { useMatrixClient } from '$hooks/useMatrixClient';
import { AsyncStatus, useAsyncCallback } from '$hooks/useAsyncCallback';
import { composerIcon, X } from '$components/icons/phosphor';
import { stopPropagation } from '$utils/keyboard';
import { getJoinedSpaceChildrenSummary, getRecursiveSpaceLeaveOrder } from '$utils/room';
import { rateLimitedActions } from '$utils/matrix';
type LeaveSpacePromptProps = {
roomId: string;
onDone: () => void;
onCancel: () => void;
};
const formatJoinedContentsMessage = (roomCount: number, subspaceCount: number): string => {
const parts: string[] = [];
if (roomCount > 0) {
parts.push(`${roomCount} ${roomCount === 1 ? 'room' : 'rooms'}`);
}
if (subspaceCount > 0) {
parts.push(`${subspaceCount} ${subspaceCount === 1 ? 'subspace' : 'subspaces'}`);
}
return `You are also joined to ${parts.join(' and ')} in this space. Leaving the space alone will not remove you from them.`;
};
const formatRecursiveLeaveLabel = (
leaving: boolean,
roomCount: number,
subspaceCount: number
): string => {
if (leaving) {
return 'Leaving space, rooms, and subspaces...';
}
const parts: string[] = [];
if (roomCount > 0) {
parts.push('Rooms');
}
if (subspaceCount > 0) {
parts.push('Subspaces');
}
return `Leave Space and All ${parts.join(' & ')}`;
};
export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptProps) {
const mx = useMatrixClient();
const [leaveState, leaveRoom] = useAsyncCallback<undefined, MatrixError, []>(
const { leaveOrder, roomCount, subspaceCount } = useMemo(
() => getJoinedSpaceChildrenSummary(mx, roomId),
[mx, roomId]
);
const joinedChildrenCount = leaveOrder.length;
const [leaveState, leaveSpace] = useAsyncCallback<undefined, MatrixError, []>(
useCallback(async () => {
mx.leave(roomId);
await mx.leave(roomId);
}, [mx, roomId])
);
const handleLeave = () => {
leaveRoom();
};
const [leaveAllState, leaveAll] = useAsyncCallback<undefined, MatrixError, []>(
useCallback(async () => {
await rateLimitedActions(getRecursiveSpaceLeaveOrder(mx, roomId), (id) => mx.leave(id));
}, [mx, roomId])
);
const leaving = leaveState.status === AsyncStatus.Loading;
const leavingAll = leaveAllState.status === AsyncStatus.Loading;
const isBusy = leaving || leavingAll;
useEffect(() => {
if (leaveState.status === AsyncStatus.Success) {
if (leaveState.status === AsyncStatus.Success || leaveAllState.status === AsyncStatus.Success) {
onDone();
}
}, [leaveState, onDone]);
}, [leaveState, leaveAllState, onDone]);
return (
<Overlay open backdrop={<OverlayBackdrop />}>
@@ -74,30 +120,52 @@ export function LeaveSpacePrompt({ roomId, onDone, onCancel }: LeaveSpacePromptP
<Box style={{ padding: config.space.S400 }} direction="Column" gap="400">
<Box direction="Column" gap="200">
<Text priority="400">Are you sure you want to leave this space?</Text>
{joinedChildrenCount > 0 && (
<Text priority="300" size="T300">
{formatJoinedContentsMessage(roomCount, subspaceCount)}
</Text>
)}
{leaveState.status === AsyncStatus.Error && (
<Text style={{ color: color.Critical.Main }} size="T300">
Failed to leave space! {leaveState.error.message}
</Text>
)}
{leaveAllState.status === AsyncStatus.Error && (
<Text style={{ color: color.Critical.Main }} size="T300">
Failed to leave space, rooms, and subspaces! {leaveAllState.error.message}
</Text>
)}
</Box>
<Box direction="Column" gap="200">
<Button
type="submit"
variant="Critical"
onClick={() => leaveSpace()}
before={
leaving ? <Spinner fill="Solid" variant="Critical" size="200" /> : undefined
}
aria-disabled={isBusy || leaveState.status === AsyncStatus.Success}
>
<Text size="B400">{leaving ? 'Leaving...' : 'Leave Space Only'}</Text>
</Button>
{joinedChildrenCount > 0 && (
<Button
variant="Critical"
fill="Soft"
onClick={() => leaveAll()}
before={
leavingAll ? (
<Spinner fill="Solid" variant="Critical" size="200" />
) : undefined
}
aria-disabled={isBusy || leaveAllState.status === AsyncStatus.Success}
>
<Text size="B400">
{formatRecursiveLeaveLabel(leavingAll, roomCount, subspaceCount)}
</Text>
</Button>
)}
</Box>
<Button
type="submit"
variant="Critical"
onClick={handleLeave}
before={
leaveState.status === AsyncStatus.Loading ? (
<Spinner fill="Solid" variant="Critical" size="200" />
) : undefined
}
aria-disabled={
leaveState.status === AsyncStatus.Loading ||
leaveState.status === AsyncStatus.Success
}
>
<Text size="B400">
{leaveState.status === AsyncStatus.Loading ? 'Leaving...' : 'Leave'}
</Text>
</Button>
</Box>
</Dialog>
</FocusTrap>
+138
View File
@@ -0,0 +1,138 @@
import { describe, expect, it } from 'vitest';
import { EventType, KnownMembership, RoomType } from '$types/matrix-sdk';
import type { MatrixClient, MatrixEvent, Room } from '$types/matrix-sdk';
import { getJoinedSpaceChildrenLeaveOrder, getJoinedSpaceChildrenSummary } from './room';
/* oxlint-disable typescript/no-explicit-any */
const SPACE = '!space:example.com';
const SUBSPACE = '!subspace:example.com';
const ROOM_1 = '!room1:example.com';
const ROOM_2 = '!room2:example.com';
const TOMBSTONED = '!old:example.com';
const createSpaceChildEvent = (childId: string) =>
({
getType: () => EventType.SpaceChild,
getStateKey: () => childId,
getContent: () => ({ via: [] }),
}) as unknown as MatrixEvent;
const createRoom = (
roomId: string,
options: {
isSpace?: boolean;
membership?: string;
tombstoned?: boolean;
children?: string[];
} = {}
): Room => {
const {
isSpace = false,
membership = KnownMembership.Join,
tombstoned = false,
children = [],
} = options;
const stateEvents: MatrixEvent[] = [
{
getType: () => EventType.RoomCreate,
getStateKey: () => '',
getContent: () => ({ type: isSpace ? RoomType.Space : undefined }),
} as unknown as MatrixEvent,
...children.map(createSpaceChildEvent),
];
if (tombstoned) {
stateEvents.push({
getType: () => EventType.RoomTombstone,
getStateKey: () => '',
getContent: () => ({ body: 'Upgraded', replacement_room: '!new:example.com' }),
} as unknown as MatrixEvent);
}
return {
roomId,
getMyMembership: () => membership,
isSpaceRoom: () => isSpace,
getLiveTimeline: () => ({
getState: () => ({
getStateEvents: (eventType: string, stateKey?: string) => {
const events = stateEvents.filter((event) => event.getType() === eventType);
if (stateKey !== undefined) {
return events.find((event) => event.getStateKey?.() === stateKey);
}
return events;
},
}),
}),
} as unknown as Room;
};
const createClient = (rooms: Record<string, Room>): MatrixClient =>
({
getRoom: (roomId: string) => rooms[roomId],
}) as unknown as MatrixClient;
describe('getJoinedSpaceChildrenLeaveOrder', () => {
it('returns only direct rooms for a flat space', () => {
const mx = createClient({
[SPACE]: createRoom(SPACE, { isSpace: true, children: [ROOM_1, ROOM_2] }),
[ROOM_1]: createRoom(ROOM_1),
[ROOM_2]: createRoom(ROOM_2),
});
expect(getJoinedSpaceChildrenLeaveOrder(mx, SPACE)).toEqual([ROOM_1, ROOM_2]);
});
it('does not include the root space itself', () => {
const mx = createClient({
[SPACE]: createRoom(SPACE, { isSpace: true, children: [SPACE, ROOM_1] }),
[ROOM_1]: createRoom(ROOM_1),
});
expect(getJoinedSpaceChildrenLeaveOrder(mx, SPACE)).toEqual([ROOM_1]);
});
it('includes nested rooms and subspaces without counting the root space', () => {
const mx = createClient({
[SPACE]: createRoom(SPACE, { isSpace: true, children: [SUBSPACE] }),
[SUBSPACE]: createRoom(SUBSPACE, { isSpace: true, children: [ROOM_1, ROOM_2] }),
[ROOM_1]: createRoom(ROOM_1),
[ROOM_2]: createRoom(ROOM_2),
});
expect(getJoinedSpaceChildrenLeaveOrder(mx, SPACE)).toEqual([ROOM_1, ROOM_2, SUBSPACE]);
});
it('skips tombstoned rooms', () => {
const mx = createClient({
[SPACE]: createRoom(SPACE, {
isSpace: true,
children: [ROOM_1, ROOM_2, TOMBSTONED],
}),
[ROOM_1]: createRoom(ROOM_1),
[ROOM_2]: createRoom(ROOM_2),
[TOMBSTONED]: createRoom(TOMBSTONED, { tombstoned: true }),
});
expect(getJoinedSpaceChildrenLeaveOrder(mx, SPACE)).toEqual([ROOM_1, ROOM_2]);
});
});
describe('getJoinedSpaceChildrenSummary', () => {
it('separates room and subspace counts', () => {
const mx = createClient({
[SPACE]: createRoom(SPACE, { isSpace: true, children: [SUBSPACE] }),
[SUBSPACE]: createRoom(SUBSPACE, { isSpace: true, children: [ROOM_1, ROOM_2] }),
[ROOM_1]: createRoom(ROOM_1),
[ROOM_2]: createRoom(ROOM_2),
});
expect(getJoinedSpaceChildrenSummary(mx, SPACE)).toEqual({
leaveOrder: [ROOM_1, ROOM_2, SUBSPACE],
roomCount: 2,
subspaceCount: 1,
});
});
});
+74
View File
@@ -145,6 +145,80 @@ export const getSpaceChildren = (room: Room) =>
return filtered;
}, []);
export const getJoinedSpaceChildrenLeaveOrder = (
mx: MatrixClient,
rootSpaceId: string
): string[] => {
const leaveOrder: string[] = [];
const visited = new Set<string>();
const isJoinedChild = (room: Room): boolean =>
room.getMyMembership() === (KnownMembership.Join as string) &&
!getStateEvent(room, EventType.RoomTombstone);
const visitSpace = (spaceId: string) => {
if (visited.has(spaceId)) return;
visited.add(spaceId);
const space = mx.getRoom(spaceId);
if (!space || !isJoinedChild(space)) return;
getSpaceChildren(space).forEach((childId) => {
if (visited.has(childId)) return;
const child = mx.getRoom(childId);
if (!child || !isJoinedChild(child)) return;
if (child.isSpaceRoom()) {
visitSpace(childId);
return;
}
visited.add(childId);
leaveOrder.push(childId);
});
if (spaceId !== rootSpaceId) {
leaveOrder.push(spaceId);
}
};
visitSpace(rootSpaceId);
return leaveOrder.filter((id) => id !== rootSpaceId);
};
export type JoinedSpaceChildrenSummary = {
leaveOrder: string[];
roomCount: number;
subspaceCount: number;
};
export const getJoinedSpaceChildrenSummary = (
mx: MatrixClient,
rootSpaceId: string
): JoinedSpaceChildrenSummary => {
const leaveOrder = getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId);
let roomCount = 0;
let subspaceCount = 0;
leaveOrder.forEach((id) => {
const room = mx.getRoom(id);
if (room?.isSpaceRoom()) {
subspaceCount += 1;
} else {
roomCount += 1;
}
});
return { leaveOrder, roomCount, subspaceCount };
};
export const getRecursiveSpaceLeaveOrder = (mx: MatrixClient, rootSpaceId: string): string[] => [
...getJoinedSpaceChildrenLeaveOrder(mx, rootSpaceId),
rootSpaceId,
];
export const mapParentWithChildren = (
roomToParents: RoomToParents,
roomId: string,