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
80 changes: 78 additions & 2 deletions static/app/components/activity/note/body.tsx
Original file line number Diff line number Diff line change
@@ -1,15 +1,91 @@
import {Markdown} from '@sentry/scraps/markdown';
import {Fragment, isValidElement} from 'react';
import styled from '@emotion/styled';

import {ExternalLink} from '@sentry/scraps/link';
import {Markdown, type MarkdownProps} from '@sentry/scraps/markdown';

import {resolveHostname} from 'sentry/utils/api/resolveHostname';

import {
COMMENT_ATTACHMENT_URL_PATTERN,
isCommentAttachmentVideo,
} from './commentAttachmentButton';

type Props = {
text: string;
};

type MarkdownComponents = NonNullable<MarkdownProps['components']>;
type NoteLinkProps = React.ComponentProps<NonNullable<MarkdownComponents['Link']>>;

/**
* Plain text of a link's label, which names the uploaded file. Markdown hands
* the label over as one Token element per inline token (text, escape, ...).
*/
function textOf(node: React.ReactNode): string {
if (typeof node === 'string' || typeof node === 'number') {
return String(node);
}
if (Array.isArray(node)) {
return node.map(textOf).join('');
}
if (isValidElement<{children?: React.ReactNode; token?: {text?: string}}>(node)) {
const {token, children} = node.props;
return typeof token?.text === 'string' ? token.text : textOf(children);
}
return '';
}

/**
* Links to videos uploaded to the comment play inline, with the link kept
* below the player so the file can still be opened directly. Other uploaded
* files are a link that downloads them.
*
* Both go to the region's host like other API requests: the browser loads
* them itself, so they skip the API client, and the default link would treat
* the `/api/0/` path as an in-app route.
*/
function NoteLink({Default, href, title, children}: NoteLinkProps) {
if (!COMMENT_ATTACHMENT_URL_PATTERN.test(href)) {
return (
<Default href={href} title={title}>
{children}
</Default>
);
}
const fileUrl = resolveHostname(href);
const link = (
<ExternalLink href={fileUrl} title={title ?? undefined}>
{children}
</ExternalLink>
);
if (!isCommentAttachmentVideo(textOf(children))) {
return link;
}
return (
<Fragment>
<Video controls preload="metadata" src={fileUrl} data-test-id="note-video" />
{link}
</Fragment>
);
}

const components: MarkdownComponents = {Link: NoteLink};

function NoteBody({text}: Props) {
return (
<div data-test-id="activity-note-body">
<Markdown raw={text} />
<Markdown raw={text} components={components} />
</div>
);
}

const Video = styled('video')`
display: block;
max-width: 100%;
max-height: 480px;
border-radius: ${p => p.theme.radius.md};
margin-bottom: ${p => p.theme.space.xs};
`;

export {NoteBody};
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {COMMENT_ATTACHMENT_UPLOAD_HEADERS} from './commentAttachmentButton';

describe('comment attachment upload client', () => {
const {Client} = jest.requireActual('sentry/api');
let fetchSpy: jest.SpyInstance;

beforeEach(() => {
fetchSpy = jest.spyOn(window, 'fetch').mockResolvedValue(
new Response('{"id": "5"}', {
status: 201,
headers: {'Content-Type': 'application/json'},
})
);
});

afterEach(() => {
fetchSpy.mockRestore();
});

function videoForm() {
const data = new FormData();
data.set('file', new File(['data'], 'video_1.mp4', {type: 'video/mp4'}));
return data;
}

it('lets the browser set the multipart Content-Type', async () => {
const client = new Client({headers: COMMENT_ATTACHMENT_UPLOAD_HEADERS});

await client.requestPromise('/organizations/org-slug/issues/1/comment-attachments/', {
method: 'POST',
data: videoForm(),
});

const [, init] = fetchSpy.mock.calls[0];
expect(init.body).toBeInstanceOf(FormData);
expect(new Headers(init.headers).get('Content-Type')).toBeNull();
});

it('the default client would label the upload as JSON', async () => {
const client = new Client();

await client.requestPromise('/organizations/org-slug/issues/1/comment-attachments/', {
method: 'POST',
data: videoForm(),
});

const [, init] = fetchSpy.mock.calls[0];
expect(new Headers(init.headers).get('Content-Type')).toBe('application/json');
});
});
138 changes: 138 additions & 0 deletions static/app/components/activity/note/commentAttachmentButton.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import {Fragment, useMemo, useRef, useState} from 'react';
import {IconUpload} from '@sentry/icons/upload';

import {Button} from '@sentry/scraps/button';
import {toast} from '@sentry/scraps/toast';

import {Client} from 'sentry/api';
import {t} from 'sentry/locale';
import {RequestError} from 'sentry/utils/requestError/requestError';
import {useApi} from 'sentry/utils/useApi';
import {useOrganization} from 'sentry/utils/useOrganization';

/**
* Headers for the upload client. The default client sends a JSON Content-Type
* on every request, which would make the server parse the multipart body as
* JSON; without it the browser sets multipart/form-data and its boundary, as
* the relocation upload does.
*/
export const COMMENT_ATTACHMENT_UPLOAD_HEADERS = {
Accept: 'application/json; charset=utf-8',
};

/**
* Matches the URL the comment attachment endpoint returns, so notes can render
* video links among them as an inline player. Segments are limited to slugs and IDs
* so a hand-written link with `..` never becomes a player for another route.
*/
export const COMMENT_ATTACHMENT_URL_PATTERN =
/^\/api\/0\/organizations\/[\w-]+\/issues\/[\w-]+\/comment-attachments\/\d+\/$/;

