Skip to content

Commit

Permalink
feat(many): add new form field error msg style + add asterisk for req…
Browse files Browse the repository at this point in the history
…uired fields
  • Loading branch information
balzss committed Nov 6, 2024
1 parent e250b02 commit 9b03683
Show file tree
Hide file tree
Showing 44 changed files with 615 additions and 47 deletions.
136 changes: 136 additions & 0 deletions docs/guides/form-errors.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
---
title: Form Errors
category: Guides
order: 7
---

# Adding Error Messages to Form Components

InstUI offers a range of form elements and all of them have a similar API to handle error/hint/success messages. These components use the `messages` prop with the following type definition:

```ts
---
type: code
---
type FormMessages = {
type:
| 'newError'
| 'error'
| 'hint'
| 'success'
| 'screenreader-only'
text: React.ReactNode
}[]
```
So a basic example would look something like this:
```ts
---
type: example
---
const PasswordExample = () => {
const [password, setPassword] = useState('')
const messages = password.length < 6
? [{type: 'newError', text: 'Password have to be at least 6 characters long!'}]
: []
return (
<TextInput
renderLabel="Password"
type="password"
messages={messages}
onChange={(event, value) => { setPassword(value) }}
/>
)
}

render(<PasswordExample/>)
```

However you might have noticed from the type definition that a message can be `error` and `newError` type. This is due to compatibility reasons. `error` is the older type and does not meet accessibility requirements, `newError` (hance the name) is the newer and more accessible format.

We wanted to allow users to start using the new format without making it mandatory, but after the introductory period `newError` will be deprecated and `error` type will be changed to look and behave the same way.

With this update we also introduced the "required asterisk" which will display an `*` character next to field labels that are required. This update is not opt-in and will apply to **all** InstUI form components so if you we relying on a custom solution for this feature before, you need to remove that to avoid having double asterisks.

Here are examples with different form components:

