Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
35 commits
Select commit Hold shift + click to select a range
99e7848
chore(spaces): setup a simple space service and some unit tests
stefanceriu Aug 1, 2025
b4606fe
chore(spaces): introduce a `SpaceServiceRoom`
stefanceriu Aug 4, 2025
3cb5874
feat(spaces): introduce a `SpaceRoomList` that allows pagination and …
stefanceriu Aug 6, 2025
c667833
feat(spaces): add a reactive version of the `joined_spaces` method
stefanceriu Aug 7, 2025
2459061
change(spaces): return only top level joined rooms from `SpaceService…
stefanceriu Aug 7, 2025
3de2d8d
feat(spaces): have the `SpaceRoomList` publish updates as known room …
stefanceriu Aug 8, 2025
bafcd7d
fix(spaces): fix complement-crypto failures because of using an outda…
stefanceriu Aug 8, 2025
4cd3e1e
fix(spaces): use wasm compatible executor `spawn` and `JoinHandle`
stefanceriu Aug 8, 2025
dd728d9
change(room_list): request both `m.space.parent` and `m.space.child` …
stefanceriu Aug 11, 2025
8fddcee
chore(spaces): build a graph from joined spaces parent and child rela…
stefanceriu Aug 11, 2025
13aad5c
feat(ffi): expose `SpaceService::subscribe_to_joined_spaces` and `Spa…
stefanceriu Aug 11, 2025
d6d1799
fix(spaces): return the TaskHandle from the FFI space service subscri…
stefanceriu Aug 11, 2025
9246f0b
feat(spaces): expose the number of children each space room has
stefanceriu Aug 11, 2025
c71065c
change(spaces): put a limit of 1 on the max depth of the /hierarchy c…
stefanceriu Aug 11, 2025
87558cd
fix(spaces): filter out the current parent space from the `/hierarchy…
stefanceriu Aug 11, 2025
136e068
change(spaces): make the `SpaceService` constructor non-async and ins…
stefanceriu Aug 11, 2025
0993802
chore(spaces): converge on single naming scheme for all spaces relate…
stefanceriu Aug 12, 2025
fb106b7
chore(spaces): add changelog
stefanceriu Aug 13, 2025
6ecc270
change(spaces): publish VectorDiffs instead of a full vectors for joi…
stefanceriu Aug 14, 2025
9e2e46c
chore(spaces): ignore room list change updates if empty
stefanceriu Aug 18, 2025
c00b826
docs(spaces): add documentation, comments and examples
stefanceriu Aug 19, 2025
b0d7831
chore(spaces): switch from manually dropping `JoinHandle`s to `AbortO…
stefanceriu Aug 20, 2025
b6b4611
fix(spaces): compute the initial `joined_spaces` value when first set…
stefanceriu Aug 20, 2025
a6be4ae
chore(spaces): use `Client::joined_space_rooms` within the space serv…
stefanceriu Aug 21, 2025
4682668
chore(spaces): various documentation fixes
stefanceriu Aug 29, 2025
90f323d
chore(spaces): simplify the `SpaceGraph` interfaces
stefanceriu Aug 29, 2025
22e23a2
chore(spaces): switch some `flat_map`s to `filter_map`
stefanceriu Aug 29, 2025
af195ea
chore(spaces): fix typo
stefanceriu Aug 29, 2025
aa27a64
chore(spaces): improve how space graph edge additions work
stefanceriu Aug 29, 2025
7a11db4
chore(spaces): simplify the `SpaceGraph` interfaces
stefanceriu Aug 29, 2025
3c45e4b
chore(spaces): cleanup clone names in room updates listener
stefanceriu Aug 29, 2025
6515ace
fix(spaces): mitigate eventual race conditions when updating the pagi…
stefanceriu Aug 29, 2025
243e51a
chore(spaces): acquire and retain an async lock on the pagination tok…
stefanceriu Aug 29, 2025
74fd754
fix(spaces): address potential race when setting up the room updates …
stefanceriu Aug 29, 2025
89f2483
fix(spaces): mitigate eventual race conditions when updating the pagi…
stefanceriu Aug 29, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions bindings/matrix-sdk-ffi/src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ use matrix_sdk_ui::{
NotificationClient as MatrixNotificationClient,
NotificationProcessSetup as MatrixNotificationProcessSetup,
},
spaces::SpaceService as UISpaceService,
unable_to_decrypt_hook::UtdHookManager,
};
use mime::Mime;
Expand Down Expand Up @@ -111,6 +112,7 @@ use crate::{
MediaPreviews, MediaSource, RoomAccountDataEvent, RoomAccountDataEventType,
},
runtime::get_runtime_handle,
spaces::SpaceService,
sync_service::{SyncService, SyncServiceBuilder},
task_handle::TaskHandle,
utd::{UnableToDecryptDelegate, UtdHook},
Expand Down Expand Up @@ -1257,6 +1259,11 @@ impl Client {
SyncServiceBuilder::new((*self.inner).clone(), self.utd_hook_manager.get().cloned())
}

