Skip to content
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
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type {
CSSProperties,
ForwardedRef,
FormEventHandler,
FormHTMLAttributes,
MutableRefObject,
ReactElement,
} from 'react';
import React, { forwardRef, useRef } from 'react';
Expand All @@ -25,6 +25,7 @@ export interface CommentClassName {

export interface CommentMarkdownInputProps {
post: Post;
inputId?: string;
editCommentId?: string;
parentCommentId?: string;
initialContent?: string;
Expand All @@ -38,6 +39,7 @@ export interface CommentMarkdownInputProps {
) => void;
showSubmit?: boolean;
showUserAvatar?: boolean;
autoFocus?: boolean;
onChange?: (value: string) => void;
formProps?: FormHTMLAttributes<HTMLFormElement>;
onClose?: () => void;
Expand All @@ -46,6 +48,7 @@ export interface CommentMarkdownInputProps {
export function CommentMarkdownInputComponent(
{
post,
inputId,
initialContent,
replyTo,
editCommentId,
Expand All @@ -55,18 +58,23 @@ export function CommentMarkdownInputComponent(
onChange,
showSubmit = true,
showUserAvatar = true,
autoFocus = true,
formProps = {},
onClose,
}: CommentMarkdownInputProps,
ref: MutableRefObject<HTMLFormElement>,
ref: ForwardedRef<HTMLFormElement>,
): ReactElement {
const shouldFocus = useRef(true);
const shouldFocus = useRef(autoFocus);
const postId = post?.id;
const sourceId = post?.source?.id;
const {
mutateComment: { mutateComment, isLoading, isSuccess },
} = useWriteCommentContext();
const richTextRef = useRef<RichTextInputRef | null>(null);
let submitCopy: string | undefined;
if (showSubmit) {
submitCopy = editCommentId ? 'Update' : 'Comment';
}

const onSubmitForm: FormEventHandler<HTMLFormElement> = async (e) => {
e.preventDefault();
Expand Down Expand Up @@ -114,6 +122,7 @@ export function CommentMarkdownInputComponent(
ref={ref}
>
<RichTextInput
inputId={inputId}
ref={(richTextRefInstance) => {
if (richTextRefInstance) {
richTextRef.current = richTextRefInstance;
Expand Down Expand Up @@ -143,7 +152,7 @@ export function CommentMarkdownInputComponent(
}}
onSubmit={onKeyboardSubmit}
enabledCommand={{ ...defaultMarkdownCommands, upload: true }}
submitCopy={showSubmit && (editCommentId ? 'Update' : 'Comment')}
submitCopy={submitCopy}
timeline={
replyTo ? (
<span className="py-1.5 pl-12 text-text-tertiary typo-caption1">
Expand Down
150 changes: 150 additions & 0 deletions packages/shared/src/components/fields/RichTextInput.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
import { render } from '@testing-library/react';
import React from 'react';
import RichTextInput from './RichTextInput';

const mockFocus = jest.fn();
const mockUseEditor = jest.fn();
const mockEditor = {
commands: {
focus: mockFocus,
setContent: jest.fn(),
},
};

jest.mock('next/dynamic', () => () => () => null);

jest.mock('@tiptap/core', () => ({
Extension: { create: jest.fn((config) => config) },
markInputRule: jest.fn(),
nodeInputRule: jest.fn(),
}));

jest.mock('@tiptap/starter-kit', () => ({
__esModule: true,
default: { configure: jest.fn(() => ({})) },
}));

jest.mock('@tiptap/extension-link', () => ({
__esModule: true,
default: { configure: jest.fn(() => ({})) },
}));

jest.mock('@tiptap/extension-placeholder', () => ({
__esModule: true,
default: { configure: jest.fn(() => ({})) },
}));

jest.mock('@tiptap/extension-character-count', () => ({
__esModule: true,
default: { configure: jest.fn(() => ({})) },
}));

jest.mock('@tiptap/extension-image', () => ({
__esModule: true,
default: {},
}));

jest.mock('@tiptap/react', () => ({
__esModule: true,
useEditor: (options: unknown) => {
mockUseEditor(options);
return mockEditor;
},
EditorContent: () => {
const react = jest.requireActual('react') as typeof React;
return react.createElement('div', { 'data-testid': 'editor-content' });
},
}));

jest.mock('../../contexts/AuthContext', () => ({
useAuthContext: () => ({ user: null }),
}));

jest.mock('../../hooks/usePopupSelector', () => ({
__esModule: true,
usePopupSelector: () => ({ parentSelector: undefined }),
}));

jest.mock('../../hooks/useToastNotification', () => ({
useToastNotification: () => ({ displayToast: jest.fn() }),
}));

jest.mock('./RichTextEditor/useDraftStorage', () => ({
useDraftStorage: () => ({
getInitialValue: (initialContent = '') => initialContent,
clearDraft: jest.fn(),
}),
}));

jest.mock('./RichTextEditor/useImageUpload', () => ({
useImageUpload: () => ({
queueCount: 0,
uploadRef: { current: null },
insertImage: jest.fn(),
handleDrop: jest.fn(),
handlePaste: jest.fn(),
onUpload: jest.fn(),
}),
}));

jest.mock('./RichTextEditor/useMentionAutocomplete', () => ({
useMentionAutocomplete: () => ({
queryRef: { current: undefined },
mentionsRef: { current: [] },
selectedRef: { current: 0 },
mentions: [],
selected: 0,
query: undefined,
updateFromEditor: jest.fn(),
clearMention: jest.fn(),
applyMention: jest.fn(),
}),
}));

jest.mock('./RichTextEditor/useEmojiAutocomplete', () => ({
useEmojiAutocomplete: () => ({
emojiQueryRef: { current: undefined },
emojiDataRef: { current: [] },
selectedEmojiRef: { current: 0 },
emojiQuery: undefined,
emojiData: [],
selectedEmoji: 0,
updateFromEditor: jest.fn(),
clearEmoji: jest.fn(),
applyEmoji: jest.fn(),
setSelectedEmoji: jest.fn(),
}),
}));

describe('RichTextInput', () => {
beforeEach(() => {
mockUseEditor.mockClear();
});

it('exposes the input id on the rich editor DOM attributes', () => {
render(<RichTextInput inputId="comment-editor" hideFooter hideToolbar />);

expect(mockUseEditor).toHaveBeenCalledWith(
expect.objectContaining({
editorProps: expect.objectContaining({
attributes: expect.objectContaining({ id: 'comment-editor' }),
}),
}),
);
});

it('exposes the rich editor as a multiline textbox', () => {
render(<RichTextInput hideFooter hideToolbar />);

expect(mockUseEditor).toHaveBeenCalledWith(
expect.objectContaining({
editorProps: expect.objectContaining({
attributes: expect.objectContaining({
role: 'textbox',
'aria-multiline': 'true',
}),
}),
}),
);
});
});
10 changes: 9 additions & 1 deletion packages/shared/src/components/fields/RichTextInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ interface ClassName {

interface RichTextInputProps {
className?: ClassName;
inputId?: string;
footer?: ReactNode;
textareaProps?: Omit<
TextareaHTMLAttributes<HTMLTextAreaElement>,
Expand Down Expand Up @@ -169,6 +170,7 @@ export interface RichTextInputRef {
function RichTextInput(
{
className = {},
inputId,
footer,
textareaProps = {},
submitCopy,
Expand Down Expand Up @@ -365,6 +367,11 @@ function RichTextInput(
updateSuggestionsFromEditor(updatedEditor);
},
editorProps: {
attributes: {
...(inputId ? { id: inputId } : {}),
role: 'textbox',
'aria-multiline': 'true',
},
handlePaste: (_view, event) => {
const hasFiles = (event.clipboardData?.files?.length ?? 0) > 0;
if (hasFiles) {
Expand Down Expand Up @@ -671,7 +678,7 @@ function RichTextInput(
return;
}

editor?.commands.focus();
editor?.commands.focus('end');
},
toggleMarkdownMode,
}));
Expand Down Expand Up @@ -863,6 +870,7 @@ function RichTextInput(
>
<textarea
{...textareaProps}
id={inputId}
name={undefined}
ref={markdownTextareaRef}
value={input}
Expand Down
91 changes: 91 additions & 0 deletions packages/shared/src/components/post/NewComment.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import React from 'react';
import { NewComment } from './NewComment';

const mockShowLogin = jest.fn();
const mockLogEvent = jest.fn();
const mockUser = {
id: 'user-1',
name: 'User',
username: 'user',
image: '',
permalink: '#',
};

jest.mock('../../contexts/AuthContext', () => ({
useAuthContext: () => ({
user: mockUser,
showLogin: mockShowLogin,
}),
}));

jest.mock('../../contexts/LogContext', () => ({
useLogContext: () => ({ logEvent: mockLogEvent }),
}));

jest.mock('../../contexts', () => ({
useActiveFeedContext: () => ({ logOpts: undefined }),
}));

jest.mock('../../lib/feed', () => ({
postLogEvent: jest.fn(() => ({ event_name: 'open comment' })),
}));

jest.mock('../ProfilePicture', () => ({
ProfileImageSize: {
Large: 'large',
Medium: 'medium',
},
ProfilePicture: () => <span />,
getProfilePictureClasses: () => '',
}));

jest.mock('../image/Image', () => ({
Image: () => null,
}));

const CommentInputOrModal = ({
inputId,
}: {
inputId: string;
}): React.ReactElement => (
<div data-testid="comment-input" id={inputId} tabIndex={-1} />
);

describe('NewComment', () => {
const originalRequestAnimationFrame = window.requestAnimationFrame;
const originalCancelAnimationFrame = window.cancelAnimationFrame;

beforeEach(() => {
jest.clearAllMocks();
window.requestAnimationFrame = ((callback: FrameRequestCallback) =>
window.setTimeout(
() => callback(0),
0,
)) as typeof window.requestAnimationFrame;
window.cancelAnimationFrame = ((id: number) =>
window.clearTimeout(id)) as typeof window.cancelAnimationFrame;
});

afterEach(() => {
window.requestAnimationFrame = originalRequestAnimationFrame;
window.cancelAnimationFrame = originalCancelAnimationFrame;
});

it('focuses the composer input from the comment click handler', async () => {
render(
<NewComment
post={{ id: 'post-1' } as never}
CommentInputOrModal={CommentInputOrModal}
/>,
);

fireEvent.click(
screen.getByRole('button', { name: /share your thoughts/i }),
);

await waitFor(() => {
expect(screen.getByTestId('comment-input')).toHaveFocus();
});
});
});
Loading
Loading