Skip to content

Handle mention suggestions for third party users #6889

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

Merged
merged 1 commit into from
Mar 14, 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
12 changes: 12 additions & 0 deletions src/sidebar/components/Annotation/AnnotationEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,14 @@ import { useCallback, useEffect, useMemo, useState } from 'preact/hooks';
import type { Annotation } from '../../../types/api';
import type { SidebarSettings } from '../../../types/config';
import { serviceConfig } from '../../config/service-config';
import { isThirdPartyUser } from '../../helpers/account-id';
import {
annotationRole,
isReply,
isSaved,
} from '../../helpers/annotation-metadata';
import { combineUsersForMentions } from '../../helpers/mention-suggestions';
import type { MentionMode } from '../../helpers/mentions';
import { applyTheme } from '../../helpers/theme';
import { withServices } from '../../service-context';
import type { AnnotationsService } from '../../services/annotations';
Expand Down Expand Up @@ -176,6 +178,15 @@ function AnnotationEditor({

const textStyle = applyTheme(['annotationFontFamily'], settings);

const defaultAuthority = store.defaultAuthority();
const mentionMode = useMemo(
(): MentionMode =>
isThirdPartyUser(annotation.user, defaultAuthority)
? 'display-name'
: 'username',
[annotation.user, defaultAuthority],
);

const mentionsEnabled = store.isFeatureEnabled('at_mentions');
const usersWhoAnnotated = store.usersWhoAnnotated();
const focusedGroupMembers = store.getFocusedGroupMembers();
Expand Down Expand Up @@ -207,6 +218,7 @@ function AnnotationEditor({
usersForMentions={usersForMentions}
showHelpLink={showHelpLink}
mentions={annotation.mentions}
mentionMode={mentionMode}
/>
<TagEditor
onAddTag={onAddTag}
Expand Down
28 changes: 28 additions & 0 deletions src/sidebar/components/Annotation/test/AnnotationEditor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ describe('AnnotationEditor', () => {
isFeatureEnabled: sinon.stub().returns(false),
usersWhoAnnotated: sinon.stub().returns([]),
getFocusedGroupMembers: sinon.stub().returns({ status: 'not-loaded' }),
defaultAuthority: sinon.stub().returns(''),
};

$imports.$mock(mockImportedComponents());
Expand Down Expand Up @@ -449,6 +450,33 @@ describe('AnnotationEditor', () => {
});
});

[
{
defaultAuthority: 'example.com',
expectedMentionMode: 'username',
},
{
defaultAuthority: 'foo.com',
expectedMentionMode: 'display-name',
},
].forEach(({ defaultAuthority, expectedMentionMode }) => {
it('sets expected mention mode based on annotation author', () => {
fakeStore.defaultAuthority.returns(defaultAuthority);

const wrapper = createComponent({
annotation: {
...fixtures.defaultAnnotation(),
user: 'acct:[email protected]',
},
});

assert.equal(
wrapper.find('MarkdownEditor').prop('mentionMode'),
expectedMentionMode,
);
});
});

it(
'should pass a11y checks',
checkAccessibility([
Expand Down
12 changes: 10 additions & 2 deletions src/sidebar/components/MarkdownEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@ import type {
UsersForMentions,
} from '../helpers/mention-suggestions';
import { usersMatchingMention } from '../helpers/mention-suggestions';
import type { MentionMode } from '../helpers/mentions';
import {
getContainingMentionOffsets,
termBeforePosition,
toPlainTextMention,
unwrapMentions,
} from '../helpers/mentions';
import {
Expand Down Expand Up @@ -204,6 +206,7 @@ type TextAreaProps = {
mentionsEnabled: boolean;
usersForMentions: UsersForMentions;
onEditText: (text: string) => void;
mentionMode: MentionMode;
};

function TextArea({
Expand All @@ -213,6 +216,7 @@ function TextArea({
usersForMentions,
onEditText,
onKeyDown,
mentionMode,
...restProps
}: TextAreaProps & JSX.TextareaHTMLAttributes) {
const [popoverOpen, setPopoverOpen] = useState(false);
Expand Down Expand Up @@ -261,7 +265,7 @@ function TextArea({
textarea.selectionStart,
);
const beforeMention = value.slice(0, start);
const beforeCaret = `${beforeMention}@${suggestion.username} `;
const beforeCaret = `${beforeMention}${toPlainTextMention(suggestion, mentionMode)} `;
const afterMention = value.slice(end);

// Set textarea value directly, set new caret position and keep it focused.
Expand All @@ -277,7 +281,7 @@ function TextArea({
setPopoverOpen(false);
setHighlightedSuggestion(0);
},
[onEditText, textareaRef],
[mentionMode, onEditText, textareaRef],
);

const usersListboxId = useId();
Expand Down Expand Up @@ -376,6 +380,7 @@ function TextArea({
highlightedSuggestion={highlightedSuggestion}
onSelectUser={insertMention}
usersListboxId={usersListboxId}
mentionMode={mentionMode}
/>
)}
</div>
Expand Down Expand Up @@ -547,6 +552,7 @@ export type MarkdownEditorProps = {

/** List of mentions extracted from the annotation text. */
mentions?: Mention[];
mentionMode: MentionMode;
};

/**
Expand All @@ -561,6 +567,7 @@ export default function MarkdownEditor({
showHelpLink = true,
usersForMentions,
mentions,
mentionMode,
}: MarkdownEditorProps) {
// Whether the preview mode is currently active.
const [preview, setPreview] = useState(false);
Expand Down Expand Up @@ -634,6 +641,7 @@ export default function MarkdownEditor({
style={textStyle}
mentionsEnabled={mentionsEnabled}
usersForMentions={usersForMentions}
mentionMode={mentionMode}
/>
)}
</div>
Expand Down
94 changes: 65 additions & 29 deletions src/sidebar/components/MentionSuggestionsPopover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,63 @@ import { Popover } from '@hypothesis/frontend-shared';
import type { PopoverProps } from '@hypothesis/frontend-shared/lib/components/feedback/Popover';
import classnames from 'classnames';

export type UserItem = {
username: string;
displayName: string | null;
import type { UserItem } from '../helpers/mention-suggestions';
import type { MentionMode } from '../helpers/mentions';

type SuggestionItemProps = {
user: UserItem;
usersListboxId: string;
highlighted: boolean;
mentionMode: MentionMode;
onSelectUser: (user: UserItem) => void;
};

function SuggestionItem({
user,
usersListboxId,
highlighted,
mentionMode,
onSelectUser,
}: SuggestionItemProps) {
const showUsername = mentionMode === 'username';

return (
// These options are indirectly handled via keyboard event
// handlers in the textarea, hence, we don't want to add keyboard
// event handlers here, but we want to handle click events.
// eslint-disable-next-line jsx-a11y/click-events-have-key-events
<li
key={user.username}
id={`${usersListboxId}-${user.username}`}
className={classnames(
'flex justify-between items-center gap-x-2',
'rounded p-2 hover:bg-grey-2',
// Adjust line height relative to the font size. This avoids
// vertically cropped usernames due to the use of `truncate`.
'leading-tight',
{
'bg-grey-2': highlighted,
},
)}
onClick={e => {
e.stopPropagation();
onSelectUser(user);
}}
role="option"
aria-selected={highlighted}
>
{showUsername && (
<span className="truncate" data-testid={`username-${user.username}`}>
{user.username}
</span>
)}
<span className={classnames({ 'text-color-text-light': showUsername })}>
{user.displayName}
</span>
</li>
);
}

export type MentionSuggestionsPopoverProps = Pick<
PopoverProps,
'open' | 'onClose' | 'anchorElementRef'
Expand All @@ -21,6 +73,8 @@ export type MentionSuggestionsPopoverProps = Pick<
onSelectUser: (selectedSuggestion: UserItem) => void;
/** Element ID for the user suggestions listbox */
usersListboxId: string;
/** Determines what information to display in suggestions */
mentionMode: MentionMode;
};

/**
Expand All @@ -32,6 +86,7 @@ export default function MentionSuggestionsPopover({
onSelectUser,
highlightedSuggestion,
usersListboxId,
mentionMode,
...popoverProps
}: MentionSuggestionsPopoverProps) {
return (
Expand All @@ -52,33 +107,14 @@ export default function MentionSuggestionsPopover({
) : (
<>
{users.map((u, index) => (
// These options are indirectly handled via keyboard event
// handlers in the textarea, hence, we don't want to add keyboard
// event handlers here, but we want to handle click events.
// eslint-disable-next-line jsx-a11y/click-events-have-key-events
<li
<SuggestionItem
key={u.username}
id={`${usersListboxId}-${u.username}`}
className={classnames(
'flex justify-between items-center gap-x-2',
'rounded p-2 hover:bg-grey-2',
// Adjust line height relative to the font size. This avoids
// vertically cropped usernames due to the use of `truncate`.
'leading-tight',
{
'bg-grey-2': highlightedSuggestion === index,
},
)}
onClick={e => {
e.stopPropagation();
onSelectUser(u);
}}
role="option"
aria-selected={highlightedSuggestion === index}
>
<span className="truncate">{u.username}</span>
<span className="text-color-text-light">{u.displayName}</span>
</li>
user={u}
highlighted={highlightedSuggestion === index}
mentionMode={mentionMode}
usersListboxId={usersListboxId}
onSelectUser={onSelectUser}
/>
))}
{users.length === 0 && (
<li className="italic p-2" data-testid="suggestions-fallback">
Expand Down
38 changes: 37 additions & 1 deletion src/sidebar/components/test/MentionSuggestionsPopover-test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mount } from '@hypothesis/frontend-testing';
import { checkAccessibility, mount } from '@hypothesis/frontend-testing';
import { useRef } from 'preact/hooks';
import sinon from 'sinon';

Expand Down Expand Up @@ -28,6 +28,7 @@ describe('MentionSuggestionsPopover', () => {
users={defaultUsers}
highlightedSuggestion={0}
onSelectUser={sinon.stub()}
mentionMode="username"
{...props}
open
/>,
Expand Down Expand Up @@ -90,4 +91,39 @@ describe('MentionSuggestionsPopover', () => {
assert.calledWith(onSelectUser, defaultUsers[index]);
});
});

[
{
mentionMode: 'username',
shouldShowUsernames: true,
},
{
mentionMode: 'display-name',
shouldShowUsernames: false,
},
].forEach(({ mentionMode, shouldShowUsernames }) => {
it('renders expected suggestions according to mention mode', () => {
const wrapper = createComponent({ mentionMode });

assert.equal(
wrapper.exists('[data-testid="username-one"]'),
shouldShowUsernames,
);
assert.equal(
wrapper.exists('[data-testid="username-two"]'),
shouldShowUsernames,
);
assert.equal(
wrapper.exists('[data-testid="username-three"]'),
shouldShowUsernames,
);
});
});

it(
'should pass a11y checks',
checkAccessibility({
content: () => createComponent(),
}),
);
});
16 changes: 11 additions & 5 deletions src/sidebar/helpers/mention-suggestions.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import type { FocusedGroupMembers } from '../store/modules/groups';

export type UserItem = {
/** User ID in the form of acct:[username]@[authority] */
userid: string;
username: string;
displayName: string | null;
};
Expand Down Expand Up @@ -29,13 +31,17 @@ export function combineUsersForMentions(
// Once group members are loaded, we can merge them with the users who
// already annotated the document, then deduplicate and sort the result.
const focusedGroupUsers: UserItem[] = focusedGroupMembers.members.map(
({ username, display_name: displayName }) => ({ username, displayName }),
({ userid, username, display_name: displayName }) => ({
userid,
username,
displayName,
}),
);
const addedUsernames = new Set<string>();
const addedUserIds = new Set<string>();
const users = [...usersWhoAnnotated, ...focusedGroupUsers]
.filter(({ username }) => {
const usernameAlreadyAdded = addedUsernames.has(username);
addedUsernames.add(username);
.filter(({ userid }) => {
const usernameAlreadyAdded = addedUserIds.has(userid);
addedUserIds.add(userid);
return !usernameAlreadyAdded;
})
.sort((a, b) => a.username.localeCompare(b.username));
Expand Down
Loading