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
6 changes: 6 additions & 0 deletions .changeset/fluffy-clowns-repair.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"@ultraviolet/form": minor
"@ultraviolet/ui": minor
---

`RichTextInput`: create component `RichTextInput` and `RichTextInputField`
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { Template } from './Template.stories'

export const Playground = Template.bind({})

Playground.args = Template.args
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Stack } from '@ultraviolet/ui'

import { RichTextInputField } from '..'
import { Submit } from '../../../components/Submit'

import { Template } from './Template.stories'

import type { StoryFn } from '@storybook/react-vite'
import type { ComponentProps } from 'react'

export const Required: StoryFn<
ComponentProps<typeof RichTextInputField>
> = args => (
<Stack gap={1}>
Comment thread
jsulpis marked this conversation as resolved.
<RichTextInputField {...args} />
<Submit>Submit</Submit>
</Stack>
)

Required.args = { ...Template.args, required: true }
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Stack } from '@ultraviolet/ui'

import { RichTextInputField } from '..'
import { Submit } from '../../../components'

import type { StoryFn } from '@storybook/react-vite'
import type { ComponentProps } from 'react'

export const Template: StoryFn<
ComponentProps<typeof RichTextInputField>
> = args => (
<Stack gap={1}>
<RichTextInputField {...args} />
<Submit>Submit</Submit>
</Stack>
)

