Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow SpotlightDialog person search on non-matrix attributes #247

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
33 changes: 9 additions & 24 deletions src/components/views/dialogs/spotlight/SpotlightDialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ import defaultDispatcher from "../../../../dispatcher/dispatcher";
import { ViewRoomPayload } from "../../../../dispatcher/payloads/ViewRoomPayload";
import { useDebouncedCallback } from "../../../../hooks/spotlight/useDebouncedCallback";
import { useRecentSearches } from "../../../../hooks/spotlight/useRecentSearches";
import { useWebSearchMetrics } from "../../../../hooks/spotlight/useWebSearchMetrics";
import { useProfileInfo } from "../../../../hooks/useProfileInfo";
import { usePublicRoomDirectory } from "../../../../hooks/usePublicRoomDirectory";
import { useSpaceResults } from "../../../../hooks/useSpaceResults";
import { useUserDirectory } from "../../../../hooks/useUserDirectory";
import { getKeyBindingsManager } from "../../../../KeyBindingsManager";
import { _t } from "../../../../languageHandler";
import { MatrixClientPeg } from "../../../../MatrixClientPeg";
import { PosthogAnalytics } from "../../../../PosthogAnalytics";
import { getCachedRoomIDForAlias } from "../../../../RoomAliasCache";
import { showStartChatInviteDialog } from "../../../../RoomInvite";
import { SettingLevel } from "../../../../settings/SettingLevel";
Expand Down Expand Up @@ -219,26 +219,6 @@ const toMemberResult = (member: Member | RoomMember): IMemberResult => ({

const recentAlgorithm = new RecentAlgorithm();

export const useWebSearchMetrics = (numResults: number, queryLength: number, viaSpotlight: boolean): void => {
useEffect(() => {
if (!queryLength) return;

// send metrics after a 1s debounce
const timeoutId = window.setTimeout(() => {
PosthogAnalytics.instance.trackEvent<WebSearchEvent>({
eventName: "WebSearch",
viaSpotlight,
numResults,
queryLength,
});
}, 1000);

return () => {
clearTimeout(timeoutId);
};
}, [numResults, queryLength, viaSpotlight]);
};

const findVisibleRooms = (cli: MatrixClient, msc3946ProcessDynamicPredecessor: boolean): Room[] => {
return cli.getVisibleRooms(msc3946ProcessDynamicPredecessor).filter((room) => {
// Do not show local rooms
Expand Down Expand Up @@ -351,7 +331,12 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = n
userIds.add(userId);
return userIds;
}, new Set<string>());
for (const user of [...findVisibleRoomMembers(cli, msc3946ProcessDynamicPredecessor), ...users]) {

const lcQuery = trimmedQuery.toLowerCase();
const members = findVisibleRoomMembers(cli);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should probably keep this:

Suggested change
const members = findVisibleRoomMembers(cli);
const members = findVisibleRoomMembers(cli, msc3946ProcessDynamicPredecessor);

const localUsers = members.filter((localResult) => [localResult.name, localResult.userId].some((q) => q.includes(lcQuery)));

for (const user of [...localUsers, ...users]) {
// Make sure we don't have any user more than once
if (alreadyAddedUserIds.has(user.userId)) continue;
alreadyAddedUserIds.add(user.userId);
Expand Down Expand Up @@ -383,7 +368,7 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = n
),
...publicRooms.map(toPublicRoomResult),
].filter((result) => filter === null || result.filter.includes(filter));
}, [cli, users, profile, publicRooms, filter, msc3946ProcessDynamicPredecessor]);
}, [cli, users, profile, publicRooms, filter, msc3946ProcessDynamicPredecessor, trimmedQuery]);