pub fn space_service(&self) -> Arc<SpaceService> {
let inner = UISpaceService::new((*self.inner).clone());
Arc::new(SpaceService::new(inner))
}

pub async fn get_notification_settings(&self) -> Arc<NotificationSettings> {
let inner = self.inner.notification_settings().await;

Expand Down
1 change: 1 addition & 0 deletions bindings/matrix-sdk-ffi/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ mod room_preview;
mod ruma;
mod runtime;
mod session_verification;
mod spaces;
mod sync_service;
mod task_handle;
mod timeline;
Expand Down
12 changes: 6 additions & 6 deletions bindings/matrix-sdk-ffi/src/room_preview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,10 @@ impl RoomPreview {
avatar_url: info.avatar_url.as_ref().map(|url| url.to_string()),
num_joined_members: info.num_joined_members,
num_active_members: info.num_active_members,
room_type: info.room_type.as_ref().into(),
room_type: info.room_type.clone().into(),
is_history_world_readable: info.is_world_readable,
membership: info.state.map(|state| state.into()),
join_rule: info.join_rule.as_ref().map(Into::into),
join_rule: info.join_rule.clone().map(Into::into),
is_direct: info.is_direct,
heroes: info
.heroes
Expand Down Expand Up @@ -116,8 +116,8 @@ pub struct RoomPreviewInfo {
pub heroes: Option<Vec<RoomHero>>,
}

impl From<&JoinRuleSummary> for JoinRule {
fn from(join_rule: &JoinRuleSummary) -> Self {
impl From<JoinRuleSummary> for JoinRule {
fn from(join_rule: JoinRuleSummary) -> Self {
match join_rule {
JoinRuleSummary::Invite => JoinRule::Invite,
JoinRuleSummary::Knock => JoinRule::Knock,
Expand Down Expand Up @@ -153,8 +153,8 @@ pub enum RoomType {
Custom { value: String },
}

impl From<Option<&RumaRoomType>> for RoomType {
fn from(value: Option<&RumaRoomType>) -> Self {
impl From<Option<RumaRoomType>> for RoomType {
fn from(value: Option<RumaRoomType>) -> Self {
match value {
Some(RumaRoomType::Space) => RoomType::Space,
Some(RumaRoomType::_Custom(_)) => RoomType::Custom {
Expand Down
276 changes: 276 additions & 0 deletions bindings/matrix-sdk-ffi/src/spaces.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,276 @@
// Copyright 2025 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{fmt::Debug, sync::Arc};

use eyeball_im::VectorDiff;
use futures_util::{pin_mut, StreamExt};
use matrix_sdk_common::{SendOutsideWasm, SyncOutsideWasm};
use matrix_sdk_ui::spaces::{
room_list::SpaceRoomListPaginationState, SpaceRoom as UISpaceRoom,
SpaceRoomList as UISpaceRoomList, SpaceService as UISpaceService,
};
use ruma::RoomId;

use crate::{
client::JoinRule,
error::ClientError,
room::{Membership, RoomHero},
room_preview::RoomType,
runtime::get_runtime_handle,
TaskHandle,
};

/// The main entry point into the Spaces facilities.
///
/// The spaces service is responsible for retrieving one's joined rooms,
/// building a graph out of their `m.space.parent` and `m.space.child` state
/// events, and providing access to the top-level spaces and their children.
#[derive(uniffi::Object)]
pub struct SpaceService {
inner: UISpaceService,
}

impl SpaceService {
/// Creates a new `SpaceService` instance.
pub(crate) fn new(inner: UISpaceService) -> Self {
Self { inner }
}
}

#[matrix_sdk_ffi_macros::export]
impl SpaceService {
/// Returns a list of all the top-level joined spaces. It will eagerly
/// compute the latest version and also notify subscribers if there were
/// any changes.
pub async fn joined_spaces(&self) -> Vec<SpaceRoom> {
self.inner.joined_spaces().await.into_iter().map(Into::into).collect()
}

/// Subscribes to updates on the joined spaces list. If space rooms are
/// joined or left, the stream will yield diffs that reflect the changes.
pub async fn subscribe_to_joined_spaces(
&self,
listener: Box<dyn SpaceServiceJoinedSpacesListener>,
) -> Arc<TaskHandle> {
let (initial_values, mut stream) = self.inner.subscribe_to_joined_spaces().await;

listener.on_update(vec![SpaceListUpdate::Reset {
values: initial_values.into_iter().map(Into::into).collect(),
}]);

Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
while let Some(diffs) = stream.next().await {
listener.on_update(diffs.into_iter().map(Into::into).collect());
}
})))
}

/// Returns a `SpaceRoomList` for the given space ID.
#[allow(clippy::unused_async)]
// This method doesn't need to be async but if its not the FFI layer panics
// with "there is no no reactor running, must be called from the context
// of a Tokio 1.x runtime" error because the underlying constructor spawns
// an async task.
pub async fn space_room_list(
&self,
space_id: String,
) -> Result<Arc<SpaceRoomList>, ClientError> {
let space_id = RoomId::parse(space_id)?;
Ok(Arc::new(SpaceRoomList::new(self.inner.space_room_list(space_id))))
}
}

/// The `SpaceRoomList`represents a paginated list of direct rooms
/// that belong to a particular space.
///
/// It can be used to paginate through the list (and have live updates on the
/// pagination state) as well as subscribe to changes as rooms are joined or
/// left.
///
/// The `SpaceRoomList` also automatically subscribes to client room changes
/// and updates the list accordingly as rooms are joined or left.
#[derive(uniffi::Object)]
pub struct SpaceRoomList {
inner: UISpaceRoomList,
}

impl SpaceRoomList {
/// Creates a new `SpaceRoomList` for the underlying UI crate room list.
fn new(inner: UISpaceRoomList) -> Self {
Self { inner }
}
}

#[matrix_sdk_ffi_macros::export]
impl SpaceRoomList {
/// Returns if the room list is currently paginating or not.
pub fn pagination_state(&self) -> SpaceRoomListPaginationState {
self.inner.pagination_state()
}

/// Subscribe to pagination updates.
pub fn subscribe_to_pagination_state_updates(
&self,
listener: Box<dyn SpaceRoomListPaginationStateListener>,
) -> Arc<TaskHandle> {
let pagination_state = self.inner.subscribe_to_pagination_state_updates();

Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
pin_mut!(pagination_state);

while let Some(state) = pagination_state.next().await {
listener.on_update(state);
}
})))
}

/// Return the current list of rooms.
pub fn rooms(&self) -> Vec<SpaceRoom> {
self.inner.rooms().into_iter().map(Into::into).collect()
}

/// Subscribes to room list updates.
pub fn subscribe_to_room_update(
&self,
listener: Box<dyn SpaceRoomListEntriesListener>,
) -> Arc<TaskHandle> {
let (initial_values, mut stream) = self.inner.subscribe_to_room_updates();

listener.on_update(vec![SpaceListUpdate::Reset {
values: initial_values.into_iter().map(Into::into).collect(),
}]);

Arc::new(TaskHandle::new(get_runtime_handle().spawn(async move {
while let Some(diffs) = stream.next().await {
listener.on_update(diffs.into_iter().map(Into::into).collect());
}
})))
}

/// Ask the list to retrieve the next page if the end hasn't been reached
/// yet. Otherwise it no-ops.
pub async fn paginate(&self) -> Result<(), ClientError> {
self.inner.paginate().await.map_err(ClientError::from)
}
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceRoomListPaginationStateListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, pagination_state: SpaceRoomListPaginationState);
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceRoomListEntriesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, rooms: Vec<SpaceListUpdate>);
}

#[matrix_sdk_ffi_macros::export(callback_interface)]
pub trait SpaceServiceJoinedSpacesListener: SendOutsideWasm + SyncOutsideWasm + Debug {
fn on_update(&self, room_updates: Vec<SpaceListUpdate>);
}

/// Structure representing a room in a space and aggregated information
/// relevant to the UI layer.
#[derive(uniffi::Record)]
pub struct SpaceRoom {
/// The ID of the room.
pub room_id: String,
/// The canonical alias of the room, if any.
pub canonical_alias: Option<String>,
/// The name of the room, if any.
pub name: Option<String>,
/// The topic of the room, if any.
pub topic: Option<String>,
/// The URL for the room's avatar, if one is set.
pub avatar_url: Option<String>,
/// The type of room from `m.room.create`, if any.
pub room_type: RoomType,
/// The number of members joined to the room.
pub num_joined_members: u64,
/// The join rule of the room.
pub join_rule: Option<JoinRule>,
/// Whether the room may be viewed by users without joining.
pub world_readable: Option<bool>,
/// Whether guest users may join the room and participate in it.
pub guest_can_join: bool,

/// The number of children room this has, if a space.
pub children_count: u64,
/// Whether this room is joined, left etc.
pub state: Option<Membership>,
/// A list of room members considered to be heroes.
pub heroes: Option<Vec<RoomHero>>,
}

impl From<UISpaceRoom> for SpaceRoom {
fn from(room: UISpaceRoom) -> Self {
Self {
room_id: room.room_id.into(),
canonical_alias: room.canonical_alias.map(|alias| alias.into()),
name: room.name,
topic: room.topic,
avatar_url: room.avatar_url.map(|url| url.into()),
room_type: room.room_type.into(),
num_joined_members: room.num_joined_members,
join_rule: room.join_rule.map(Into::into),
world_readable: room.world_readable,
guest_can_join: room.guest_can_join,
children_count: room.children_count,
state: room.state.map(Into::into),
heroes: room.heroes.map(|heroes| heroes.into_iter().map(Into::into).collect()),
}
}
}

#[derive(uniffi::Enum)]
pub enum SpaceListUpdate {
Append { values: Vec<SpaceRoom> },
Clear,
PushFront { value: SpaceRoom },
PushBack { value: SpaceRoom },
PopFront,
PopBack,
Insert { index: u32, value: SpaceRoom },
Set { index: u32, value: SpaceRoom },
Remove { index: u32 },
Truncate { length: u32 },
Reset { values: Vec<SpaceRoom> },
}

impl From<VectorDiff<UISpaceRoom>> for SpaceListUpdate {
fn from(diff: VectorDiff<UISpaceRoom>) -> Self {
match diff {
VectorDiff::Append { values } => {
Self::Append { values: values.into_iter().map(|v| v.into()).collect() }
}
VectorDiff::Clear => Self::Clear,
VectorDiff::PushFront { value } => Self::PushFront { value: value.into() },
VectorDiff::PushBack { value } => Self::PushBack { value: value.into() },
VectorDiff::PopFront => Self::PopFront,
VectorDiff::PopBack => Self::PopBack,
VectorDiff::Insert { index, value } => {
Self::Insert { index: index as u32, value: value.into() }
}
VectorDiff::Set { index, value } => {
Self::Set { index: index as u32, value: value.into() }
}
VectorDiff::Remove { index } => Self::Remove { index: index as u32 },
VectorDiff::Truncate { length } => Self::Truncate { length: length as u32 },
VectorDiff::Reset { values } => {
Self::Reset { values: values.into_iter().map(|v| v.into()).collect() }
}
}
}
}
2 changes: 1 addition & 1 deletion crates/matrix-sdk-base/src/sync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ impl RoomUpdates {
/// Iterate over all room IDs, from [`RoomUpdates::left`],
/// [`RoomUpdates::joined`], [`RoomUpdates::invited`] and
/// [`RoomUpdates::knocked`].
pub(crate) fn iter_all_room_ids(&self) -> impl Iterator<Item = &OwnedRoomId> {
pub fn iter_all_room_ids(&self) -> impl Iterator<Item = &OwnedRoomId> {
self.left
.keys()
.chain(self.joined.keys())
Expand Down
3 changes: 3 additions & 0 deletions crates/matrix-sdk-ui/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ All notable changes to this project will be documented in this file.
## [Unreleased] - ReleaseDate

### Features
- Add a new [`SpaceService`] that provides high level reactive interfaces for listing
the user's joined top level spaces as long as their children.
([#5509](https://github.com/matrix-org/matrix-rust-sdk/pull/5509))
- Add `new_filter_low_priority` and `new_filter_non_low_priority` filters to the room list filtering system,
allowing clients to filter rooms based on their low priority status. The filters use the `Room::is_low_priority()`
method which checks for the `m.lowpriority` room tag.
Expand Down
1 change: 1 addition & 0 deletions crates/matrix-sdk-ui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ use ruma::html::HtmlSanitizerMode;
pub mod encryption_sync_service;
pub mod notification_client;
pub mod room_list_service;
pub mod spaces;
pub mod sync_service;
pub mod timeline;
pub mod unable_to_decrypt_hook;
Expand Down
2 changes: 2 additions & 0 deletions crates/matrix-sdk-ui/src/room_list_service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ const DEFAULT_REQUIRED_STATE: &[(StateEventType, &str)] = &[
(StateEventType::RoomHistoryVisibility, ""),
// Required to correctly calculate the room display name.
(StateEventType::MemberHints, ""),
(StateEventType::SpaceParent, "*"),
(StateEventType::SpaceChild, "*"),
];

/// The default `required_state` constant value for sliding sync room
Expand Down
Loading
Loading