Skip to content
This repository has been archived by the owner on Sep 11, 2024. It is now read-only.

Commit

Permalink
Merge branch 'andybalaam/dynamic-predecessor-in-roomprovider' into an…
Browse files Browse the repository at this point in the history
…dybalaam/dynamic-predecessor-in-spaceprovider
  • Loading branch information
andybalaam authored Mar 10, 2023
2 parents fc6d1d7 + 3dcf9cb commit ea45c3d
Show file tree
Hide file tree
Showing 11 changed files with 525 additions and 5 deletions.
189 changes: 189 additions & 0 deletions cypress/e2e/polls/pollHistory.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,189 @@
/*
Copyright 2022 - 2023 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.
*/

/// <reference types="cypress" />

import { HomeserverInstance } from "../../plugins/utils/homeserver";
import { MatrixClient } from "../../global";

describe("Poll history", () => {
let homeserver: HomeserverInstance;

type CreatePollOptions = {
title: string;
options: {
"id": string;
"org.matrix.msc1767.text": string;
}[];
};
const createPoll = async ({ title, options }: CreatePollOptions, roomId, client: MatrixClient) => {
return await client.sendEvent(roomId, "org.matrix.msc3381.poll.start", {
"org.matrix.msc3381.poll.start": {
question: {
"org.matrix.msc1767.text": title,
"body": title,
"msgtype": "m.text",
},
kind: "org.matrix.msc3381.poll.disclosed",
max_selections: 1,
answers: options,
},
"org.matrix.msc1767.text": "poll fallback text",
});
};

const botVoteForOption = async (
bot: MatrixClient,
roomId: string,
pollId: string,
optionId: string,
): Promise<void> => {
// We can't use the js-sdk types for this stuff directly, so manually construct the event.
await bot.sendEvent(roomId, "org.matrix.msc3381.poll.response", {
"m.relates_to": {
rel_type: "m.reference",
event_id: pollId,
},
"org.matrix.msc3381.poll.response": {
answers: [optionId],
},
});
};

const endPoll = async (bot: MatrixClient, roomId: string, pollId: string): Promise<void> => {
// We can't use the js-sdk types for this stuff directly, so manually construct the event.
await bot.sendEvent(roomId, "org.matrix.msc3381.poll.end", {
"m.relates_to": {
rel_type: "m.reference",
event_id: pollId,
},
"org.matrix.msc1767.text": "The poll has ended",
});
};

function openPollHistory(): void {
cy.get('.mx_HeaderButtons [aria-label="Room info"]').click();
cy.get(".mx_RoomSummaryCard").within(() => {
cy.contains("Polls history").click();
});
}

beforeEach(() => {
cy.window().then((win) => {
win.localStorage.setItem("mx_lhs_size", "0"); // Collapse left panel for these tests
});
cy.startHomeserver("default").then((data) => {
homeserver = data;

cy.enableLabsFeature("feature_poll_history");

cy.initTestUser(homeserver, "Tom");
});
});

afterEach(() => {
cy.stopHomeserver(homeserver);
});

it("Should display active and past polls", () => {
let bot: MatrixClient;
cy.getBot(homeserver, { displayName: "BotBob" }).then((_bot) => {
bot = _bot;
});

const pollParams1 = {
title: "Does the polls feature work?",
options: ["Yes", "No", "Maybe"].map((option) => ({
"id": option,
"org.matrix.msc1767.text": option,
})),
};

const pollParams2 = {
title: "Which way",
options: ["Left", "Right"].map((option) => ({
"id": option,
"org.matrix.msc1767.text": option,
})),
};

cy.createRoom({}).as("roomId");

cy.get<string>("@roomId").then((roomId) => {
cy.inviteUser(roomId, bot.getUserId());
cy.visit("/#/room/" + roomId);
// wait until Bob joined
cy.contains(".mx_TextualEvent", "BotBob joined the room").should("exist");
});

// active poll
cy.get<string>("@roomId")
.then(async (roomId) => {
const { event_id: pollId } = await createPoll(pollParams1, roomId, bot);
await botVoteForOption(bot, roomId, pollId, pollParams1.options[1].id);
return pollId;
})
.as("pollId1");

// ended poll
cy.get<string>("@roomId")
.then(async (roomId) => {
const { event_id: pollId } = await createPoll(pollParams2, roomId, bot);
await botVoteForOption(bot, roomId, pollId, pollParams1.options[1].id);
await endPoll(bot, roomId, pollId);
return pollId;
})
.as("pollId2");

openPollHistory();

// these polls are also in the timeline
// focus on the poll history dialog
cy.get(".mx_Dialog").within(() => {
// active poll is in active polls list
// open poll detail
cy.contains(pollParams1.title).click();

// vote in the poll
cy.contains("Yes").click();
cy.get('[data-testid="totalVotes"]').should("have.text", "Based on 2 votes");

// navigate back to list
cy.contains("Active polls").click();

// go to past polls list
cy.contains("Past polls").click();

cy.contains(pollParams2.title).should("exist");
});

// end poll1 while dialog is open
cy.all([cy.get<string>("@roomId"), cy.get<string>("@pollId1")]).then(async ([roomId, pollId]) => {
return endPoll(bot, roomId, pollId);
});

cy.get(".mx_Dialog").within(() => {
// both ended polls are in past polls list
cy.contains(pollParams2.title).should("exist");
cy.contains(pollParams1.title).should("exist");

cy.contains("Active polls").click();

// no more active polls
cy.contains("There are no active polls in this room").should("exist");
});
});
});
7 changes: 6 additions & 1 deletion src/components/structures/SpaceHierarchy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ import { Alignment } from "../views/elements/Tooltip";
import { getTopic } from "../../hooks/room/useTopic";
import { SdkContextClass } from "../../contexts/SDKContext";
import { getDisplayAliasForAliasSet } from "../../Rooms";
import SettingsStore from "../../settings/SettingsStore";

