Skip to content
Draft
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
55 changes: 8 additions & 47 deletions src/base-field/base-field.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -2,68 +2,29 @@
--reactist-field-label-padding-bottom: 6px;
--reactist-field-label-line-height: inherit;
}

.container {
font-family: var(--reactist-font-family);
display: flex;
flex-direction: column;
}

.container label {
letter-spacing: -0.15px;
padding-bottom: var(--reactist-field-label-padding-bottom);
line-height: var(--reactist-field-label-line-height);
}

.container label,
.container .auxiliaryLabel {
text-align: right;
padding-bottom: var(--reactist-field-label-padding-bottom);
line-height: var(--reactist-field-label-line-height);
}

.container.bordered {
border-radius: var(--reactist-border-radius-large);
border: 1px solid var(--reactist-inputs-idle);
padding: var(--reactist-spacing-small);
padding-bottom: var(--reactist-spacing-xsmall);
overflow: clip;
}

.container.bordered label {
/* so that clicking in blank areas to the right of the label will focus the field element */
flex-grow: 1;
/* to convey that clicking in blank area to the right of the label places focus on the text field */
cursor: text;
}

.container.bordered label span {
/* overrides the cursor set above, so that hovering over the non-blank parts of the label stay unaffected */
cursor: default;
}

.container.bordered:hover {
border-color: var(--reactist-inputs-hover) !important;
}

.container.bordered:focus-within {
border-color: var(--reactist-inputs-focus) !important;
}

.container.bordered.error {
border-color: var(--reactist-inputs-alert) !important;
}

.container.bordered .primaryLabel {
font-weight: 500;
}

.container.bordered .auxiliaryLabel {
font-size: var(--reactist-font-size-caption);
}

