Skip to content
Open
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
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {Text} from '@sentry/scraps/text';

import {t} from 'sentry/locale';
import type {NoteType} from 'sentry/types/alerts';
import {serializeMentions} from 'sentry/utils/mentions/serializeMentions';
import {useOrgMentionPlugins} from 'sentry/utils/mentions/useOrgMentionPlugins';

interface CreateComposerProps {
Expand All @@ -37,20 +38,6 @@ type MentionComposerProps =

type EditorMode = 'write' | 'preview';

function serializeNoteMentions(value: ComposerValue): string {
let text = value.text;

for (const mention of value.mentions.toSorted((a, b) => b.start - a.start)) {
if (value.text.slice(mention.start, mention.end) !== mention.text) {
continue;
}

text = text.slice(0, mention.start) + `**${mention.text}**` + text.slice(mention.end);
}

return text;
}

export function MentionComposer(props: MentionComposerProps) {
const {
initialValue = '',
Expand All @@ -70,16 +57,7 @@ export function MentionComposer(props: MentionComposerProps) {
...defaultFormOptions,
defaultValues: {value: initialEditorValue},
onSubmit: async ({value}) => {
const editorValue = value.value;
const validMentionIds = editorValue.mentions.flatMap(mention =>
editorValue.text.slice(mention.start, mention.end) === mention.text
? mention.id
: []
);
const uniqueMentionIds = [...new Set(validMentionIds)];
const data = {text: serializeNoteMentions(editorValue), mentions: uniqueMentionIds};

await onSubmit(data);
await onSubmit(serializeMentions(value.value));

if (props.mode === 'create') {
form.reset(
Expand Down Expand Up @@ -144,7 +122,7 @@ export function MentionComposer(props: MentionComposerProps) {
minHeight={`${minHeight}px`}
overflow="auto"
>
<Markdown raw={serializeNoteMentions(field.state.value)} />
<Markdown raw={serializeMentions(field.state.value).text} />
</Container>
)
}
Expand Down
31 changes: 31 additions & 0 deletions static/app/components/core/composer/composer.spec.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,37 @@ describe('Composer', () => {
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
});

it('filters a large suggestion list and selects a matching mention', async () => {
const height = jest
.spyOn(HTMLElement.prototype, 'offsetHeight', 'get')
.mockReturnValue(200);
const suggestions = Array.from({length: 50}, (_, index) => ({
id: `user:${index}`,
label: `Person${index}`,
}));
const source: TestComposerSource = {
...MEMBER_SOURCE,
getSuggestions: query =>
suggestions.filter(suggestion => suggestion.label.includes(query)),
};

render(<ControlledComposer sources={[source]} />);
const textbox = getEditor();
await userEvent.type(textbox, '@');
expect(await screen.findByRole('option', {name: 'Person0'})).toBeVisible();
expect(screen.queryByRole('option', {name: 'Person49'})).not.toBeInTheDocument();

await userEvent.keyboard('Person49');
await screen.findByRole('option', {name: 'Person49'});
await userEvent.keyboard('{Enter}');

expect(screen.getByRole('status', {name: 'Editor value'})).toHaveTextContent(
'@Person49 |user:49'
);
expect(screen.queryByRole('listbox')).not.toBeInTheDocument();
height.mockRestore();
});

it('selects the current suggestion with Tab', async () => {
render(<ControlledComposer />);

Expand Down
1 change: 1 addition & 0 deletions static/app/components/core/composer/composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,7 @@ export function Composer({
selectionMode="none"
shouldUseVirtualFocus
size="sm"
virtualized={suggestionCount > 10}
/>
) : (
<Container minWidth="220px" maxWidth="360px">
Expand Down
14 changes: 14 additions & 0 deletions static/app/utils/mentions/serializeMentions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type {ComposerValue} from '@sentry/scraps/composer';

export function serializeMentions(value: ComposerValue) {
const mentions = value.mentions.filter(
mention => value.text.slice(mention.start, mention.end) === mention.text
);
let text = value.text;

for (const mention of mentions.toSorted((a, b) => b.start - a.start)) {
text = text.slice(0, mention.start) + `**${mention.text}**` + text.slice(mention.end);
}

return {text, mentions: [...new Set(mentions.map(mention => mention.id))]};
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
import {MemberFixture} from 'sentry-fixture/member';
import {OrganizationFixture} from 'sentry-fixture/organization';
import {TeamFixture} from 'sentry-fixture/team';
import {UserFixture} from 'sentry-fixture/user';

import {
render,
Expand All @@ -9,6 +12,7 @@ import {
within,
} from 'sentry-test/reactTestingLibrary';

import {TeamStore} from 'sentry/stores/teamStore';
import InvestigationDetailView from 'sentry/views/investigations/detail';
import {
InvestigationCommentFixture,
Expand Down Expand Up @@ -380,23 +384,38 @@ describe('InvestigationActivity', () => {
).toBeInTheDocument();
});

it('posts a comment with Enter', async () => {
it('posts user and team mentions with Enter', async () => {
TeamStore.loadInitialData([TeamFixture({id: '2', slug: 'frontend'})]);
MockApiClient.addMockResponse({
url: '/organizations/org-slug/members/',
body: [MemberFixture({user: UserFixture({id: '1', name: 'Alice Example'})})],
});
MockApiClient.addMockResponse({url: commentsUrl, body: []});
const request = MockApiClient.addMockResponse({
url: commentsUrl,
method: 'POST',
body: InvestigationCommentFixture({body: 'Looks like the deploy'}),
body: InvestigationCommentFixture(),
});
renderPage();

const input = await findEditor('Add a comment');
await userEvent.type(input, ' Looks like the deploy {Enter}');
await userEvent.type(input, ' Thanks @ali');
await userEvent.click(await screen.findByRole('option', {name: /Alice Example/}));
await userEvent.type(input, 'and #front');
await userEvent.keyboard('{Enter}');
expect(request).not.toHaveBeenCalled();
await userEvent.keyboard('{Enter}');

await waitFor(() => expect(input).toHaveTextContent(/^$/));
expect(request).toHaveBeenCalledWith(
commentsUrl,
expect.objectContaining({data: {body: 'Looks like the deploy'}})
expect.objectContaining({
data: {
body: 'Thanks **@Alice Example** and **#frontend**',
mentions: ['user:1', 'team:2'],
},
})
);
await waitFor(() => expect(input).toHaveTextContent(/^$/));
});

it('hides the composer and comment actions on an archived investigation', async () => {
Expand Down
9 changes: 6 additions & 3 deletions static/app/views/investigations/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,10 @@ export function investigationCommentsQueryOptions({
export function useCreateInvestigationCommentMutation(
organizationSlug: string,
investigationId: string,
options?: MutationOptions<InvestigationComment, {body: string; blockId?: string}>
options?: MutationOptions<
InvestigationComment,
{body: string; blockId?: string; mentions?: string[]}
>
) {
const invalidateComments = useInvalidateInvestigationComments(
organizationSlug,
Expand All @@ -108,14 +111,14 @@ export function useCreateInvestigationCommentMutation(

return useMutation({
...options,
mutationFn: ({body, blockId}) =>
mutationFn: ({body, blockId, mentions}) =>
fetchMutation<InvestigationComment>({
url: getApiUrl(
'/organizations/$organizationIdOrSlug/notebooks/$notebookId/comments/',
{path: {organizationIdOrSlug: organizationSlug, notebookId: investigationId}}
),
method: 'POST',
data: blockId === undefined ? {body} : {body, blockId},
data: {body, blockId, mentions},
}),
onSuccess: async (comment, variables, onMutateResult, context) => {
await invalidateComments();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import {Fragment, useEffect} from 'react';
import {MemberFixture} from 'sentry-fixture/member';
import {OrganizationFixture} from 'sentry-fixture/organization';
import {UserFixture} from 'sentry-fixture/user';

import {
act,
Expand Down Expand Up @@ -126,26 +128,75 @@ describe('BlockCommentsDrawer', () => {

expect(request).toHaveBeenCalledWith(
commentsUrl,
expect.objectContaining({data: {body: 'Check this', blockId: 'block-1'}})
expect.objectContaining({
data: {body: 'Check this', blockId: 'block-1', mentions: []},
})
);
});

it('keeps an unsent reply for the block', async () => {
it('restores mentions in a block draft and clears the draft after posting', async () => {
mockBlockComments([]);
MockApiClient.addMockResponse({
url: '/organizations/org-slug/members/',
body: [MemberFixture({user: UserFixture({id: '1', name: 'Alice Example'})})],
});
const request = MockApiClient.addMockResponse({
url: commentsUrl,
method: 'POST',
body: InvestigationCommentFixture({blockId: 'block-1'}),
});
const {unmount} = renderPage({comments: 'open', commentsBlock: 'block-1'});

const drawer = await screen.findByRole('complementary', {name: 'Block comments'});
const editor = await within(drawer).findByRole('combobox', {name: 'Add a comment'});
// user-event does not yet recognize contenteditable="plaintext-only".
editor.setAttribute('contenteditable', 'true');
await userEvent.type(editor, 'Half a thought');
await userEvent.type(editor, 'Check @ali');
await userEvent.click(await screen.findByRole('option', {name: /Alice Example/}));
unmount();

renderPage({comments: 'open', commentsBlock: 'block-1'});
const reopenedPage = renderPage({comments: 'open', commentsBlock: 'block-1'});
const reopened = await screen.findByRole('complementary', {name: 'Block comments'});
const restoredEditor = await within(reopened).findByRole('combobox', {
name: 'Add a comment',
});
expect(restoredEditor).toHaveTextContent('Check @Alice Example');
await userEvent.click(within(reopened).getByRole('button', {name: 'Comment'}));

await waitFor(() => expect(restoredEditor).toHaveTextContent(/^$/));
expect(request).toHaveBeenCalledWith(
commentsUrl,
expect.objectContaining({
data: {
body: 'Check **@Alice Example**',
blockId: 'block-1',
mentions: ['user:1'],
},
})
);
reopenedPage.unmount();

renderPage({comments: 'open', commentsBlock: 'block-1'});
const cleared = await screen.findByRole('complementary', {name: 'Block comments'});
expect(
await within(cleared).findByRole('combobox', {name: 'Add a comment'})
).toHaveTextContent(/^$/);
});

it('restores drafts saved before mention support', async () => {
mockBlockComments([]);
localStorage.setItem(
'investigation-comment-drafts',
JSON.stringify({
'investigation-1:block-1': {text: 'Old draft', savedAt: Date.now()},
})
);
renderPage({comments: 'open', commentsBlock: 'block-1'});

const drawer = await screen.findByRole('complementary', {name: 'Block comments'});
expect(
await within(reopened).findByRole('combobox', {name: 'Add a comment'})
).toHaveTextContent('Half a thought');
await within(drawer).findByRole('combobox', {name: 'Add a comment'})
).toHaveTextContent('Old draft');
});

it('highlights the comment in the URL', async () => {
Expand Down
33 changes: 23 additions & 10 deletions static/app/views/investigations/comments/commentComposer.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import {useEffect, useRef, useState} from 'react';
import isEqual from 'lodash/isEqual';

import {Button} from '@sentry/scraps/button';
import {Composer, type ComposerValue} from '@sentry/scraps/composer';
import {Flex, Stack} from '@sentry/scraps/layout';
import {toast} from '@sentry/scraps/toast';

import {t} from 'sentry/locale';
import {serializeMentions} from 'sentry/utils/mentions/serializeMentions';
import {useOrgMentionPlugins} from 'sentry/utils/mentions/useOrgMentionPlugins';
import {useOrganization} from 'sentry/utils/useOrganization';
import {
useCreateInvestigationCommentMutation,
Expand All @@ -21,6 +24,11 @@ function isSubmitKey(event: React.KeyboardEvent) {
return event.key === 'Enter' && !event.shiftKey && !event.altKey;
}

function serializeComment(value: ComposerValue) {
const {text, mentions} = serializeMentions(value);
return {body: text.trim(), mentions};
}

export function CommentComposer({
investigationId,
blockId,
Expand All @@ -33,19 +41,24 @@ export function CommentComposer({
inputRef?: React.Ref<HTMLDivElement>;
}) {
const organization = useOrganization();
const plugins = useOrgMentionPlugins({team: {trigger: '#'}});
const [value, setValue] = useState<ComposerValue>(() =>
blockId
? {text: loadCommentDraft(investigationId, blockId), mentions: []}
: EMPTY_VALUE
blockId ? loadCommentDraft(investigationId, blockId) : EMPTY_VALUE
);
const {mutate, isPending} = useCreateInvestigationCommentMutation(
organization.slug,
investigationId,
{
onSuccess: (_comment, {body: submitted}) => {
setValue(current => (current.text.trim() === submitted ? EMPTY_VALUE : current));
if (blockId && loadCommentDraft(investigationId, blockId).trim() === submitted) {
saveCommentDraft(investigationId, blockId, '');
onSuccess: (_comment, {body, mentions}) => {
const submitted = {body, mentions: mentions ?? []};
setValue(current =>
isEqual(serializeComment(current), submitted) ? EMPTY_VALUE : current
);
if (
blockId &&
isEqual(serializeComment(loadCommentDraft(investigationId, blockId)), submitted)
) {
saveCommentDraft(investigationId, blockId, EMPTY_VALUE);
}
},
onError: () => toast.error(t('Unable to post comment.')),
Expand All @@ -57,7 +70,7 @@ export function CommentComposer({
if (!body || isPending) {
return;
}
mutate({body, blockId});
mutate({...serializeComment(value), blockId});
};

return (
Expand All @@ -70,10 +83,10 @@ export function CommentComposer({
onChange={next => {
setValue(next);
if (blockId) {
saveCommentDraft(investigationId, blockId, next.text);
saveCommentDraft(investigationId, blockId, next);
}
}}
plugins={[]}
plugins={plugins}
minHeight={56}
onKeyDown={event => {
if (isSubmitKey(event)) {
Expand Down
Loading
Loading