interface IProps {
space: Room;
Expand Down Expand Up @@ -425,7 +426,11 @@ interface IHierarchyLevelProps {
}

export const toLocalRoom = (cli: MatrixClient, room: IHierarchyRoom, hierarchy: RoomHierarchy): IHierarchyRoom => {
const history = cli.getRoomUpgradeHistory(room.room_id, true);
const history = cli.getRoomUpgradeHistory(
room.room_id,
true,
SettingsStore.getValue("feature_dynamic_room_predecessors"),
);

// Pick latest room that is actually part of the hierarchy
let cliRoom = null;
Expand Down
7 changes: 6 additions & 1 deletion src/components/views/dialogs/AddExistingToSpaceDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ import ProgressBar from "../elements/ProgressBar";
import DecoratedRoomAvatar from "../avatars/DecoratedRoomAvatar";
import QueryMatcher from "../../../autocomplete/QueryMatcher";
import LazyRenderList from "../elements/LazyRenderList";
import { useSettingValue } from "../../../hooks/useSettings";

// These values match CSS
const ROW_HEIGHT = 32 + 12;
Expand Down Expand Up @@ -135,7 +136,11 @@ export const AddExistingToSpace: React.FC<IAddExistingToSpaceProps> = ({
onFinished,
}) => {
const cli = useContext(MatrixClientContext);
const visibleRooms = useMemo(() => cli.getVisibleRooms().filter((r) => r.getMyMembership() === "join"), [cli]);
const msc3946ProcessDynamicPredecessor = useSettingValue<boolean>("feature_dynamic_room_predecessors");
const visibleRooms = useMemo(
() => cli.getVisibleRooms(msc3946ProcessDynamicPredecessor).filter((r) => r.getMyMembership() === "join"),
[cli, msc3946ProcessDynamicPredecessor],
);

const scrollRef = useRef<AutoHideScrollbar<"div">>();
const [scrollState, setScrollState] = useState<IScrollState>({
Expand Down
9 changes: 7 additions & 2 deletions src/components/views/dialogs/ForwardDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,16 @@ const ForwardDialog: React.FC<IProps> = ({ matrixClient: cli, event, permalinkCr
const lcQuery = query.toLowerCase();

const previewLayout = useSettingValue<Layout>("layout");
const msc3946DynamicRoomPredecessors = useSettingValue<boolean>("feature_dynamic_room_predecessors");

let rooms = useMemo(
() =>
sortRooms(cli.getVisibleRooms().filter((room) => room.getMyMembership() === "join" && !room.isSpaceRoom())),
[cli],
sortRooms(
cli
.getVisibleRooms(msc3946DynamicRoomPredecessors)
.filter((room) => room.getMyMembership() === "join" && !room.isSpaceRoom()),
),
[cli, msc3946DynamicRoomPredecessors],
);

if (lcQuery) {
Expand Down
27 changes: 26 additions & 1 deletion src/stores/OwnBeaconStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import {
} from "../utils/beacon";
import { getCurrentPosition } from "../utils/beacon";
import { doMaybeLocalRoomAction } from "../utils/local-room";
import SettingsStore from "../settings/SettingsStore";

const isOwnBeacon = (beacon: Beacon, userId: string): boolean => beacon.beaconInfoOwner === userId;

Expand Down Expand Up @@ -119,6 +120,10 @@ export class OwnBeaconStore extends AsyncStoreWithClient<OwnBeaconStoreState> {
* when the target is stationary
*/
private lastPublishedPositionTimestamp?: number;
/**
* Ref returned from watchSetting for the MSC3946 labs flag
*/
private dynamicWatcherRef: string | undefined;

public constructor() {
super(defaultDispatcher);
Expand All @@ -142,7 +147,12 @@ export class OwnBeaconStore extends AsyncStoreWithClient<OwnBeaconStoreState> {
this.matrixClient.removeListener(BeaconEvent.Update, this.onUpdateBeacon);
this.matrixClient.removeListener(BeaconEvent.Destroy, this.onDestroyBeacon);
this.matrixClient.removeListener(RoomStateEvent.Members, this.onRoomStateMembers);
SettingsStore.unwatchSetting(this.dynamicWatcherRef ?? "");

this.clearBeacons();
}

private clearBeacons(): void {
this.beacons.forEach((beacon) => beacon.destroy());

this.stopPollingLocation();
Expand All @@ -159,6 +169,11 @@ export class OwnBeaconStore extends AsyncStoreWithClient<OwnBeaconStoreState> {
this.matrixClient.on(BeaconEvent.Update, this.onUpdateBeacon);
this.matrixClient.on(BeaconEvent.Destroy, this.onDestroyBeacon);
this.matrixClient.on(RoomStateEvent.Members, this.onRoomStateMembers);
this.dynamicWatcherRef = SettingsStore.watchSetting(
"feature_dynamic_room_predecessors",
null,
this.reinitialiseBeaconState,
);

this.initialiseBeaconState();
}
Expand Down Expand Up @@ -308,9 +323,19 @@ export class OwnBeaconStore extends AsyncStoreWithClient<OwnBeaconStoreState> {
);
}

/**
* @internal public for test only
*/
public reinitialiseBeaconState = (): void => {
this.clearBeacons();
this.initialiseBeaconState();
};

private initialiseBeaconState = (): void => {
const userId = this.matrixClient.getUserId()!;
const visibleRooms = this.matrixClient.getVisibleRooms();
const visibleRooms = this.matrixClient.getVisibleRooms(
SettingsStore.getValue("feature_dynamic_room_predecessors"),
);

visibleRooms.forEach((room) => {
const roomState = room.currentState;
Expand Down
30 changes: 30 additions & 0 deletions test/components/structures/SpaceHierarchy-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ limitations under the License.
*/

import React from "react";
import { mocked } from "jest-mock";
import { render } from "@testing-library/react";
import { MatrixClient } from "matrix-js-sdk/src/client";
import { Room } from "matrix-js-sdk/src/models/room";
Expand All @@ -28,6 +29,7 @@ import { HierarchyLevel, showRoom, toLocalRoom } from "../../../src/components/s
import { Action } from "../../../src/dispatcher/actions";
import MatrixClientContext from "../../../src/contexts/MatrixClientContext";
import DMRoomMap from "../../../src/utils/DMRoomMap";
import SettingsStore from "../../../src/settings/SettingsStore";

// Fake random strings to give a predictable snapshot for checkbox IDs
jest.mock("matrix-js-sdk/src/randomstring", () => {
Expand Down Expand Up @@ -128,6 +130,34 @@ describe("SpaceHierarchy", () => {
const localRoomV3 = toLocalRoom(client, { room_id: roomV3.roomId } as IHierarchyRoom, hierarchy);
expect(localRoomV3.room_id).toEqual(roomV3.roomId);
});

describe("If the feature_dynamic_room_predecessors is not enabled", () => {
beforeEach(() => {
jest.spyOn(SettingsStore, "getValue").mockReturnValue(false);
});
it("Passes through the dynamic predecessor setting", async () => {
mocked(client.getRoomUpgradeHistory).mockClear();
const hierarchy = { roomMap: new Map([]) } as RoomHierarchy;
toLocalRoom(client, { room_id: roomV1.roomId } as IHierarchyRoom, hierarchy);
expect(client.getRoomUpgradeHistory).toHaveBeenCalledWith(roomV1.roomId, true, false);
});
});

describe("If the feature_dynamic_room_predecessors is enabled", () => {
beforeEach(() => {
// Turn on feature_dynamic_room_predecessors setting
jest.spyOn(SettingsStore, "getValue").mockImplementation(
(settingName) => settingName === "feature_dynamic_room_predecessors",
);
});

it("Passes through the dynamic predecessor setting", async () => {
mocked(client.getRoomUpgradeHistory).mockClear();
const hierarchy = { roomMap: new Map([]) } as RoomHierarchy;
toLocalRoom(client, { room_id: roomV1.roomId } as IHierarchyRoom, hierarchy);
expect(client.getRoomUpgradeHistory).toHaveBeenCalledWith(roomV1.roomId, true, true);
});
});
});

describe("<HierarchyLevel />", () => {
Expand Down
1 change: 1 addition & 0 deletions test/components/views/beacon/RoomLiveShareWarning-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ describe("<RoomLiveShareWarning />", () => {
getUserId: jest.fn().mockReturnValue(aliceId),
unstable_setLiveBeacon: jest.fn().mockResolvedValue({ event_id: "1" }),
sendEvent: jest.fn(),
isGuest: jest.fn().mockReturnValue(false),
});

// 14.03.2022 16:15
Expand Down
Loading

0 comments on commit ea45c3d

Please sign in to comment.