/**
* File names the server plays inline (its INLINE_CONTENT_TYPES). Other
* attachments are served as downloads, so they get a link without a player.
*/
const VIDEO_FILE_NAME_PATTERN = /\.(mp4|m4v|mov|webm|ogg|ogv)$/i;

export function isCommentAttachmentVideo(name: string): boolean {
return VIDEO_FILE_NAME_PATTERN.test(name.trim());
}

export interface CommentAttachment {
contentType: string;
id: string;
name: string;
size: number;
url: string;
}

/**
* Markdown link to an uploaded attachment, with the characters that would end
* the link text escaped.
*/
export function commentAttachmentMarkdown(attachment: CommentAttachment): string {
const label = attachment.name.replace(/([\\[\]])/g, '\\$1');
return `[${label}](${attachment.url})`;
}

function uploadErrorMessage(error: unknown): string {
const detail =
error instanceof RequestError && typeof error.responseJSON?.detail === 'string'
? error.responseJSON.detail
: null;
if (detail) {
return detail;
}
if (error instanceof RequestError && error.status === 413) {
return t('This file is too large to upload.');
}
return t('Unable to upload file');
}

interface CommentAttachmentButtonProps {
issueId: string;
onUploaded: (attachment: CommentAttachment) => void;
}

export function CommentAttachmentButton({
issueId,
onUploaded,
}: CommentAttachmentButtonProps) {
const organization = useOrganization();
const uploadClient = useMemo(
() => new Client({headers: COMMENT_ATTACHMENT_UPLOAD_HEADERS}),
[]
);
const api = useApi({api: uploadClient});
const fileInputRef = useRef<HTMLInputElement>(null);
const [isUploading, setIsUploading] = useState(false);

if (!organization.features.includes('issue-comment-attachments')) {
return null;
}

async function handleSelectFile(event: React.ChangeEvent<HTMLInputElement>) {
const file = event.target.files?.[0];
// Reset so selecting the same file again still fires a change.
event.target.value = '';
if (!file) {
return;
}

const data = new FormData();
data.set('file', file);
setIsUploading(true);
try {
const attachment: CommentAttachment = await api.requestPromise(
`/organizations/${organization.slug}/issues/${issueId}/comment-attachments/`,
{method: 'POST', data}
);
setIsUploading(false);
onUploaded(attachment);
} catch (error) {
setIsUploading(false);
toast.error(uploadErrorMessage(error));
}
}

return (
<Fragment>
<input
ref={fileInputRef}
type="file"
aria-label={t('Attachment file')}
style={{display: 'none'}}
onChange={handleSelectFile}
/>
<Button
size="xs"
icon={<IconUpload />}
busy={isUploading}
disabled={isUploading}
aria-label={t('Attach file')}
tooltipProps={{title: t('Attach file')}}
onClick={() => fileInputRef.current?.click()}
/>
</Fragment>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,21 @@ import {Markdown} from '@sentry/scraps/markdown';
import {SegmentedControl} from '@sentry/scraps/segmentedControl';
import {Text} from '@sentry/scraps/text';

import {
CommentAttachmentButton,
commentAttachmentMarkdown,
} from 'sentry/components/activity/note/commentAttachmentButton';
import {t} from 'sentry/locale';
import type {NoteType} from 'sentry/types/alerts';
import {useOrgMentionPlugins} from 'sentry/utils/mentions/useOrgMentionPlugins';

interface CreateComposerProps {
onSubmit: (data: NoteType) => Promise<void>;
/**
* Issue that files are uploaded to. Without it the composer has no attach
* button.
*/
attachmentIssueId?: string;
initialValue?: string;
minHeight?: number;
onValueChange?: (value: string) => void;
Expand Down Expand Up @@ -169,6 +178,19 @@ export function MentionComposer(props: MentionComposerProps) {
/>
)}
<Flex align="center" gap="sm">
{props.mode === 'create' && props.attachmentIssueId && (
<CommentAttachmentButton
issueId={props.attachmentIssueId}
onUploaded={attachment => {
const {text, mentions} = form.getFieldValue('value');
const link = commentAttachmentMarkdown(attachment);
const nextText =
text.trim() === '' ? link : `${text.trimEnd()}\n${link}`;
form.setFieldValue('value', {text: nextText, mentions});
props.onValueChange?.(nextText);
}}
/>
)}
{props.mode === 'edit' && (
<form.Subscribe selector={state => state.isSubmitting}>
{isSubmitting => (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ interface ActivityNoteInputProps {
itemKey: string;
onSubmit: (data: NoteType) => Promise<void>;
storageKey: string;
attachmentIssueId?: string;
minHeight?: number;
placeholder?: string;
variant?: 'compact' | 'full';
Expand Down Expand Up @@ -39,6 +40,7 @@ function saveToStorage(storageKey: string, drafts: DraftStorage) {
}

export function ActivityNoteInput({
attachmentIssueId,
itemKey,
storageKey,
variant,
Expand Down Expand Up @@ -74,6 +76,7 @@ export function ActivityNoteInput({
return (
<ActivityInputFrame>
<MentionComposer
attachmentIssueId={attachmentIssueId}
initialValue={value}
minHeight={minHeight}
mode="create"
Expand Down
Loading
Loading