UNPKG

@octopusdeploy/design-system-components

Version:
169 lines (168 loc) • 10.5 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.Input = void 0; const jsx_runtime_1 = require("react/jsx-runtime"); const css_1 = require("@emotion/css"); const design_system_icons_1 = require("@octopusdeploy/design-system-icons"); const design_system_tokens_1 = require("@octopusdeploy/design-system-tokens"); const React = __importStar(require("react")); const useObserveElementSize_1 = require("../../../hooks/useObserveElementSize"); const Button_1 = require("../../Button"); const SharedFormStyling_styles_1 = require("../Primitives/SharedFormStyling.styles"); function InputInner(props, ref) { const { id, value, placeholder, onChange, onClear, onFocus, onBlur, onKeyDown, disabled = false, required = false, type = "text", autoFocus = false, readOnly = false, name, prefix, suffix, actions, validationDisplayState, "aria-describedby": ariaDescribedBy, "aria-activedescendant": ariaActiveDescendant, "aria-controls": ariaControls, "aria-autocomplete": ariaAutoComplete, "aria-label": ariaLabel, } = props; // 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; const handleChange = React.useCallback((event) => { if (onChange) { // eslint-disable-next-line @typescript-eslint/consistent-type-assertions onChange(event.target.value); } }, [onChange]); const handleClear = React.useCallback(() => { onClear?.(); }, [onClear]); // React useId adds colons which are not valid in css custom properties const sanitisedInputId = id.replace(/[:;]/g, ""); const isButtonSuffix = React.isValidElement(suffix); const hasActions = actions !== undefined && actions.length > 0; const hasValue = value !== undefined && value !== null && value !== ""; const showClearButton = hasValue && Boolean(onClear) && !disabled && !readOnly; // Simple text truncation for prefix and suffix const suffixText = typeof suffix === "string" ? (suffix.length > 4 ? suffix.substring(0, 4) : suffix) : null; const containerRef = React.useRef(null); const [prefixElement, setPrefixElement] = React.useState(null); const [suffixElement, setSuffixElement] = React.useState(null); // Determines the width of the prefix, suffix, and clear button and sets a custom property. // This ensures that the size is correct regardless of the prefix/suffix length or content const prefixWidthCssVar = `--${sanitisedInputId}-prefix-width`; const suffixWidthCssVar = `--${sanitisedInputId}-suffix-width`; (0, useObserveElementSize_1.useObserveElementSize)(prefixElement, ({ width }) => containerRef.current?.style.setProperty(prefixWidthCssVar, `${width}px`), () => containerRef.current?.style.removeProperty(prefixWidthCssVar)); (0, useObserveElementSize_1.useObserveElementSize)(suffixElement, ({ width }) => containerRef.current?.style.setProperty(suffixWidthCssVar, `${width}px`), () => containerRef.current?.style.removeProperty(suffixWidthCssVar)); const inputPaddingStyles = { paddingLeft: prefix ? `var(${prefixWidthCssVar})` : undefined, paddingRight: suffix || onClear || hasActions ? `var(${suffixWidthCssVar})` : undefined, }; return ((0, jsx_runtime_1.jsxs)("div", { ref: containerRef, className: (0, css_1.cx)(inputContainerStyles), children: [prefix && ((0, jsx_runtime_1.jsx)("div", { ref: setPrefixElement, className: (0, css_1.cx)(inputPrefixStyles), children: prefix ? ((0, jsx_runtime_1.jsx)("p", { className: prefixSuffixTextStyles, title: typeof prefix === "string" ? prefix : undefined, children: prefix })) : (prefix) })), (0, jsx_runtime_1.jsx)("input", { ref: ref, id: id, type: type, name: name, // Coalesce null/undefined to "" so the input stays controlled for its whole lifetime. Letting // `value` go to undefined (e.g. NumberField reporting "no value" when cleared) makes React treat // the field as switching from controlled to uncontrolled, which can leave the DOM's value stuck // at its last defined value instead of clearing (reproduced live: type "0", backspace, the field // never empties). value: value ?? "", placeholder: placeholder, disabled: disabled, readOnly: readOnly, "aria-readonly": readOnly, "aria-required": required, autoFocus: autoFocus, min: min, max: max, step: step, className: (0, css_1.cx)(textFieldStyles, SharedFormStyling_styles_1.inputStyles, { [SharedFormStyling_styles_1.inputErrorStyles]: validationDisplayState === "error", [SharedFormStyling_styles_1.inputSuccessStyles]: validationDisplayState === "success", [SharedFormStyling_styles_1.inputDisabledStyles]: disabled, [SharedFormStyling_styles_1.inputReadOnlyStyles]: readOnly, }), style: inputPaddingStyles, onChange: handleChange, onFocus: onFocus, onBlur: onBlur, onKeyDown: onKeyDown, "aria-invalid": validationDisplayState === "error", "aria-describedby": ariaDescribedBy, "aria-activedescendant": ariaActiveDescendant, "aria-controls": ariaControls, "aria-autocomplete": ariaAutoComplete, "aria-label": ariaLabel }), (suffix || onClear || hasActions) && ((0, jsx_runtime_1.jsxs)("div", { ref: setSuffixElement, className: (0, css_1.cx)(inputSuffixStyles, { [inputSuffixButtonStyles]: isButtonSuffix || hasActions, }), children: [showClearButton && ((0, jsx_runtime_1.jsx)("div", { className: clearButtonContainerStyles, children: (0, jsx_runtime_1.jsx)(Button_1.Button, { size: "small", importance: "ghost", icon: (0, jsx_runtime_1.jsx)(design_system_icons_1.XmarkIcon, { size: 20 }), onClick: handleClear, accessibleName: ariaLabel ? `Clear ${ariaLabel}` : "Clear", "aria-controls": id }) })), suffixText ? ((0, jsx_runtime_1.jsx)("p", { className: prefixSuffixTextStyles, title: typeof suffix === "string" ? suffix : undefined, children: suffixText })) : (suffix), (suffix || showClearButton) && hasActions && (0, jsx_runtime_1.jsx)("div", { className: SharedFormStyling_styles_1.actionsDividerStyles }), hasActions && (0, jsx_runtime_1.jsx)("div", { className: inputActions, children: actions })] }))] })); } // forwardRef doesn't like function components with generics, so this assertion is required // revisit this in React 19 // eslint-disable-next-line @typescript-eslint/consistent-type-assertions exports.Input = React.forwardRef(InputInner); const inputContainerStyles = (0, css_1.css)({ position: "relative", display: "grid", gridTemplateColumns: "minmax(0, max-content) 1fr minmax(0, max-content)", isolation: "isolate", }); const textFieldStyles = (0, css_1.css)({ minHeight: "2rem", placeContent: "center", gridColumn: "1 / -1", gridRow: 1, textOverflow: "ellipsis", whiteSpace: "nowrap", overflow: "hidden", // Fix the input leading so TextField and Select text align vertically. // This avoids a ~1px shift when toggling between them (e.g. BindableField). // `&&` increases specificity over inputStyles' `font` shorthand line-height. "&&": { lineHeight: "normal", }, }); const inputPrefixStyles = (0, css_1.css)({ font: design_system_tokens_1.text.body.regular.medium, color: design_system_tokens_1.themeTokens.color.text.secondary, gridColumn: "1 / 2", gridRow: 1, justifySelf: "start", placeContent: "center", padding: `0 ${design_system_tokens_1.space[6]} 0 ${design_system_tokens_1.space[8]}`, zIndex: 1, }); const clearButtonContainerStyles = (0, css_1.css)({ pointerEvents: "auto", }); const inputSuffixStyles = (0, css_1.css)({ font: design_system_tokens_1.text.body.regular.medium, color: design_system_tokens_1.themeTokens.color.text.secondary, gridColumn: "3 / 4", gridRow: 1, justifySelf: "end", placeContent: "center", padding: `0 ${design_system_tokens_1.space[8]}`, pointerEvents: "none", display: "flex", alignItems: "center", }); const prefixSuffixTextStyles = (0, css_1.css)({ margin: 0, // If there is a divider next to the suffix, add a small margin to the right so the text doesn't butt up against it. // Otherwise the padding with the input itself is sufficient "&:has(+ div)": { marginRight: design_system_tokens_1.space[4], }, }); const inputSuffixButtonStyles = (0, css_1.css)({ pointerEvents: "auto", padding: 0, // Keeps buttons/actions from butting up against the input text once it grows long enough to // reach the suffix. The container is part of the measured suffix width, so this padding also // widens the input's right padding to match, preserving the gap. paddingLeft: design_system_tokens_1.space[6], ...SharedFormStyling_styles_1.suffixSharedStyles, "button:disabled svg": { fill: design_system_tokens_1.themeTokens.color.icon.secondary, }, }); const inputActions = (0, css_1.css)({ display: "flex", });