```ts
---
type: example
---
const Example = () => {
const [showError, setShowError] = useState(true)
const [showNewError, setShowNewError] = useState(true)
const [showLongError, setShowLongError] = useState(false)
const [isRequired, setIsRequired] = useState(true)

const messages = showError
? [{type: showNewError ? 'newError' : 'error', text: showLongError ? 'Long error. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos voluptas, esse commodi eos facilis voluptatibus harum exercitationem. Et magni est consectetur, eveniet veniam unde! Molestiae labore libero sapiente ad ratione.' : 'Short error message'}]
: []

const handleSettingsChange = (v) => {
setShowError(v.includes('showError'))
setShowNewError(v.includes('showNewError'))
setShowLongError(v.includes('showLongError'))
setIsRequired(v.includes('isRequired'))
}

return (
<div>
<CheckboxGroup
name="errorOptions"
description="Error message options"
onChange={handleSettingsChange}
defaultValue={['showError', 'showNewError', 'isRequired']}
>
<Checkbox label="Show error message" value="showError"/>
<Checkbox label="Use the new error type" value="showNewError" />
<Checkbox label="Use long message" value="showLongError" />
<Checkbox label="Make fields required" value="isRequired" />
</CheckboxGroup>
<div style={{display: 'flex', gap: '2rem', marginTop: '3rem', flexDirection: 'column'}}>

<TextInput renderLabel="TextInput" messages={messages} isRequired={isRequired}/>

<NumberInput renderLabel="NumberInput" messages={messages} isRequired={isRequired}/>

<TextArea messages={messages} label="TextArea" required={isRequired}/>

<Checkbox label="Checkbox" isRequired={isRequired} messages={messages}/>

<Checkbox label={`Checkbox (variant="toggle")`} variant="toggle" isRequired={isRequired} messages={messages}/>

<CheckboxGroup
name="CheckboxGroup"
messages={messages}
description="CheckboxGroup"
>
<Checkbox label="Checkbox 1" value="checkbox1"/>
<Checkbox label="Checkbox 2" value="checkbox2"/>
<Checkbox label="Checkbox 3" value="checkbox3"/>
</CheckboxGroup>

<RadioInputGroup name="radioInputGroup" description="RadioInputGroup" messages={messages} isRequired={isRequired}>
<RadioInput
label="RadioInput 1"
value="radioInput1"
/>
<RadioInput
label="RadioInput 2"
value="radioInput2"
/>
<RadioInput
label="RadioInput 3"
value="radioInput3"
/>
</RadioInputGroup>

<FileDrop messages={messages} renderLabel="FileDrop" />
</div>
</div>
)
}

render(<Example/>)
```
101 changes: 101 additions & 0 deletions packages/__examples__/.storybook/stories/FormErrors.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
/*
* The MIT License (MIT)
*
* Copyright (c) 2015 - present Instructure, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/

import React from 'react'
import {
TextInput,
TextArea,
NumberInput,
Checkbox,
CheckboxGroup,
RadioInput,
RadioInputGroup,
FileDrop,
} from '@instructure/ui'

function FormErrors() {
const renderForms = ({messages, isRequired}) => {
return (
<div style={{display: 'flex', gap: '2rem', marginTop: '3rem', flexDirection: 'column'}}>
<TextInput renderLabel="TextInput" messages={messages} isRequired={isRequired}/>
<NumberInput renderLabel="NumberInput" messages={messages} isRequired={isRequired}/>
<TextArea messages={messages} label="TextArea" required={isRequired}/>
<Checkbox label="Checkbox" isRequired={isRequired} messages={messages}/>
<Checkbox label={`Checkbox (variant="toggle")`} variant="toggle" isRequired={isRequired} messages={messages}/>
<CheckboxGroup
name="CheckboxGroup"
messages={messages}
description="CheckboxGroup"
>
<Checkbox label="Checkbox 1" value="checkbox1"/>
<Checkbox label="Checkbox 2" value="checkbox2"/>
<Checkbox label="Checkbox 3" value="checkbox3"/>
</CheckboxGroup>
<RadioInputGroup name="radioInputGroup" description="RadioInputGroup" messages={messages} isRequired={isRequired}>
<RadioInput
label="RadioInput 1"
value="radioInput1"
/>
<RadioInput
label="RadioInput 2"
value="radioInput2"
/>
<RadioInput
label="RadioInput 3"
value="radioInput3"
/>
</RadioInputGroup>
<FileDrop messages={messages} renderLabel="FileDrop" />
</div>
)
}

const exampleMessage = [{ type: 'newError', text: 'Long error. Lorem ipsum dolor sit amet consectetur adipisicing elit. Dignissimos voluptas, esse commodi eos facilis voluptatibus harum exercitationem. Et magni est consectetur, eveniet veniam unde! Molestiae labore libero sapiente ad ratione.' }]

const formOptions = [
{
messages: exampleMessage,
isRequired: true
},
{
messages: exampleMessage,
isRequired: false
},
{
messages: [],
isRequired: true
},
{
messages: [],
isRequired: false
},
]
return (
<div>
{formOptions.map((option) => renderForms(option))}
</div>
)
}

export default FormErrors
10 changes: 10 additions & 0 deletions packages/__examples__/.storybook/stories/stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { renderPage } from './renderPage'
// @ts-ignore TODO figure out why this is an error
import propJSONData from '../../prop-data.json'
import TooltipPositioning from './TooltipPositioning'
import FormErrors from './FormErrors'
import SourceCodeEditorExamples from './SourceCodeEditorExamples'

type AdditionalExample = {
Expand Down Expand Up @@ -68,6 +69,15 @@ const additionalExamples: AdditionalExample[] = [
}
]
},
{
title: 'Form errors',
stories: [
{
storyName: 'Form errors',
storyFn: () => FormErrors()
}
]
},
// TODO: try to fix the editor not rendering fully on chromatic screenshot,
// even with delay
{
Expand Down
11 changes: 11 additions & 0 deletions packages/shared-types/src/ComponentThemeVariables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ export type CheckboxFacadeTheme = {
iconSizeSmall: string
iconSizeMedium: string
iconSizeLarge: string
errorBorderColor: Colors['contrasts']['red4570']
}

export type ToggleFacadeTheme = {
Expand Down Expand Up @@ -343,6 +344,7 @@ export type ToggleFacadeTheme = {
labelFontSizeSmall: Typography['fontSizeSmall']
labelFontSizeMedium: Typography['fontSizeMedium']
labelFontSizeLarge: Typography['fontSizeLarge']
errorBorderColor: Colors['contrasts']['red4570']
}

export type CodeEditorTheme = {
Expand Down Expand Up @@ -584,6 +586,7 @@ export type FormFieldMessageTheme = {
fontWeight: Typography['fontWeightNormal']
fontSize: Typography['fontSizeSmall']
lineHeight: Typography['lineHeight']
errorIconMarginRight: Spacing['xxSmall']
}

export type FormFieldMessagesTheme = {
Expand Down Expand Up @@ -879,6 +882,7 @@ export type NumberInputTheme = {
mediumHeight: Forms['inputHeightMedium']
largeFontSize: Typography['fontSizeLarge']
largeHeight: Forms['inputHeightLarge']
requiredInvalidColor: Colors['contrasts']['red5782']
}

export type OptionsItemTheme = {
Expand Down Expand Up @@ -1365,6 +1369,7 @@ export type TextAreaTheme = {
mediumHeight: Forms['inputHeightMedium']
largeFontSize: Typography['fontSizeLarge']
largeHeight: Forms['inputHeightLarge']
requiredInvalidColor: Colors['contrasts']['red5782']
}

export type TextInputTheme = {
Expand All @@ -1389,6 +1394,7 @@ export type TextInputTheme = {
mediumHeight: Forms['inputHeightMedium']
largeFontSize: Typography['fontSizeLarge']
largeHeight: Forms['inputHeightLarge']
requiredInvalidColor: Colors['contrasts']['red5782']
}

export type ToggleDetailsTheme = {
Expand Down Expand Up @@ -1659,6 +1665,10 @@ export type ViewTheme = {
borderStyle: string
}

export type RadioInputGroupTheme = {
invalidAsteriskColor: Colors['contrasts']['red5782']
}

export interface ThemeVariables {
Avatar: AvatarTheme
Alert: AlertTheme
Expand Down Expand Up @@ -1797,4 +1807,5 @@ export interface ThemeVariables {
TruncateText: TruncateTextTheme
ContextView: ContextViewTheme
View: ViewTheme
RadioInputGroup: RadioInputGroupTheme
}
7 changes: 6 additions & 1 deletion packages/ui-checkbox/src/Checkbox/CheckboxFacade/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ type CheckboxFacadeOwnProps = {
* Visual state showing that child checkboxes are a combination of checked and unchecked
*/
indeterminate?: boolean
/**
* Indicate if the parent component (`Checkbox`) is invalid to set the style accordingly.
*/
invalid?: boolean
}

