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

Add logic to load focused group members #6756

Merged
merged 1 commit into from
Jan 30, 2025
Merged
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
15 changes: 14 additions & 1 deletion src/sidebar/components/Annotation/AnnotationEditor.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useCallback, useMemo, useState } from 'preact/hooks';
import { useCallback, useEffect, useMemo, useState } from 'preact/hooks';

import type { Annotation } from '../../../types/api';
import type { SidebarSettings } from '../../../types/config';
Expand All @@ -11,6 +11,7 @@ import {
import { applyTheme } from '../../helpers/theme';
import { withServices } from '../../service-context';
import type { AnnotationsService } from '../../services/annotations';
import type { GroupsService } from '../../services/groups';
import type { TagsService } from '../../services/tags';
import type { ToastMessengerService } from '../../services/toast-messenger';
import { useSidebarStore } from '../../store';
Expand All @@ -28,6 +29,7 @@ type AnnotationEditorProps = {

// Injected
annotationsService: AnnotationsService;
groups: GroupsService;
settings: SidebarSettings;
toastMessenger: ToastMessengerService;
tags: TagsService;
Expand All @@ -40,6 +42,7 @@ function AnnotationEditor({
annotation,
draft,
annotationsService,
groups: groupsService,
settings,
tags: tagsService,
toastMessenger,
Expand Down Expand Up @@ -174,6 +177,15 @@ function AnnotationEditor({

const mentionsEnabled = store.isFeatureEnabled('at_mentions');
const usersWhoAnnotated = store.usersWhoAnnotated();
const focusedGroupMembers = store.getFocusedGroupMembers();
const focusedGroupId = store.focusedGroupId();

useEffect(() => {
// Load members for focused group only if not yet loaded
if (mentionsEnabled && focusedGroupId && focusedGroupMembers === null) {
groupsService.loadFocusedGroupMembers(focusedGroupId);
}
}, [focusedGroupId, focusedGroupMembers, groupsService, mentionsEnabled]);

return (
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */
Expand Down Expand Up @@ -214,6 +226,7 @@ function AnnotationEditor({

export default withServices(AnnotationEditor, [
'annotationsService',
'groups',
'settings',
'tags',
'toastMessenger',
Expand Down
63 changes: 63 additions & 0 deletions src/sidebar/components/Annotation/test/AnnotationEditor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from '@hypothesis/frontend-testing';
import { mount } from '@hypothesis/frontend-testing';
import { act } from 'preact/test-utils';
import sinon from 'sinon';

import * as fixtures from '../../../test/annotation-fixtures';
import AnnotationEditor, { $imports } from '../AnnotationEditor';
Expand All @@ -16,6 +17,7 @@ describe('AnnotationEditor', () => {
let fakeTagsService;
let fakeSettings;
let fakeToastMessenger;
let fakeGroupsService;

let fakeStore;

Expand All @@ -30,6 +32,7 @@ describe('AnnotationEditor', () => {
settings={fakeSettings}
tags={fakeTagsService}
toastMessenger={fakeToastMessenger}
groups={fakeGroupsService}
{...props}
/>,
);
Expand All @@ -54,6 +57,9 @@ describe('AnnotationEditor', () => {
error: sinon.stub(),
success: sinon.stub(),
};
fakeGroupsService = {
loadFocusedGroupMembers: sinon.stub().resolves(undefined),
};

fakeStore = {
createDraft: sinon.stub(),
Expand All @@ -63,6 +69,8 @@ describe('AnnotationEditor', () => {
removeAnnotations: sinon.stub(),
isFeatureEnabled: sinon.stub().returns(false),
usersWhoAnnotated: sinon.stub().returns([]),
getFocusedGroupMembers: sinon.stub(),
focusedGroupId: sinon.stub().returns(null),
};

$imports.$mock(mockImportedComponents());
Expand Down Expand Up @@ -405,6 +413,61 @@ describe('AnnotationEditor', () => {
});
});

describe('loading focused group members', () => {
[
{
atMentionsEnabled: true,
focusedGroupMembers: null,
focusedGroupId: 'group_id',
shouldLoadMembers: true,
},
{
atMentionsEnabled: true,
focusedGroupMembers: null,
focusedGroupId: null,
shouldLoadMembers: false,
},
{
atMentionsEnabled: false,
focusedGroupMembers: null,
focusedGroupId: 'group_id',
shouldLoadMembers: false,
},
{
atMentionsEnabled: true,
focusedGroupMembers: [],
focusedGroupId: 'group_id',
shouldLoadMembers: false,
},
{
atMentionsEnabled: false,
focusedGroupMembers: [],
focusedGroupId: 'group_id',
shouldLoadMembers: false,
},
].forEach(
({
atMentionsEnabled,
focusedGroupMembers,
focusedGroupId,
shouldLoadMembers,
}) => {
it('loads focused group members when mounted', () => {
fakeStore.isFeatureEnabled.returns(atMentionsEnabled);
fakeStore.getFocusedGroupMembers.returns(focusedGroupMembers);
fakeStore.focusedGroupId.returns(focusedGroupId);

createComponent();

assert.equal(
fakeGroupsService.loadFocusedGroupMembers.called,
shouldLoadMembers,
);
});
},
);
});

it(
'should pass a11y checks',
checkAccessibility([
Expand Down
23 changes: 23 additions & 0 deletions src/sidebar/services/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
RouteMap,
RouteMetadata,
Profile,
GroupMembers,
} from '../../types/api';
import { stripInternalProperties } from '../helpers/strip-internal-properties';
import type { SidebarStore } from '../store';
Expand Down Expand Up @@ -218,6 +219,17 @@ export class APIService {
member: {
delete: APICall<{ pubid: string; userid: string }>;
};
members: {
read: APICall<
{
pubid: string;
'page[number]'?: number;
'page[size]'?: number;
},
void,
GroupMembers
>;
};
read: APICall<{ id: string; expand: string[] }, void, Group>;
};
groups: {
Expand Down Expand Up @@ -287,6 +299,17 @@ export class APIService {
userid: string;
}>,
},
members: {
read: apiCall('group.members.read') as APICall<
{
pubid: string;
'page[number]'?: number;
'page[size]'?: number;
},
void,
GroupMembers
>,
},
read: apiCall('group.read') as APICall<
{ id: string; expand: string[] },
void,
Expand Down
81 changes: 80 additions & 1 deletion src/sidebar/services/groups.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import shallowEqual from 'shallowequal';

// @ts-ignore - TS doesn't know about SVG files.
import { default as logo } from '../../images/icons/logo.svg';
import type { Group } from '../../types/api';
import type { Group, GroupMember, GroupMembers } from '../../types/api';
import type { SidebarSettings } from '../../types/config';
import type { Service } from '../../types/config';
import { serviceConfig } from '../config/service-config';
Expand All @@ -23,6 +23,8 @@ const DEFAULT_ORGANIZATION = {
logo: 'data:image/svg+xml;utf8,' + encodeURIComponent(logo),
};

export const MEMBERS_PAGE_SIZE = 100;

/**
* For any group that does not have an associated organization, populate with
* the default Hypothesis organization.
Expand Down Expand Up @@ -61,6 +63,12 @@ export class GroupsService {
private _serviceConfig: Service | null;
private _reloadSetUp: boolean;

/**
* Tracks the loading of the focused group members.
* If this is null it means we are not loading members yet.
*/
private _focusedMembersController: AbortController | null = null;

constructor(
store: SidebarStore,
api: APIService,
Expand Down Expand Up @@ -450,6 +458,10 @@ export class GroupsService {

const groupHasChanged = prevGroupId !== newGroupId && prevGroupId !== null;
if (groupHasChanged && newGroupId) {
// Abort previous in-flight members loading if the group was different
// from the focused one
this._focusedMembersController?.abort();

// Move any top-level new annotations to the newly-focused group.
// Leave replies where they are.
const updatedAnnotations = this._store
Expand Down Expand Up @@ -478,4 +490,71 @@ export class GroupsService {
userid: 'me',
});
}

/**
* Fetch members for a group from the API and load them into the store as the
* members of the focused group.
*/
async loadFocusedGroupMembers(groupId: string): Promise<void> {
Copy link
Member

Choose a reason for hiding this comment

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

The focused group ID doesn't need to be an argument to this method as we always want to load members for the group that is currently focused, and the service can get that from the store.

Copy link
Contributor Author

@acelaya acelaya Jan 30, 2025

Choose a reason for hiding this comment

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

Yeah, I know you suggested that in the previous review, and at some point the method was implemented that way.

However, not passing a group ID here means the side effect in the component does not need to depend on the focused group ID, and therefore, it does not re-run if focused group changes while mounted, and before members have been loaded, the group changes again.

One solution would be to still add the focused group ID as a dependency, but it wouldn't be immediately obvious why.

I think there has to be a way to still make that work. Perhaps ensuring focusedGroupMembers value changes when another group is focused. Right now it could be null already, so it wouldn't change and therefore, wouldn't trigger a re-render.

Anyway, I'll try to think about that separately, as this PR is big enough already.

// Abort previous loading, if any
this._focusedMembersController?.abort();

this._focusedMembersController = new AbortController();
const { signal } = this._focusedMembersController;

const members = await this._fetchAllMembers(groupId, signal);
if (!signal?.aborted) {
this._store.loadFocusedGroupMembers(members);
}
acelaya marked this conversation as resolved.
Show resolved Hide resolved
}

private async _fetchAllMembers(
groupId: string,
signal?: AbortSignal,
): Promise<GroupMember[]> {
// Fetch first page of members, to determine how many more pages there are
Copy link
Member

Choose a reason for hiding this comment

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

There is a race condition here that if group members are added while we are paging through, we will end up with duplicates. Unlikely, but possible in principle.

Copy link
Contributor Author

@acelaya acelaya Jan 20, 2025

Choose a reason for hiding this comment

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

True. Something similar could happen if a member that's already fetched in a previous page is removed. That could cause a member from a subsequent page to not be fetched since it has moved a position "up" and is now part of a page which is supposedly fetched already.

None of these issues are easy to handle with current API contract though, where pagination is not done via cursor, but good to have in mind.

const firstPage = await this._fetchMembers({ groupId, signal });
const pages = Math.min(
Math.ceil(firstPage.meta.page.total / MEMBERS_PAGE_SIZE),
// Do not try to load more than 10 pages, to avoid long loading times and
// hitting the server too much
10,
);
let members = firstPage.data;

// Fetch remaining pages. Start at 2 to skip first one which was already
// loaded.
// TODO Consider parallelizing requests
for (let page = 2; page <= pages; page++) {
// Do not attempt any further request once the signal has been aborted
if (signal?.aborted) {
break;
}

const membersPage = await this._fetchMembers({ groupId, page, signal });
members = members.concat(membersPage.data);
}

return members;
}
acelaya marked this conversation as resolved.
Show resolved Hide resolved

private _fetchMembers({
groupId,
page = 1,
signal,
}: {
groupId: string;
page?: number;
signal?: AbortSignal;
}): Promise<GroupMembers> {
return this._api.group.members.read(
{
pubid: groupId,
'page[number]': page,
'page[size]': MEMBERS_PAGE_SIZE,
},
undefined,
signal,
);
}
}
7 changes: 7 additions & 0 deletions src/sidebar/services/test/api-index.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,13 @@
"desc": "Remove the current user from a group."
}
},
"members": {
"read": {
"url": "https://example.com/api/groups/:pubid/members",
"method": "GET",
"desc": "Fetch a list of all members of a group"
}
},
"read": {
"url": "https://example.com/api/groups/:id",
"method": "GET",
Expand Down
20 changes: 20 additions & 0 deletions src/sidebar/services/test/api-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,26 @@ describe('APIService', () => {
return api.group.member.delete({ pubid: 'an-id', userid: 'me' });
});

it('gets group members', () => {
const groupMembers = {
meta: {
page: { total: 0 },
},
data: [],
};
expectCall(
'get',
`groups/an-id/members?${encodeURIComponent('page[number]')}=1&${encodeURIComponent('page[size]')}=100`,
200,
groupMembers,
);
return api.group.members.read({
pubid: 'an-id',
'page[number]': 1,
'page[size]': 100,
});
});

it('gets a group by provided group id', () => {
const group = { id: 'group-id', name: 'Group' };
expectCall('get', 'groups/group-id', 200, group);
Expand Down
Loading