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

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
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
22 changes: 21 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 @@ -10,6 +10,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 @@ -27,6 +28,7 @@ type AnnotationEditorProps = {

// Injected
annotationsService: AnnotationsService;
groups: GroupsService;
settings: SidebarSettings;
toastMessenger: ToastMessengerService;
tags: TagsService;
Expand All @@ -39,6 +41,7 @@ function AnnotationEditor({
annotation,
draft,
annotationsService,
groups: groupsService,
settings,
tags: tagsService,
toastMessenger,
Expand Down Expand Up @@ -169,6 +172,22 @@ function AnnotationEditor({

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

useEffect(() => {
const controller = new AbortController();

// When entering edit mode, load focused group members if not yet loaded
// TODO Do not start loading members if loading is already in progress for
// focused group
if (mentionsEnabled && focusedGroupId && focusedGroupMembers === null) {
groupsService.loadFocusedGroupMembers(focusedGroupId, controller.signal);
}

// TODO Abort loading group members only if focusedGroupId has changed
return () => controller.abort();
}, [focusedGroupId, focusedGroupMembers, groupsService, mentionsEnabled]);

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

export default withServices(AnnotationEditor, [
'annotationsService',
'groups',
'settings',
'tags',
'toastMessenger',
Expand Down
46 changes: 46 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(),
};

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

$imports.$mock(mockImportedComponents());
Expand Down Expand Up @@ -386,6 +393,45 @@ describe('AnnotationEditor', () => {
assert.isFalse(wrapper.find('AnnotationLicense').exists());
});

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

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
69 changes: 68 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 @@ -478,4 +480,69 @@ 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.
*
* @param [signal] - If provided, it can be used to cancel the loading of
* group members when aborted
*/
async loadFocusedGroupMembers(
groupId: string,
signal?: AbortSignal,
): Promise<void> {
const members = await this._fetchAllMembers(groupId, signal);
this._store.loadFocusedGroupMembers(members);
Copy link
Member

Choose a reason for hiding this comment

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

This code still has the issue that the focused group could change in between the call to loadFocusedGroupMembers and store.loadFocusedGroupMembers being called. At a minimum you need to ensure that members loaded for group A don't get saved as the members of group B if the focused group changes from A to B while fetching. Ideally you also want to stop fetching any further pages of members for group A.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yeah, sorry. This is not ready for review yet. I haven't finished applying all the changes from your previous review, but I forgot to move it to draft.

}

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.
for (let page = 2; page <= pages; page++) {
// Do not attempt any further request once the signal has been aborted
if (signal?.aborted) {
break;
}

// TODO Consider parallelizing requests
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
Loading