Skip to content

Commit

Permalink
Populate list of suggestions matching @mentions
Browse files Browse the repository at this point in the history
  • Loading branch information
acelaya committed Dec 19, 2024
1 parent 4b7f380 commit bd9669d
Show file tree
Hide file tree
Showing 5 changed files with 141 additions and 9 deletions.
6 changes: 5 additions & 1 deletion src/sidebar/components/Annotation/AnnotationEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,9 @@ function AnnotationEditor({

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

const atMentionsEnabled = store.isFeatureEnabled('at_mentions');
const usersWhoAnnotated = store.usersWhoAnnotated();

return (
/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */
<div
Expand All @@ -179,7 +182,8 @@ function AnnotationEditor({
label={isReplyAnno ? 'Enter reply' : 'Enter comment'}
text={text}
onEditText={onEditText}
atMentionsEnabled={store.isFeatureEnabled('at_mentions')}
atMentionsEnabled={atMentionsEnabled}
usersWhoAnnotated={usersWhoAnnotated}
/>
<TagEditor
onAddTag={onAddTag}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ describe('AnnotationEditor', () => {
removeDraft: sinon.stub(),
removeAnnotations: sinon.stub(),
isFeatureEnabled: sinon.stub().returns(false),
usersWhoAnnotated: sinon.stub().returns([]),
};

$imports.$mock(mockImportedComponents());
Expand Down
97 changes: 90 additions & 7 deletions src/sidebar/components/MarkdownEditor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,20 +181,44 @@ function ToolbarButton({
);
}

export type UserItem = {
username: string;
displayName: string | null;
};

type TextAreaProps = {
classes?: string;
containerRef?: Ref<HTMLTextAreaElement>;
atMentionsEnabled: boolean;
usersWhoAnnotated: UserItem[];
};

function TextArea({
classes,
containerRef,
atMentionsEnabled,
usersWhoAnnotated,
...restProps
}: TextAreaProps & JSX.TextareaHTMLAttributes<HTMLTextAreaElement>) {
const [popoverOpen, setPopoverOpen] = useState(false);
const [activeMention, setActiveMention] = useState<string>();
const textareaRef = useSyncedRef(containerRef);
const [highlightedSuggestion, setHighlightedSuggestion] = useState(0);
const suggestions = useMemo(() => {
if (!atMentionsEnabled || activeMention === undefined) {
return [];
}

return usersWhoAnnotated
.filter(
u =>
// Match all users if the active mention is empty, which happens right
// after typing `@`
!activeMention ||
`${u.username} ${u.displayName ?? ''}`.match(activeMention),
)
.slice(0, 10);
}, [activeMention, atMentionsEnabled, usersWhoAnnotated]);

useEffect(() => {
if (!atMentionsEnabled) {
Expand All @@ -212,17 +236,46 @@ function TextArea({
if (e.key === 'Escape') {
return;
}
setPopoverOpen(
termBeforePosition(textarea.value, textarea.selectionStart).startsWith(
'@',
),

const termBeforeCaret = termBeforePosition(
textarea.value,
textarea.selectionStart,
);
const isAtMention = termBeforeCaret.startsWith('@');

setPopoverOpen(isAtMention);
setActiveMention(isAtMention ? termBeforeCaret.substring(1) : undefined);
});

listenerCollection.add(textarea, 'keydown', e => {
if (
!popoverOpen ||
suggestions.length === 0 ||
!['ArrowDown', 'ArrowUp', 'Enter'].includes(e.key)
) {
return;
}

// When vertical arrows or Enter are pressed while the popover is open
// with suggestions, highlight or pick the right suggestion.
e.preventDefault();
e.stopPropagation();

if (e.key === 'ArrowDown') {
setHighlightedSuggestion(prev =>
Math.min(prev + 1, suggestions.length),
);
} else if (e.key === 'ArrowUp') {
setHighlightedSuggestion(prev => Math.max(prev - 1, 0));
} else if (e.key === 'Enter') {
// TODO "Print" suggestion in textarea
}
});

return () => {
listenerCollection.removeAll();
};
}, [atMentionsEnabled, popoverOpen, textareaRef]);
}, [atMentionsEnabled, popoverOpen, suggestions.length, textareaRef]);

return (
<div className="relative">
Expand All @@ -241,9 +294,30 @@ function TextArea({
open={popoverOpen}
onClose={() => setPopoverOpen(false)}
anchorElementRef={textareaRef}
classes="p-2"
classes="p-1"
>
Suggestions
<ul className="flex-col gap-y-0.5">
{suggestions.map((s, index) => (
<li
key={s.username}
className={classnames(
'flex justify-between items-center',
'rounded p-2 hover:bg-grey-2',
{
'bg-grey-2': highlightedSuggestion === index,
},
)}
>
<span className="truncate">{s.username}</span>
<span className="text-color-text-light">{s.displayName}</span>
</li>
))}
{suggestions.length === 0 && (
<li className="italic p-2">
No matches. You can still write the username
</li>
)}
</ul>
</Popover>
)}
</div>
Expand Down Expand Up @@ -391,6 +465,13 @@ export type MarkdownEditorProps = {
text: string;

onEditText?: (text: string) => void;

/**
* List of users who have annotated current document and belong to active group.
* This is used to populate the @mentions suggestions, when `atMentionsEnabled`
* is `true`.
*/
usersWhoAnnotated: UserItem[];
};

/**
Expand All @@ -402,6 +483,7 @@ export default function MarkdownEditor({
onEditText = () => {},
text,
textStyle = {},
usersWhoAnnotated,
}: MarkdownEditorProps) {
// Whether the preview mode is currently active.
const [preview, setPreview] = useState(false);
Expand Down Expand Up @@ -472,6 +554,7 @@ export default function MarkdownEditor({
value={text}
style={textStyle}
atMentionsEnabled={atMentionsEnabled}
usersWhoAnnotated={usersWhoAnnotated}
/>
)}
</div>
Expand Down
9 changes: 8 additions & 1 deletion src/sidebar/components/test/MarkdownEditor-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {
checkAccessibility,
mockImportedComponents,
} from '@hypothesis/frontend-testing';
import { mount } from '@hypothesis/frontend-testing';
import { mount, unmountAll } from '@hypothesis/frontend-testing';
import { render } from 'preact';
import { act } from 'preact/test-utils';

Expand All @@ -23,13 +23,18 @@ describe('MarkdownEditor', () => {
};
let fakeIsMacOS;
let MarkdownView;
let fakeStore;

beforeEach(() => {
fakeMarkdownCommands.convertSelectionToLink.resetHistory();
fakeMarkdownCommands.toggleBlockStyle.resetHistory();
fakeMarkdownCommands.toggleSpanStyle.resetHistory();
fakeIsMacOS = sinon.stub().returns(false);

fakeStore = {
isFeatureEnabled: sinon.stub().returns(false),
};

MarkdownView = function MarkdownView() {
return null;
};
Expand All @@ -41,11 +46,13 @@ describe('MarkdownEditor', () => {
'../../shared/user-agent': {
isMacOS: fakeIsMacOS,
},
'../store': { useSidebarStore: () => fakeStore },
});
});

afterEach(() => {
$imports.$restore();
unmountAll();
});

function createComponent(props = {}, mountProps = {}) {
Expand Down
37 changes: 37 additions & 0 deletions src/sidebar/store/modules/annotations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { createSelector } from 'reselect';
import { hasOwn } from '../../../shared/has-own';
import type { Annotation, SavedAnnotation } from '../../../types/api';
import type { HighlightCluster } from '../../../types/shared';
import { username as getUsername } from '../../helpers/account-id';
import * as metadata from '../../helpers/annotation-metadata';
import { isHighlight, isSaved } from '../../helpers/annotation-metadata';
import { countIf, toTrueMap, trueKeys } from '../../util/collections';
Expand All @@ -34,6 +35,11 @@ type AnnotationStub = {
$tag?: string;
};

export type UserItem = {
user: string;
displayName: string | null;
};

const initialState = {
annotations: [],
highlighted: {},
Expand Down Expand Up @@ -567,6 +573,36 @@ const savedAnnotations = createSelector(
annotations => annotations.filter(ann => isSaved(ann)) as SavedAnnotation[],
);

/**
* Return the list of unique users who authored any annotation, ordered by username.
*/
const usersWhoAnnotated = createSelector(
(state: State) => state.annotations,
annotations => {
const usersMap = new Map<
string,
{ username: string; displayName: string | null }
>();
annotations.forEach(anno => {
const username = getUsername(anno.user);
const displayName = anno.user_info?.display_name ?? null;

// Keep a unique list of users
if (!usersMap.has(username)) {
usersMap.set(username, { username, displayName });
}
});

// Sort users by username
return [...usersMap.values()].sort((a, b) => {
const lowerAUsername = a.username.toLowerCase();
const lowerBUsername = b.username.toLowerCase();

return lowerAUsername.localeCompare(lowerBUsername);
});
},
);

export const annotationsModule = createStoreModule(initialState, {
namespace: 'annotations',
reducers,
Expand Down Expand Up @@ -597,5 +633,6 @@ export const annotationsModule = createStoreModule(initialState, {
noteCount,
orphanCount,
savedAnnotations,
usersWhoAnnotated,
},
});

0 comments on commit bd9669d

Please sign in to comment.