Template.args = {
label: 'Label',
name: 'richTextInput',
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { Snippet, Stack, Text } from '@ultraviolet/ui'

import { RichTextInputField } from '..'
import { useForm } from '../../..'
import { Form } from '../../../components'
import { mockErrors } from '../../../mocks'

import type { Meta } from '@storybook/react-vite'

export default {
component: RichTextInputField,
decorators: [
ChildStory => {
const methods = useForm()
const {
errors,
isDirty,
isSubmitting,
touchedFields,
submitCount,
dirtyFields,
isValid,
isLoading,
isSubmitted,
isValidating,
isSubmitSuccessful,
} = methods.formState

return (
<Form errors={mockErrors} methods={methods} onSubmit={() => {}}>
<Stack gap={2}>
<ChildStory />
<Stack gap={1}>
<Text as="p" variant="bodyStrong">
Form input values:
</Text>
<Snippet initiallyExpanded prefix="lines">
{JSON.stringify(methods.watch(), null, 1)}
</Snippet>
</Stack>
<Stack gap={1}>
<Text as="p" variant="bodyStrong">
Form values:
</Text>
<Snippet prefix="lines">
{JSON.stringify(
{
errors,
isDirty,
isSubmitting,
touchedFields,
submitCount,
dirtyFields,
isValid,
isLoading,
isSubmitted,
isValidating,
isSubmitSuccessful,
},
null,
1,
)}
</Snippet>
</Stack>
</Stack>
</Form>
)
},
],
title: 'Form/Components/Compositions/RichTextInputField',
} as Meta

export { Playground } from './Playground.stories'
export { Required } from './Required.stories'

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { renderHook, screen, waitFor } from '@testing-library/react'
import { userEvent } from '@testing-library/user-event'
import { mockFormErrors, renderWithForm, renderWithTheme } from '@utils/test'
import { useForm } from 'react-hook-form'
import { describe, expect, test, vi } from 'vitest'

import { RichTextInputField } from '..'
import { Submit } from '../../../components'
import { Form } from '../../../components/Form'

describe('richTextInputField', () => {
test('should render correctly', () => {
const { asFragment } = renderWithForm(
<RichTextInputField label="Test" name="test" />,
)

expect(asFragment()).toMatchSnapshot()
})

test('should render correctly generated', async () => {
const onSubmit = vi.fn()
const { result } = renderHook(() =>
useForm<{ test: string }>({ defaultValues: { test: '' } }),
)

const { asFragment } = renderWithTheme(
<Form
errors={mockFormErrors}
methods={result.current}
onSubmit={onSubmit}
>
<RichTextInputField label="Test" name="test" required />
<Submit>Submit</Submit>
</Form>,
)

await userEvent.click(screen.getByRole('button', { name: 'Submit' }))
await waitFor(() => {
expect(onSubmit).toHaveBeenCalledTimes(0)
})

const doc = document.querySelector<HTMLDivElement>(
'[contenteditable="true"]',
)
if (!doc) {
throw new Error('RichTextInput contenteditable not found')
}
await userEvent.click(doc)
await userEvent.type(doc, 'This is an example')
await userEvent.click(screen.getByText('Submit'))
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

always use getByRole if possible. This is more precise, because you want to click on a button, not a text

Suggested change
await userEvent.click(screen.getByText('Submit'))
await userEvent.click(screen.getByRole('button', { name: 'Submit' }))


await waitFor(() => {
expect(onSubmit).toHaveBeenCalledOnce()
expect(onSubmit.mock.calls[0][0]).toEqual({
test: '<p>This is an example</p>',
})
})
expect(asFragment()).toMatchSnapshot()
})

test('should submit rich text with style and list', async () => {
const onSubmit = vi.fn()
const { result } = renderHook(() =>
useForm<{ test: string }>({ defaultValues: { test: '' } }),
)

renderWithTheme(
<Form
errors={mockFormErrors}
methods={result.current}
onSubmit={onSubmit}
>
<RichTextInputField label="Test" name="test" required />
<Submit>Submit</Submit>
</Form>,
)

const italicButton = screen.getByTitle('ItalicIcon').closest('button')
const bulletListButton = screen
.getByTitle('ListBulletIcon')
.closest('button')
Comment on lines +78 to +81
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
const italicButton = screen.getByTitle('ItalicIcon').closest('button')
const bulletListButton = screen
.getByTitle('ListBulletIcon')
.closest('button')
const italicButton = screen.getByRole('button', { name: "Italic" })
const bulletListButton = screen
.getByRole('button', { name: "Bullet List" })

expect(italicButton).not.toBeNull()
expect(bulletListButton).not.toBeNull()

const doc = document.querySelector<HTMLDivElement>(
'[contenteditable="true"]',
)
if (!doc) {
throw new Error('RichTextInput contenteditable not found')
}
await userEvent.click(doc)
await userEvent.click(italicButton!)
await userEvent.type(doc, 'Styled ')
await userEvent.click(bulletListButton!)
await userEvent.type(doc, 'item')
await userEvent.click(screen.getByText('Submit'))
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
await userEvent.click(screen.getByText('Submit'))
await userEvent.click(screen.getByRole('button', { name: "Submit" }))


await waitFor(() => {
expect(onSubmit).toHaveBeenCalledOnce()
expect(onSubmit.mock.calls[0][0]).toEqual({
test: '<ul><li><p><em>Styled item</em></p></li></ul>',
})
})
})
})
69 changes: 69 additions & 0 deletions packages/form/src/compositions/RichTextInputField/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
'use client'

import { RichTextInput } from '@ultraviolet/ui/compositions/RichTextInput'
import { useController } from 'react-hook-form'

import { useErrors } from '../../providers'

import type { BaseFieldProps } from '../../types'
import type { ComponentProps, FocusEvent } from 'react'
import type { FieldPath, FieldValues, Path, PathValue } from 'react-hook-form'

export type RichTextInputFieldProps<
TFieldValues extends FieldValues,
TFieldName extends FieldPath<TFieldValues>,
> = BaseFieldProps<TFieldValues, TFieldName> &
Omit<ComponentProps<typeof RichTextInput>, 'value' | 'onChange' | 'error'>

export const RichTextInputField = <
TFieldValues extends FieldValues,
TFieldName extends FieldPath<TFieldValues> = FieldPath<TFieldValues>,
>({
control,
errorLabel,
label,
onChange,
name,
onBlur,
required = false,
validate,
'aria-label': ariaLabel,
...props
}: RichTextInputFieldProps<TFieldValues, TFieldName>) => {
const { getError } = useErrors()

const {
field,
fieldState: { error },
} = useController<TFieldValues, TFieldName>({
control,
name,
rules: {
required,
validate,
},
})

return (
<RichTextInput
{...props}
error={getError(
{
label: errorLabel ?? label ?? ariaLabel ?? name,
value: field.value,
},
error,
)}
onBlur={(event: FocusEvent<HTMLElement>) => {
onBlur?.(event)
field.onBlur()
}}
onChange={value => {
field.onChange(value)
onChange?.(value as PathValue<TFieldValues, Path<TFieldValues>>)
}}
value={field.value}
{...(label ? { label } : { 'aria-label': ariaLabel! })}
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this logic should be in the RichTextEditor component, not the field

/>
)
}
1 change: 1 addition & 0 deletions packages/form/src/compositions/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export { CustomerSatisfactionField } from './CustomerSatisfactionField'
export { OfferListField } from './OfferListField'
export { OptionSelectorField } from './OptionSelectorField'
export { PlansField } from './PlansField'
export { RichTextInputField } from './RichTextInputField'
8 changes: 8 additions & 0 deletions packages/ui/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@
"watch:build": "vite build --config vite.config.ts --watch"
},
"dependencies": {
"@handlewithcare/react-prosemirror": "3.0.0",
"@nivo/bar": "0.89.1",
"@nivo/core": "0.89.1",
"@nivo/line": "0.89.1",
Expand All @@ -94,6 +95,13 @@
"codemirror": "6.0.2",
"csstype": "3.2.3",
"deepmerge": "4.3.1",
"prosemirror-commands": "1.5.0",
"prosemirror-keymap": "1.2.1",
"prosemirror-model": "1.25.1",
"prosemirror-schema-basic": "1.2.2",
"prosemirror-schema-list": "1.2.2",
"prosemirror-state": "1.4.3",
"prosemirror-view": "1.41.4",
"react-intersection-observer": "10.0.3",
"react-toastify": "11.0.5"
},
Expand Down
41 changes: 41 additions & 0 deletions packages/ui/src/compositions/RichTextInput/Notice.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
'use client'

import { Row } from '../../components/Row'
import { Text } from '../../components/Text'

import type { ReactNode } from 'react'

export const Notice = ({
error,
success,
helper,
disabled,
sentiment,
id,
}: {
error?: string | boolean
success?: string | boolean
helper?: ReactNode
disabled?: boolean
sentiment?: 'danger' | 'success' | 'neutral'
id?: string
}) => (
<div aria-describedby={id} role="status">
<Row gap="1" templateColumns="minmax(0, 1fr) min-content">
{error || success || typeof helper === 'string' ? (
<Text
as="p"
disabled={disabled}
prominence={error || success ? 'default' : 'weak'}
sentiment={sentiment}
variant="caption"
>
{error || success || helper}
</Text>
) : null}
{!(error || success) && typeof helper !== 'string' && helper
? helper
: null}
</Row>
</div>
)
Loading
Loading