UNPKG

@octopusdeploy/design-system-components

Version:
166 lines (165 loc) 10.9 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.TextField = TextField; const jsx_runtime_1 = require("react/jsx-runtime"); const css_1 = require("@emotion/css"); const design_system_tokens_1 = require("@octopusdeploy/design-system-tokens"); const React = __importStar(require("react")); const FormDescription_1 = require("../Primitives/FormDescription"); const Input_1 = require("../Primitives/Input"); const InputLabel_1 = require("../Primitives/InputLabel"); const InputValidationMessage_1 = require("../Primitives/InputValidationMessage"); const formFieldMaxWidth_1 = require("../formFieldMaxWidth"); /** * TextField component * @remarks Only use in pre-approved areas, as in #project-form-uplift if unsure before using. * * @param props - TextFieldProps * @param props.label - The label for the input field * @param props.value - The current value of the input * @param props.type - The input type (text, email, password, etc.) * @param props.placeholder - The placeholder text to display when input is empty * @param props.description - The description text to display below the input * @param props.validationMessage - Validation message to display * @param props.validationState - The validation state ('error' | 'success'). Only applied when a `validationMessage` is provided; defaults to 'error' in that case. * @param props.disabled - Whether the field is disabled * @param props.hasRequiredMarker - Whether the field is required * @param props.hasOptionalMarker - Whether to show optional marker * @param props.hasDefaultMarker - Whether this field has a default value marker * @param props.popover - PopoverBasicHelp component to display additional help information e.g. <PopoverBasicHelp placement="right-start" description="A popover" /> * @param props.autoFocus - Whether to autofocus the input * @param props.readOnly - Whether the input is readonly * @param props.name - The name attribute for the input * @param props.prefix - The prefix to display before the input - can be a string or a icon it cannot be interactive * @param props.suffix - The suffix to display after the input - can be a string or a button with ghost importance and medium size only * @param props.onChange - The action to perform when the form control field is changed * @param props.onClear - A clear (✕) button is shown at the start of the suffix to clear the field. * @param props.actions - Raw icon-only `Button` elements displayed inside the field (max two recommended). Prebuilt/declarative actions live in `@octopusdeploy/design-system-octopus-components`. * * @returns TextField component */ function TextField(props) { const { label, value, placeholder, description, validationMessage, validationState, onChange, disabled = false, hasRequiredMarker = false, hasOptionalMarker = false, hasDefaultMarker = false, popover, type = "text", autoFocus = false, readOnly = false, name, prefix, suffix, actions, inputRef, onClear, onBlur, required, } = props; const [localValidationErrorMessage, setLocalValidationErrorMessage] = React.useState(null); // Once the user edits the field, an external validationMessage is no longer guaranteed to still apply (we // don't control when the caller re-validates), so stop showing this specific message until the caller sets // a different one. Tracked by value rather than a boolean so a fresh message (even after being dismissed) // shows immediately without needing another edit. const [dismissedValidationMessage, setDismissedValidationMessage] = React.useState(undefined); // If the caller clears validationMessage (e.g. useMutation resets its error to null at the start of every // submit, before the new result comes in), that's a reliable sign a fresh validation pass is happening - // forget the dismissal so an identical message reappearing afterwards isn't mistaken for the stale one. // This compares against the previous render's prop rather than reacting to the dismissal itself, following // React's "adjusting state when a prop changes" pattern, so it takes effect in the same render (no flash). const [previousValidationMessage, setPreviousValidationMessage] = React.useState(validationMessage); if (validationMessage !== previousValidationMessage) { setPreviousValidationMessage(validationMessage); if (!validationMessage) { setDismissedValidationMessage(undefined); } } // min, max, step only when type is "number" const min = props.type === "number" ? props.min : undefined; const max = props.type === "number" ? props.max : undefined; const step = props.type === "number" ? props.step : undefined; // minLength, maxLength only when type is not "number" const minLength = props.type !== "number" ? props.minLength : undefined; const maxLength = props.type !== "number" ? props.maxLength : undefined; const [previousValue, setPreviousValue] = React.useState(value); if (value !== previousValue) { setPreviousValue(value); setLocalValidationErrorMessage(runValidators({ value, required, type, min, max, minLength, maxLength })); } const validateOnChangeHandler = (newValue) => { setLocalValidationErrorMessage(runValidators({ value: newValue, required, type, min, max, minLength, maxLength })); if (validationMessage) { setDismissedValidationMessage(validationMessage); } onChange(newValue); }; const baseId = React.useId(); const inputId = `textfield-${name ? name + "-" : ""}${baseId}`; const effectiveValidationMessage = validationMessage && validationMessage === dismissedValidationMessage ? undefined : validationMessage; const localValidationDisplayState = localValidationErrorMessage ? "error" : "none"; const validationDisplayState = effectiveValidationMessage ? (validationState ?? "error") : "none"; const mergedValidationDisplayState = localValidationDisplayState === "error" ? localValidationDisplayState : validationDisplayState; const mergedValidationMessage = localValidationErrorMessage ?? effectiveValidationMessage; return ((0, jsx_runtime_1.jsxs)("div", { className: (0, css_1.cx)(containerStyles), children: [(0, jsx_runtime_1.jsxs)("div", { children: [(0, jsx_runtime_1.jsx)(InputLabel_1.InputLabel, { label: label, htmlFor: inputId, isDisabled: disabled, hasRequiredMarker: hasRequiredMarker, hasOptionalMarker: hasOptionalMarker, hasDefaultMarker: hasDefaultMarker, popover: popover }), description && (0, jsx_runtime_1.jsx)(FormDescription_1.FormDescription, { id: `${inputId}-description`, description: description, isDisabled: disabled })] }), (0, jsx_runtime_1.jsx)(Input_1.Input, { ref: inputRef, id: inputId, type: type, value: value, placeholder: placeholder, disabled: disabled, required: required, readOnly: readOnly, autoFocus: autoFocus, min: min, max: max, step: step, name: name, prefix: prefix, suffix: suffix, actions: actions, onClear: onClear, onChange: validateOnChangeHandler, onBlur: onBlur, "aria-describedby": [description ? `${inputId}-description` : null, mergedValidationMessage ? `${inputId}-validation` : null].filter(Boolean).join(" ") || undefined, validationDisplayState: mergedValidationDisplayState }), (0, jsx_runtime_1.jsx)(InputValidationMessage_1.InputValidationMessage, { message: mergedValidationMessage, displayState: mergedValidationDisplayState, id: `${inputId}-validation` })] })); } const requiredValidator = ({ value, required }) => (required && (value === undefined || value === "") ? "This field is required." : null); // The underlying <input> always reports its value as a string via event.target.value, even when type="number", // so a numeric value must be parsed out before comparing against min/max. function parseNumericValue(value) { const numericValue = typeof value === "number" ? value : parseFloat(String(value)); return isNaN(numericValue) ? undefined : numericValue; } const minValidator = ({ value, type, min }) => { if (type !== "number" || min === undefined) { return null; } const numericValue = parseNumericValue(value); return numericValue !== undefined && numericValue < min ? `This field's minimum allowed value is ${min}.` : null; }; const maxValidator = ({ value, type, max }) => { if (type !== "number" || max === undefined) { return null; } const numericValue = parseNumericValue(value); return numericValue !== undefined && numericValue > max ? `This field's maximum allowed value is ${max}.` : null; }; const minLengthValidator = ({ value, minLength }) => { if (minLength === undefined || typeof value !== "string" || value === "") { return null; } return value.length < minLength ? `This field's value must be ${minLength} characters or more.` : null; }; const maxLengthValidator = ({ value, maxLength }) => { if (maxLength === undefined || typeof value !== "string") { return null; } return value.length > maxLength ? `This field's value must be ${maxLength} characters or less.` : null; }; const validators = [requiredValidator, minValidator, maxValidator, minLengthValidator, maxLengthValidator]; function runValidators(context) { return validators.reduce((error, validate) => error ?? validate(context), null); } const containerStyles = (0, css_1.css)({ display: "grid", position: "relative", gap: design_system_tokens_1.space[8], width: "100%", maxWidth: formFieldMaxWidth_1.formFieldMaxWidth, });