2022-02-17 21:24:05 +01:00
|
|
|
/*
|
2024-09-09 14:57:16 +01:00
|
|
|
Copyright 2024 New Vector Ltd.
|
2022-02-17 21:24:05 +01:00
|
|
|
Copyright 2022 The Matrix.org Foundation C.I.C.
|
|
|
|
|
|
2025-01-06 11:18:54 +00:00
|
|
|
SPDX-License-Identifier: AGPL-3.0-only OR GPL-3.0-only OR LicenseRef-Element-Commercial
|
2024-09-09 14:57:16 +01:00
|
|
|
Please see LICENSE files in the repository root for full details.
|
2022-02-17 21:24:05 +01:00
|
|
|
*/
|
|
|
|
|
|
2025-02-05 13:25:06 +00:00
|
|
|
import { type SpaceKey } from ".";
|
2022-02-17 21:24:05 +01:00
|
|
|
|
|
|
|
|
export type SpaceEntityMap = Map<SpaceKey, Set<string>>;
|
|
|
|
|
export type SpaceDescendantMap = Map<SpaceKey, Set<SpaceKey>>;
|
|
|
|
|
|
|
|
|
|
const traverseSpaceDescendants = (
|
|
|
|
|
spaceDescendantMap: SpaceDescendantMap,
|
|
|
|
|
spaceId: SpaceKey,
|
|
|
|
|
flatSpace = new Set<SpaceKey>(),
|
|
|
|
|
): Set<SpaceKey> => {
|
|
|
|
|
flatSpace.add(spaceId);
|
|
|
|
|
const descendentSpaces = spaceDescendantMap.get(spaceId);
|
|
|
|
|
descendentSpaces?.forEach((descendantSpaceId) => {
|
|
|
|
|
if (!flatSpace.has(descendantSpaceId)) {
|
|
|
|
|
traverseSpaceDescendants(spaceDescendantMap, descendantSpaceId, flatSpace);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return flatSpace;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
2022-05-09 16:52:05 -06:00
|
|
|
* Helper function to traverse space hierarchy and flatten
|
2022-02-17 21:24:05 +01:00
|
|
|
* @param spaceEntityMap ie map of rooms or dm userIds
|
|
|
|
|
* @param spaceDescendantMap map of spaces and their children
|
|
|
|
|
* @returns set of all rooms
|
|
|
|
|
*/
|
|
|
|
|
export const flattenSpaceHierarchy = (
|
|
|
|
|
spaceEntityMap: SpaceEntityMap,
|
|
|
|
|
spaceDescendantMap: SpaceDescendantMap,
|
|
|
|
|
spaceId: SpaceKey,
|
|
|
|
|
): Set<string> => {
|
|
|
|
|
const flattenedSpaceIds = traverseSpaceDescendants(spaceDescendantMap, spaceId);
|
|
|
|
|
const flattenedRooms = new Set<string>();
|
|
|
|
|
|
|
|
|
|
flattenedSpaceIds.forEach((id) => {
|
|
|
|
|
const roomIds = spaceEntityMap.get(id);
|
|
|
|
|
roomIds?.forEach(flattenedRooms.add, flattenedRooms);
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
return flattenedRooms;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const flattenSpaceHierarchyWithCache =
|
|
|
|
|
(cache: SpaceEntityMap) =>
|
|
|
|
|
(
|
|
|
|
|
spaceEntityMap: SpaceEntityMap,
|
|
|
|
|
spaceDescendantMap: SpaceDescendantMap,
|
|
|
|
|
spaceId: SpaceKey,
|
|
|
|
|
useCache = true,
|
|
|
|
|
): Set<string> => {
|
|
|
|
|
if (useCache && cache.has(spaceId)) {
|
2023-02-03 15:27:47 +00:00
|
|
|
return cache.get(spaceId)!;
|
2022-02-17 21:24:05 +01:00
|
|
|
}
|
|
|
|
|
const result = flattenSpaceHierarchy(spaceEntityMap, spaceDescendantMap, spaceId);
|
|
|
|
|
cache.set(spaceId, result);
|
|
|
|
|
|
|
|
|
|
return result;
|
2022-12-12 12:24:14 +01:00
|
|
|
};
|