Add rooms hierarchy class
authorajbura <ajbura@gmail.com>
Thu, 10 Feb 2022 15:26:23 +0000 (20:56 +0530)
committerajbura <ajbura@gmail.com>
Thu, 10 Feb 2022 15:26:23 +0000 (20:56 +0530)
Signed-off-by: ajbura <ajbura@gmail.com>
src/client/state/RoomsHierarchy.js [new file with mode: 0644]

diff --git a/src/client/state/RoomsHierarchy.js b/src/client/state/RoomsHierarchy.js
new file mode 100644 (file)
index 0000000..ce1036c
--- /dev/null
@@ -0,0 +1,46 @@
+import { RoomHierarchy } from 'matrix-js-sdk/lib/room-hierarchy';
+
+class RoomsHierarchy {
+  constructor(matrixClient, limit = 20, maxDepth = 1, suggestedOnly = false) {
+    this.matrixClient = matrixClient;
+    this._maxDepth = maxDepth;
+    this._suggestedOnly = suggestedOnly;
+    this._limit = limit;
+
+    this.roomIdToHierarchy = new Map();
+  }
+
+  getHierarchy(roomId) {
+    return this.roomIdToHierarchy.get(roomId);
+  }
+
+  removeHierarchy(roomId) {
+    return this.roomIdToHierarchy.delete(roomId);
+  }
+
+  canLoadMore(roomId) {
+    const roomHierarchy = this.getHierarchy(roomId);
+    if (!roomHierarchy) return true;
+    return roomHierarchy.canLoadMore;
+  }
+
+  async load(roomId, limit = this._limit) {
+    let roomHierarchy = this.getHierarchy(roomId);
+
+    if (!roomHierarchy) {
+      const room = this.matrixClient.getRoom(roomId);
+      if (!room) return null;
+      roomHierarchy = new RoomHierarchy(room, limit, this._maxDepth, this._suggestedOnly);
+      this.roomIdToHierarchy.set(roomId, roomHierarchy);
+    }
+
+    try {
+      await roomHierarchy.load(limit);
+      return roomHierarchy.rooms;
+    } catch {
+      return roomHierarchy.rooms;
+    }
+  }
+}
+
+export default RoomsHierarchy;