type PropKeys = keyof CheckboxFacadeOwnProps
Expand All @@ -57,7 +61,8 @@ const propTypes: PropValidators<PropKeys> = {
focused: PropTypes.bool,
hovered: PropTypes.bool,
size: PropTypes.oneOf(['small', 'medium', 'large']),
indeterminate: PropTypes.bool
indeterminate: PropTypes.bool,
invalid: PropTypes.bool
}

const allowedProps: AllowedPropKeys = [
Expand Down
4 changes: 2 additions & 2 deletions packages/ui-checkbox/src/Checkbox/CheckboxFacade/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ const generateStyle = (
componentTheme: CheckboxFacadeTheme,
props: CheckboxFacadeProps
): CheckboxFacadeStyle => {
const { size, checked, focused, hovered, indeterminate } = props
const { size, checked, focused, hovered, indeterminate, invalid } = props

const isChecked = checked || indeterminate

Expand Down Expand Up @@ -87,7 +87,7 @@ const generateStyle = (
boxSizing: 'border-box',
flexShrink: 0,
transition: 'all 0.2s',
border: `${componentTheme.borderWidth} solid ${componentTheme.borderColor}`,
border: `${componentTheme.borderWidth} solid ${invalid ? componentTheme.errorBorderColor : componentTheme.borderColor}`,
borderRadius: componentTheme.borderRadius,
marginInlineEnd: componentTheme.marginRight,
marginInlineStart: '0',
Expand Down
1 change: 1 addition & 0 deletions packages/ui-checkbox/src/Checkbox/CheckboxFacade/theme.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ const generateComponentTheme = (theme: Theme): CheckboxFacadeTheme => {
color: colors?.contrasts?.white1010,
borderWidth: borders?.widthSmall,
borderColor: colors?.contrasts?.grey1214,
errorBorderColor: colors?.ui?.textError,
borderRadius: borders?.radiusMedium,
background: colors?.contrasts?.white1010,
marginRight: spacing?.xSmall,
Expand Down
7 changes: 6 additions & 1 deletion packages/ui-checkbox/src/Checkbox/ToggleFacade/props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ type ToggleFacadeOwnProps = {
focused?: boolean
size?: 'small' | 'medium' | 'large'
labelPlacement?: 'top' | 'start' | 'end'
/**
* Indicate if the parent component (`Checkbox`) is invalid to set the style accordingly.
*/
invalid?: boolean
}

type PropKeys = keyof ToggleFacadeOwnProps
Expand All @@ -59,7 +63,8 @@ const propTypes: PropValidators<PropKeys> = {
readOnly: PropTypes.bool,
focused: PropTypes.bool,
size: PropTypes.oneOf(['small', 'medium', 'large']),
labelPlacement: PropTypes.oneOf(['top', 'start', 'end'])
labelPlacement: PropTypes.oneOf(['top', 'start', 'end']),
invalid: PropTypes.bool
}

const allowedProps: AllowedPropKeys = [
Expand Down
Loading

0 comments on commit 9b03683

Please sign in to comment.