.container:not(.bordered) .primaryLabel {
.container .primaryLabel {
font-weight: var(--reactist-font-weight-strong);
}

.container:not(.bordered) .auxiliaryLabel {
font-size: var(--reactist-font-size-body);
}

.container input,
.container textarea,
.container select {
Expand All @@ -75,7 +36,7 @@
}

.auxiliaryLabel {
text-align: right;
font-size: var(--reactist-font-size-body);
}

.loadingIcon {
Expand Down
212 changes: 28 additions & 184 deletions src/base-field/base-field.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,6 @@ import styles from './base-field.module.css'
import type { BoxProps } from '../box'
import type { WithEnhancedClassName } from '../utils/common-types'

// Define the remaining characters before the character count turns red
// See: https://twist.com/a/1585/ch/765851/t/6664583/c/93631846 for latest spec
const MAX_LENGTH_THRESHOLD = 0

type FieldTone = 'neutral' | 'success' | 'error' | 'loading'
Expand Down Expand Up @@ -74,25 +72,16 @@ function validateInputLength({
maxLength,
}: ValidateInputLengthProps): ValidateInputLengthResult {
if (!maxLength) {
return {
count: null,
tone: 'neutral',
}
return { count: null, tone: 'neutral' }
}

const currentLength = String(value || '').length
const isNearMaxLength = maxLength - currentLength <= MAX_LENGTH_THRESHOLD

return {
count: `${currentLength}/${maxLength}`,
tone: isNearMaxLength ? 'error' : 'neutral',
}
}

//
// BaseField
//

type ChildrenRenderProps = {
id: string
value?: React.InputHTMLAttributes<unknown>['value']
Expand All @@ -107,144 +96,29 @@ type HtmlInputProps<T extends HTMLElement> = React.DetailedHTMLProps<
T
>

type BaseFieldVariant = 'default' | 'bordered'
type BaseFieldVariantProps = {
/**
* Provides alternative visual layouts or modes that the field can be rendered in.
*
* Namely, there are two variants supported:
*
* - the default one
* - a "bordered" variant, where the border of the field surrounds also the labels, instead
* of just surrounding the actual field element
*
* In both cases, the message and description texts for the field lie outside the bordered
* area.
*/
variant?: BaseFieldVariant
}

export type BaseFieldProps = WithEnhancedClassName &
Pick<HtmlInputProps<HTMLInputElement>, 'id' | 'hidden' | 'maxLength' | 'aria-describedby'> & {
/**
* The main label for this field element.
*
* This prop is not optional. Consumers of field components must be explicit about not
* wanting a label by passing `label=""` or `label={null}`. In those situations, consumers
* should make sure that fields are properly labelled semantically by other means (e.g using
* `aria-labelledby`, or rendering a `<label />` element referencing the field by id).
*
* Avoid providing interactive elements in the label. Prefer `auxiliaryLabel` for that.
*
* @see BaseFieldProps['auxiliaryLabel']
*/
/** Main label. Pass `null` for components that render the label themselves. */
label: React.ReactNode

/**
* The initial value for this field element.
*
* This prop is used to calculate the character count for the initial value, and is then
* passed to the underlying child element.
*/
value?: React.InputHTMLAttributes<unknown>['value']

/**
* An optional extra element to be placed to the right of the main label.
*
* This extra element is not included in the accessible name of the field element. Its only
* purpose is either visual, or functional (if you include interactive elements in it).
*
* @see BaseFieldProps['label']
*
* @deprecated The usage of this element is discouraged given that it was removed from the
* latest form field spec revision.
*/
/** @deprecated removed from the latest form-field spec; will be deleted in a future major. */
auxiliaryLabel?: React.ReactNode

/**
* A message associated with the field. It is rendered below the field, and with an
* appearance that conveys the tone of the field (e.g. coloured red for errors, green for
* success, etc).
*
* The message element is associated to the field via the `aria-describedby` attribute.
*
* In the future, when `aria-errormessage` gets better user agent support, we should use it
* to associate the filed with a message when tone is `"error"`.
*
* @see BaseFieldProps['tone']
* @see https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-errormessage
* @see https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes/aria-invalid
*/
message?: React.ReactNode

/**
* The tone with which the message, if any, is presented.
*
* If the tone is `"error"`, the field border turns red, and the message, if any, is also
* red.
*
* When the tone is `"loading"`, it is recommended that you also disable the field. However,
* this is not enforced by the component. It is only a recommendation.
*
* @see BaseFieldProps['message']
* @see BaseFieldProps['hint']
*/
tone?: FieldTone

/**
* The maximum width that the input field can expand to.
*/
maxWidth?: BoxProps['maxWidth']

/**
* The maximum number of characters that the input field can accept.
* When this limit is reached, the input field will not accept any more characters.
* The counter element will turn red when the number of characters is within 10 of the maximum limit.
*/
maxLength?: number

/**
* Used internally by components composed using `BaseField`. It is not exposed as part of
* the public props of such components.
*/
children: (props: ChildrenRenderProps) => React.ReactNode

/**
* The position of the character count element.
* It can be shown below the field or inline with the field.
*
* @default 'below'
*/
/** 'below' (default) renders the count under the field; 'inline' yields it via the render-prop; 'hidden' suppresses. */
characterCountPosition?: 'below' | 'inline' | 'hidden'
} & (
| {
supportsStartAndEndSlots?: false
endSlot?: never
endSlotPosition?: never
}
| {
supportsStartAndEndSlots: true
endSlot?: React.ReactElement | string | number
/**
* This is solely for `bordered` variants of TextField. When set to `bottom` (the default),
* the endSlot will be placed inline with the input field. When set to `fullHeight`, the endSlot
* will be placed to the side of both the input field and the label.
*/
endSlotPosition?: 'bottom' | 'fullHeight'
}
)
}

type FieldComponentProps<T extends HTMLElement> = Omit<
BaseFieldProps,
'children' | 'className' | 'fieldRef' | 'variant'
'children' | 'className' | 'fieldRef'
> &
Omit<HtmlInputProps<T>, 'className' | 'style'>

/**
* BaseField is a base component that provides a consistent structure for form fields.
*/
function BaseField({
variant = 'default',
label,
value,
auxiliaryLabel,
Expand All @@ -258,9 +132,7 @@ function BaseField({
'aria-describedby': originalAriaDescribedBy,
id: originalId,
characterCountPosition = 'below',
endSlot,
endSlotPosition = 'bottom',
}: BaseFieldProps & BaseFieldVariantProps & WithEnhancedClassName) {
}: BaseFieldProps) {
const id = useId(originalId)
const messageId = useId()

Expand Down Expand Up @@ -288,19 +160,14 @@ function BaseField({
...(ariaDescribedBy ? { 'aria-describedby': ariaDescribedBy } : {}),
'aria-invalid': tone === 'error' ? true : undefined,
onChange(event) {
if (!maxLength) {
return
}

if (!maxLength) return
const inputLength = validateInputLength({
value: event.currentTarget.value,
maxLength,
})

setCharacterCount(inputLength.count)
setCharacterCountTone(inputLength.tone)
},
// If the character count is inline, we pass it as a prop to the children element so it can be rendered inline
characterCountElement: renderCharacterCountInline ? renderCharacterCount() : null,
}

Expand All @@ -313,45 +180,25 @@ function BaseField({

return (
<Stack space="xsmall" hidden={hidden}>
<Box
display="flex"
flexDirection="row"
className={[
className,
styles.container,
tone === 'error' ? styles.error : null,
variant === 'bordered' ? styles.bordered : null,
]}
maxWidth={maxWidth}
alignItems="center"
>
<Box flexGrow={1}>
{label || auxiliaryLabel ? (
<Box
as="span"
display="flex"
justifyContent="spaceBetween"
alignItems="flexEnd"
>
<Text
size={variant === 'bordered' ? 'caption' : 'body'}
as="label"
htmlFor={id}
>
{label ? (
<span className={styles.primaryLabel}>{label}</span>
) : null}
</Text>
{auxiliaryLabel ? (
<Box className={styles.auxiliaryLabel} paddingLeft="small">
{auxiliaryLabel}
</Box>
) : null}
</Box>
) : null}
{children(childrenProps)}
</Box>
{endSlot && endSlotPosition === 'fullHeight' ? endSlot : null}
<Box className={[className, styles.container]} maxWidth={maxWidth}>
{label || auxiliaryLabel ? (
<Box
as="span"
display="flex"
justifyContent="spaceBetween"
alignItems="flexEnd"
>
<Text size="body" as="label" htmlFor={id}>
{label ? <span className={styles.primaryLabel}>{label}</span> : null}
</Text>
{auxiliaryLabel ? (
<Box className={styles.auxiliaryLabel} paddingLeft="small">
{auxiliaryLabel}
</Box>
) : null}
</Box>
) : null}
{children(childrenProps)}
</Box>

{message || renderCharacterCountBelow ? (
Expand All @@ -363,9 +210,6 @@ function BaseField({
</FieldMessage>
</Column>
) : null}

{/* If the character count is below the field, we render it, if it's inline,
we pass it as a prop to the children element so it can be rendered inline */}
{characterCountPosition === 'below' ? (
<Column width="content">{renderCharacterCount()}</Column>
) : null}
Expand All @@ -376,4 +220,4 @@ function BaseField({
}

export { BaseField, FieldMessage }
export type { BaseFieldVariant, BaseFieldVariantProps, FieldComponentProps }
export type { FieldComponentProps }
Loading
Loading