-
Notifications
You must be signed in to change notification settings - Fork 203
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
Populate list of suggestions matching @mentions #6728
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -2,7 +2,6 @@ import { | |
Button, | ||
IconButton, | ||
Link, | ||
Popover, | ||
useSyncedRef, | ||
} from '@hypothesis/frontend-shared'; | ||
import { | ||
|
@@ -20,9 +19,14 @@ import { | |
import type { IconComponent } from '@hypothesis/frontend-shared/lib/types'; | ||
import classnames from 'classnames'; | ||
import type { Ref, JSX } from 'preact'; | ||
import { useEffect, useMemo, useRef, useState } from 'preact/hooks'; | ||
import { | ||
useCallback, | ||
useEffect, | ||
useMemo, | ||
useRef, | ||
useState, | ||
} from 'preact/hooks'; | ||
|
||
import { ListenerCollection } from '../../shared/listener-collection'; | ||
import { isMacOS } from '../../shared/user-agent'; | ||
import { | ||
LinkType, | ||
|
@@ -31,8 +35,12 @@ import { | |
toggleSpanStyle, | ||
} from '../markdown-commands'; | ||
import type { EditorState } from '../markdown-commands'; | ||
import { termBeforePosition } from '../util/term-before-position'; | ||
import { | ||
getContainingWordOffsets, | ||
termBeforePosition, | ||
} from '../util/term-before-position'; | ||
import MarkdownView from './MarkdownView'; | ||
import MentionPopover from './MentionPopover'; | ||
|
||
/** | ||
* Toolbar commands that modify the editor state. This excludes the Help link | ||
|
@@ -181,49 +189,96 @@ function ToolbarButton({ | |
); | ||
} | ||
|
||
export type UserItem = { | ||
username: string; | ||
displayName: string | null; | ||
}; | ||
|
||
type TextAreaProps = { | ||
classes?: string; | ||
containerRef?: Ref<HTMLTextAreaElement>; | ||
atMentionsEnabled: boolean; | ||
mentionsEnabled: boolean; | ||
usersForMentions: UserItem[]; | ||
onEditText: (text: string) => void; | ||
}; | ||
|
||
function TextArea({ | ||
classes, | ||
containerRef, | ||
atMentionsEnabled, | ||
mentionsEnabled, | ||
usersForMentions, | ||
onEditText, | ||
onKeyDown, | ||
...restProps | ||
}: TextAreaProps & JSX.TextareaHTMLAttributes<HTMLTextAreaElement>) { | ||
}: TextAreaProps & JSX.TextareaHTMLAttributes) { | ||
const [popoverOpen, setPopoverOpen] = useState(false); | ||
const [activeMention, setActiveMention] = useState<string>(); | ||
const textareaRef = useSyncedRef(containerRef); | ||
|
||
useEffect(() => { | ||
acelaya marked this conversation as resolved.
Show resolved
Hide resolved
|
||
if (!atMentionsEnabled) { | ||
return () => {}; | ||
const [highlightedSuggestion, setHighlightedSuggestion] = useState(0); | ||
const userSuggestions = useMemo(() => { | ||
if (!mentionsEnabled || activeMention === undefined) { | ||
return []; | ||
} | ||
|
||
const textarea = textareaRef.current!; | ||
const listenerCollection = new ListenerCollection(); | ||
const checkForMentionAtCaret = () => { | ||
const term = termBeforePosition(textarea.value, textarea.selectionStart); | ||
setPopoverOpen(term.startsWith('@')); | ||
}; | ||
|
||
// We listen for `keyup` to make sure the text in the textarea reflects the | ||
// just-pressed key when we evaluate it | ||
listenerCollection.add(textarea, 'keyup', e => { | ||
// `Esc` key is used to close the popover. Do nothing and let users close | ||
// it that way, even if the caret is in a mention | ||
if (e.key !== 'Escape') { | ||
checkForMentionAtCaret(); | ||
return usersForMentions | ||
.filter( | ||
u => | ||
// Match all users if the active mention is empty, which happens right | ||
// after typing `@` | ||
!activeMention || | ||
`${u.username} ${u.displayName ?? ''}` | ||
acelaya marked this conversation as resolved.
Show resolved
Hide resolved
|
||
.toLowerCase() | ||
.match(activeMention.toLowerCase()), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'd suggest pulling this out into a function with its own tests in future. |
||
) | ||
.slice(0, 10); | ||
}, [activeMention, mentionsEnabled, usersForMentions]); | ||
|
||
const checkForMentionAtCaret = useCallback( | ||
(textarea: HTMLTextAreaElement) => { | ||
if (!mentionsEnabled) { | ||
return; | ||
} | ||
}); | ||
|
||
// When clicking the textarea it's possible the caret is moved "into" a | ||
// mention, so we check if the popover should be opened | ||
listenerCollection.add(textarea, 'click', checkForMentionAtCaret); | ||
const term = termBeforePosition(textarea.value, textarea.selectionStart); | ||
const isAtMention = term.startsWith('@'); | ||
|
||
return () => listenerCollection.removeAll(); | ||
}, [atMentionsEnabled, popoverOpen, textareaRef]); | ||
setPopoverOpen(isAtMention); | ||
setActiveMention(isAtMention ? term.substring(1) : undefined); | ||
|
||
// Reset highlighted suggestion when closing the popover | ||
if (!isAtMention) { | ||
setHighlightedSuggestion(0); | ||
} | ||
}, | ||
[mentionsEnabled], | ||
); | ||
const insertMention = useCallback( | ||
(suggestion: UserItem) => { | ||
const textarea = textareaRef.current!; | ||
const { value } = textarea; | ||
const { start, end } = getContainingWordOffsets( | ||
value, | ||
textarea.selectionStart, | ||
); | ||
const beforeMention = value.slice(0, start); | ||
const beforeCaret = `${beforeMention}@${suggestion.username} `; | ||
const afterMention = value.slice(end); | ||
|
||
// Set textarea value directly, set new caret position and keep it focused. | ||
textarea.value = `${beforeCaret}${afterMention}`; | ||
textarea.selectionStart = beforeCaret.length; | ||
textarea.selectionEnd = beforeCaret.length; | ||
textarea.focus(); | ||
// Then update state to keep it in sync. | ||
onEditText(textarea.value); | ||
acelaya marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Close popover and reset highlighted suggestion once the value is | ||
// replaced | ||
setPopoverOpen(false); | ||
setHighlightedSuggestion(0); | ||
}, | ||
[onEditText, textareaRef], | ||
); | ||
|
||
return ( | ||
<div className="relative"> | ||
|
@@ -234,18 +289,59 @@ function TextArea({ | |
'focus:bg-white focus:outline-none focus:shadow-focus-inner', | ||
classes, | ||
)} | ||
onInput={(e: Event) => onEditText((e.target as HTMLInputElement).value)} | ||
{...restProps} | ||
// We listen for `keyup` to make sure the text in the textarea reflects | ||
// the just-pressed key when we evaluate it | ||
onKeyUp={e => { | ||
// `Esc` key is used to close the popover. Do nothing and let users | ||
// close it that way, even if the caret is in a mention. | ||
// `Enter` is handled on keydown. Do not handle it here. | ||
if (!['Escape', 'Enter'].includes(e.key)) { | ||
checkForMentionAtCaret(e.target as HTMLTextAreaElement); | ||
} | ||
}} | ||
onKeyDown={e => { | ||
// Invoke original handler if present | ||
onKeyDown?.(e); | ||
|
||
if (!popoverOpen || userSuggestions.length === 0) { | ||
return; | ||
} | ||
|
||
// When vertical arrows are pressed while the popover is open with | ||
// user suggestions, highlight the right one. | ||
// When `Enter` is pressed, insert highlighted one. | ||
if (e.key === 'ArrowDown') { | ||
e.preventDefault(); | ||
setHighlightedSuggestion(prev => | ||
Math.min(prev + 1, userSuggestions.length - 1), | ||
); | ||
} else if (e.key === 'ArrowUp') { | ||
e.preventDefault(); | ||
setHighlightedSuggestion(prev => Math.max(prev - 1, 0)); | ||
} else if (e.key === 'Enter') { | ||
e.preventDefault(); | ||
insertMention(userSuggestions[highlightedSuggestion]); | ||
} | ||
}} | ||
onClick={e => { | ||
e.stopPropagation(); | ||
// When clicking the textarea, it's possible the caret is moved "into" a | ||
// mention, so we check if the popover should be opened | ||
checkForMentionAtCaret(e.target as HTMLTextAreaElement); | ||
}} | ||
ref={textareaRef} | ||
/> | ||
{atMentionsEnabled && ( | ||
<Popover | ||
{mentionsEnabled && ( | ||
<MentionPopover | ||
open={popoverOpen} | ||
onClose={() => setPopoverOpen(false)} | ||
anchorElementRef={textareaRef} | ||
classes="p-2" | ||
> | ||
Suggestions | ||
</Popover> | ||
users={userSuggestions} | ||
highlightedSuggestion={highlightedSuggestion} | ||
onSelectUser={insertMention} | ||
/> | ||
)} | ||
</div> | ||
); | ||
|
@@ -380,7 +476,7 @@ export type MarkdownEditorProps = { | |
* Whether the at-mentions feature ir enabled or not. | ||
* Defaults to false. | ||
*/ | ||
atMentionsEnabled?: boolean; | ||
mentionsEnabled?: boolean; | ||
|
||
/** An accessible label for the input field */ | ||
label: string; | ||
|
@@ -392,17 +488,27 @@ export type MarkdownEditorProps = { | |
text: string; | ||
|
||
onEditText?: (text: string) => void; | ||
|
||
/** | ||
* Base list of users used to populate the @mentions suggestions, when | ||
* `mentionsEnabled` is `true`. | ||
* The list will be filtered and narrowed down based on the partial mention. | ||
* The mention can still be set manually. It is not restricted to the items on | ||
* this list. | ||
*/ | ||
usersForMentions: UserItem[]; | ||
}; | ||
|
||
/** | ||
* Viewer/editor for the body of an annotation in markdown format. | ||
*/ | ||
export default function MarkdownEditor({ | ||
atMentionsEnabled = false, | ||
mentionsEnabled = false, | ||
label, | ||
onEditText = () => {}, | ||
text, | ||
textStyle = {}, | ||
usersForMentions, | ||
}: MarkdownEditorProps) { | ||
// Whether the preview mode is currently active. | ||
const [preview, setPreview] = useState(false); | ||
|
@@ -465,14 +571,12 @@ export default function MarkdownEditor({ | |
'text-base touch:text-touch-base', | ||
)} | ||
containerRef={input} | ||
onClick={(e: Event) => e.stopPropagation()} | ||
onKeyDown={handleKeyDown} | ||
onInput={(e: Event) => | ||
onEditText((e.target as HTMLInputElement).value) | ||
} | ||
onEditText={onEditText} | ||
value={text} | ||
style={textStyle} | ||
atMentionsEnabled={atMentionsEnabled} | ||
mentionsEnabled={mentionsEnabled} | ||
usersForMentions={usersForMentions} | ||
/> | ||
)} | ||
</div> | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
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; | ||
}; | ||
|
||
export type MentionPopoverProps = Pick< | ||
PopoverProps, | ||
'open' | 'onClose' | 'anchorElementRef' | ||
> & { | ||
/** List of users to suggest */ | ||
users: UserItem[]; | ||
/** Index for currently highlighted suggestion */ | ||
highlightedSuggestion: number; | ||
/** Invoked when a user is selected */ | ||
onSelectUser: (selectedSuggestion: UserItem) => void; | ||
}; | ||
|
||
/** | ||
* A Popover component that displays a list of user suggestions for @mentions. | ||
*/ | ||
export default function MentionPopover({ | ||
users, | ||
onSelectUser, | ||
highlightedSuggestion, | ||
...popoverProps | ||
}: MentionPopoverProps) { | ||
return ( | ||
<Popover {...popoverProps} classes="p-1"> | ||
<ul | ||
className="flex-col gap-y-0.5" | ||
role="listbox" | ||
aria-orientation="vertical" | ||
> | ||
{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 | ||
key={u.username} | ||
className={classnames( | ||
'flex justify-between items-center', | ||
'rounded p-2 hover:bg-grey-2', | ||
{ | ||
'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> | ||
))} | ||
{users.length === 0 && ( | ||
<li className="italic p-2" data-testid="suggestions-fallback"> | ||
No matches. You can still write the username | ||
</li> | ||
)} | ||
</ul> | ||
</Popover> | ||
); | ||
} |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The list of suggested users also includes the current user. That feels a bit strange. I note that GitHub does include
@robertknight
in the list of suggestions as I type this comment. It is possible to see yourself in X and Bluesky mentions too. That surprised me.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
It shouldn't be super hard to filter out "self" later, if we decide that's the desired behavior.