const results = useMemo<Record<Section, Result[]>>(() => {
const results: Record<Section, Result[]> = {
Expand All @@ -408,7 +393,7 @@ const SpotlightDialog: React.FC<IProps> = ({ initialText = "", initialFilter = n
)
return; // bail, does not match query
} else if (isMemberResult(entry)) {
if (!entry.query?.some((q) => q.includes(lcQuery))) return; // bail, does not match query
// do-not-bail, homeserver might be matching search query on attributes the client does not know about
} else if (isPublicRoomResult(entry)) {
if (!entry.query?.some((q) => q.includes(lcQuery))) return; // bail, does not match query
} else {
Expand Down
38 changes: 38 additions & 0 deletions src/hooks/spotlight/useWebSearchMetrics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
/*
Copyright 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.
*/

import { useEffect } from "react";
import { PosthogAnalytics } from "../../../src/PosthogAnalytics";

export const useWebSearchMetrics = (numResults: number, queryLength: number, viaSpotlight: boolean): void => {
useEffect(() => {
if (!queryLength) return;

// send metrics after a 1s debounce
const timeoutId = window.setTimeout(() => {
PosthogAnalytics.instance.trackEvent<WebSearchEvent>({
eventName: "WebSearch",
viaSpotlight,
numResults,
queryLength,
});
}, 1000);

return () => {
clearTimeout(timeoutId);
};
}, [numResults, queryLength, viaSpotlight]);
};
55 changes: 55 additions & 0 deletions test/components/views/dialogs/SpotlightDialog-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -449,4 +449,59 @@ describe("Spotlight Dialog", () => {
expect(screen.getByText(potatoRoom.name!)).toBeInTheDocument();
});
});

describe("user directory non-matrix attributes", () => {
interface IUserExternalAttributesChunkMember extends IUserChunkMember {
location?: string;
}

const testPersonExternalAttributtes: IUserExternalAttributesChunkMember = {
user_id: "@earthling:matrix.org",
display_name: "Earth Person",
avatar_url: undefined,
location: "Earth", // this attribute could come from a matrix homeserver connected to LDAP

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this test case is not clear: with this, searching by location would require searching for (a substring of) Earth, which is also a substring of earthling and Earth Person. That means it would also match in the current implementation. However with our change, the dialogue should be able to successfully find a user such as

            user_id: "@earthling:matrix.org",
            display_name: "Earth Person",
            avatar_url: undefined,
            location: "Mars",

with a query of Mars.

};

let mockedClient: MatrixClient;
beforeEach(() => {
const users: IUserExternalAttributesChunkMember[] = [testPersonExternalAttributtes]
mockedClient = mockClient({ rooms: [], users });
/* overwrite the function searchUserDirectory, to include non-matrix search attributes, used by the homeserver */
mockedClient.searchUserDirectory = jest.fn(({ term, limit }) => {
const searchTerm = term?.toLowerCase();
const results = users.filter(
(it) => {
return (
!searchTerm ||
it.user_id.toLowerCase().includes(searchTerm) ||
it.display_name?.toLowerCase().includes(searchTerm) ||
it.location?.toLowerCase().includes(searchTerm)
)
}
);
Comment on lines +472 to +481
Copy link

@HarHarLinks HarHarLinks Apr 20, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it seems superfluous to not just do

Suggested change
const results = users.filter(
(it) => {
return (
!searchTerm ||
it.user_id.toLowerCase().includes(searchTerm) ||
it.display_name?.toLowerCase().includes(searchTerm) ||
it.location?.toLowerCase().includes(searchTerm)
)
}
);
const results = users;

while this illustrates how the server works, i feel it overcomplicates things without being useful in this place. unless i'm overlooking something?

return Promise.resolve({
results: results.slice(0, limit ?? +Infinity),
limited: !!limit && limit < results.length,
});
});
});

it("should display in results, persons with non-matrix attributes matching the search query", async () => {
render(
<SpotlightDialog
initialFilter={Filter.People}
initialText={testPersonExternalAttributtes.location}
onFinished={() => null}
/>
);

// search is debounced
jest.advanceTimersByTime(200);
await flushPromisesWithFakeTimers();

const options = document.querySelectorAll("div.mx_SpotlightDialog_option");
expect(options.length).toBeGreaterThanOrEqual(1);
expect(options[0]!.innerHTML).toContain(testPersonExternalAttributtes.display_name);
});
});
});