@mrshmllw/smores-react 16.11.5 → 16.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,7 +5,6 @@ export interface Props extends CommonFieldProps {
5
5
  name?: string;
6
6
  value: string;
7
7
  decimalNumber?: boolean;
8
- formatThousands?: boolean;
9
8
  onBlur?: (e: FocusEvent<HTMLInputElement>) => void;
10
9
  min?: number;
11
10
  max?: number;
@@ -8,9 +8,10 @@ import { getFieldAria } from '../fields/fieldAria';
8
8
  import { faSterlingSign } from '@awesome.me/kit-46ca99185c/icons/classic/regular';
9
9
  import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
10
10
  import { useTheme } from 'styled-components';
11
- const DIGITS_DOT_OR_MINUS = /[\d.-]/;
12
- const stripFormatting = (value) => {
13
- const cleaned = value.replace(/(?!^)-|[^\d.-]/g, '');
11
+ const stripFormatting = (value, allowNegative) => {
12
+ const cleaned = allowNegative
13
+ ? value.replace(/[^\d.-]/g, '').replace(/(?!^)-/g, '')
14
+ : value.replace(/[^\d.]/g, '');
14
15
  const [integer, ...fraction] = cleaned.split('.');
15
16
  return fraction.length ? `${integer}.${fraction.join('')}` : integer;
16
17
  };
@@ -21,18 +22,17 @@ const addThousandsSeparators = (value) => {
21
22
  const grouped = integer.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
22
23
  return fraction === undefined ? grouped : `${grouped}.${fraction}`;
23
24
  };
24
- const countSignificant = (value) => value.replace(/[^\d.-]/g, '').length;
25
25
  const caretAfterSignificant = (formatted, count) => {
26
26
  let seen = 0;
27
27
  for (let i = 0; i < formatted.length; i++) {
28
28
  if (seen === count)
29
29
  return i;
30
- if (DIGITS_DOT_OR_MINUS.test(formatted[i]))
30
+ if (formatted[i] !== ',')
31
31
  seen++;
32
32
  }
33
33
  return formatted.length;
34
34
  };
35
- export const CurrencyInput = forwardRef(function CurrencyInput({ id: idProp, placeholder, name, value, decimalNumber = true, formatThousands = false, onChange, onInputChange, onBlur, min, max, disabled = false, error = false, fallbackStyle, ...fieldProps }, ref) {
35
+ export const CurrencyInput = forwardRef(function CurrencyInput({ id: idProp, placeholder, name, value, decimalNumber = true, onChange, onInputChange, onBlur, min, max, disabled = false, error = false, fallbackStyle, ...fieldProps }, ref) {
36
36
  const theme = useTheme();
37
37
  const id = useUniqueId(idProp);
38
38
  const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {
@@ -48,7 +48,9 @@ export const CurrencyInput = forwardRef(function CurrencyInput({ id: idProp, pla
48
48
  else if (ref)
49
49
  ref.current = node;
50
50
  }, [ref]);
51
- const displayValue = formatThousands ? addThousandsSeparators(value) : value;
51
+ const allowNegative = min !== undefined && min < 0;
52
+ // Some apps pass a number or an already-formatted string despite the type
53
+ const displayValue = addThousandsSeparators(stripFormatting(String(value ?? ''), allowNegative));
52
54
  const applyPendingCaret = () => {
53
55
  const input = inputRef.current;
54
56
  const pending = pendingCaret.current;
@@ -62,12 +64,8 @@ export const CurrencyInput = forwardRef(function CurrencyInput({ id: idProp, pla
62
64
  useLayoutEffect(applyPendingCaret);
63
65
  const formatCurrency = (value) => {
64
66
  const decimalIndex = value.indexOf('.');
65
- if (!decimalNumber) {
66
- const numberValue = Number(value);
67
- return Number.isNaN(numberValue)
68
- ? value
69
- : Math.trunc(numberValue).toString();
70
- }
67
+ if (!decimalNumber)
68
+ return value.split('.')[0];
71
69
  if (decimalIndex >= 0 && value.length > decimalIndex + 1) {
72
70
  const fractionalString = value.substring(decimalIndex + 1).substring(0, 2);
73
71
  return `${value.substring(0, decimalIndex)}.${fractionalString}`;
@@ -78,9 +76,9 @@ export const CurrencyInput = forwardRef(function CurrencyInput({ id: idProp, pla
78
76
  };
79
77
  const applyMinMax = (value) => {
80
78
  const numberValue = Number(value);
81
- if (min && numberValue < min)
79
+ if (min !== undefined && numberValue < min)
82
80
  return min.toString();
83
- if (max && numberValue > max)
81
+ if (max !== undefined && numberValue > max)
84
82
  return max.toString();
85
83
  return value;
86
84
  };
@@ -95,26 +93,18 @@ export const CurrencyInput = forwardRef(function CurrencyInput({ id: idProp, pla
95
93
  return;
96
94
  onChange(normalise(value));
97
95
  };
98
- return (_jsx(Field, { ...fieldProps, htmlFor: id, error: error, assistiveTextId: assistiveTextId, errorMsgId: errorMsgId, children: _jsxs(Box, { flex: true, alignItems: "center", justifyContent: "flex-start", children: [_jsx(InputLeadingIconContainer, { $size: 20, $disabled: disabled, style: { top: '-1px' }, children: _jsx(FontAwesomeIcon, { icon: faSterlingSign, color: disabled ? theme.color.icon.subtle : theme.color.text.subtle }) }), _jsx(Input, { ref: setInputRef, $error: error, disabled: disabled, type: formatThousands ? 'text' : 'number', inputMode: formatThousands ? 'decimal' : undefined, id: id, name: name, placeholder: placeholder, value: displayValue, $frontIcon: true, $fallbackStyle: fallbackStyle, onChange: (e) => {
99
- if (formatThousands) {
100
- const { value: typed, selectionStart } = e.currentTarget;
101
- const raw = stripFormatting(typed);
102
- const nextDisplay = addThousandsSeparators(onChange ? normalise(raw) : raw);
103
- const significantBeforeCaret = countSignificant(typed.slice(0, selectionStart ?? typed.length));
104
- pendingCaret.current = {
105
- value: nextDisplay,
106
- position: caretAfterSignificant(nextDisplay, significantBeforeCaret),
107
- };
108
- queueMicrotask(applyPendingCaret);
109
- if (onChange)
110
- handleChange(raw);
111
- }
112
- else if (onChange) {
113
- handleChange(e.currentTarget.value);
114
- }
96
+ return (_jsx(Field, { ...fieldProps, htmlFor: id, error: error, assistiveTextId: assistiveTextId, errorMsgId: errorMsgId, children: _jsxs(Box, { flex: true, alignItems: "center", justifyContent: "flex-start", children: [_jsx(InputLeadingIconContainer, { $size: 20, $disabled: disabled, style: { top: '-1px' }, children: _jsx(FontAwesomeIcon, { icon: faSterlingSign, color: disabled ? theme.color.icon.subtle : theme.color.text.subtle }) }), _jsx(Input, { ref: setInputRef, $error: error, disabled: disabled, type: "text", inputMode: decimalNumber ? 'decimal' : 'numeric', id: id, name: name, placeholder: placeholder, value: displayValue, $frontIcon: true, $fallbackStyle: fallbackStyle, onChange: (e) => {
97
+ const { value: typed, selectionStart } = e.currentTarget;
98
+ const raw = stripFormatting(typed, allowNegative);
99
+ const nextDisplay = addThousandsSeparators(onChange ? normalise(raw) : raw);
100
+ const significantBeforeCaret = stripFormatting(typed.slice(0, selectionStart ?? typed.length), allowNegative).length;
101
+ pendingCaret.current = {
102
+ value: nextDisplay,
103
+ position: caretAfterSignificant(nextDisplay, significantBeforeCaret),
104
+ };
105
+ queueMicrotask(applyPendingCaret);
106
+ handleChange(raw);
115
107
  onInputChange?.(e);
116
- }, onWheel: formatThousands
117
- ? undefined
118
- : (e) => e.currentTarget.blur(), ...controlAria, onBlur: onBlur })] }) }));
108
+ }, ...controlAria, onBlur: onBlur })] }) }));
119
109
  });
120
110
  //# sourceMappingURL=CurrencyInput.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"CurrencyInput.js","sourceRoot":"","sources":["../../src/CurrencyInput/CurrencyInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAKL,UAAU,EACV,WAAW,EACX,eAAe,EACf,MAAM,GACP,MAAM,OAAO,CAAA;AAEd,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAC5B,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAA;AAGvC,OAAO,EACL,KAAK,EACL,yBAAyB,GAC1B,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,cAAc,EAAE,MAAM,kDAAkD,CAAA;AACjF,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAA;AAChE,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAa5C,MAAM,mBAAmB,GAAG,QAAQ,CAAA;AAEpC,MAAM,eAAe,GAAG,CAAC,KAAa,EAAE,EAAE;IACxC,MAAM,OAAO,GAAG,KAA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AI,EAAE,KAE7D,WAAW,EACf,MAAM,EAAE,MAAM,GACd,IACE,GACA,CACT,CAAA;AACH,CAAC,CAAC,CAAA","sourcesContent":["import {\n FocusEvent,\n FormEvent,\n ForwardedRef,\n WheelEvent,\n forwardRef,\n useCallback,\n useLayoutEffect,\n useRef,\n} from 'react'\n\nimport { Box } from '../Box'\nimport { Field } from '../fields/Field'\nimport { CommonFieldProps } from '../fields/commonFieldTypes'\n\nimport {\n Input,\n InputLeadingIconContainer,\n} from '../fields/components/CommonInput'\nimport { useUniqueId } from '../utils/id'\nimport { getFieldAria } from '../fields/fieldAria'\nimport { faSterlingSign } from '@awesome.me/kit-46ca99185c/icons/classic/regular'\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome'\nimport { useTheme } from 'styled-components'\n\nexport interface Props extends CommonFieldProps {\n placeholder: string\n name?: string\n value: string\n decimalNumber?: boolean\n formatThousands?: boolean\n onBlur?: (e: FocusEvent<HTMLInputElement>) => void\n min?: number\n max?: number\n}\n\nconst DIGITS_DOT_OR_MINUS = /[\\d.-]/\n\nconst stripFormatting = (value: string) => {\n const cleaned = value.replace(/(?!^)-|[^\\d.-]/g, '')\n const [integer, ...fraction] = cleaned.split('.')\n return fraction.length ? `${integer}.${fraction.join('')}` : integer\n}\n\nconst addThousandsSeparators = (value: string) => {\n if (!value) return value\n const [integer, fraction] = value.split('.')\n const grouped = integer.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return fraction === undefined ? grouped : `${grouped}.${fraction}`\n}\n\nconst countSignificant = (value: string) => value.replace(/[^\\d.-]/g, '').length\n\nconst caretAfterSignificant = (formatted: string, count: number) => {\n let seen = 0\n for (let i = 0; i < formatted.length; i++) {\n if (seen === count) return i\n if (DIGITS_DOT_OR_MINUS.test(formatted[i])) seen++\n }\n return formatted.length\n}\n\n/** on change or on input required */\ntype InputProps =\n | {\n /** on change is required and on input optional */\n onChange: (e: string) => void\n onInputChange?: (e: FormEvent<HTMLInputElement>) => void\n }\n | {\n /** on input is required and on change optional */\n onChange?: (e: string) => void\n onInputChange: (e: FormEvent<HTMLInputElement>) => void\n }\n\nexport type CurrencyInputProps = Props & InputProps\n\nexport const CurrencyInput = forwardRef(function CurrencyInput(\n {\n id: idProp,\n placeholder,\n name,\n value,\n decimalNumber = true,\n formatThousands = false,\n onChange,\n onInputChange,\n onBlur,\n min,\n max,\n disabled = false,\n error = false,\n fallbackStyle,\n ...fieldProps\n }: CurrencyInputProps,\n ref: ForwardedRef<HTMLInputElement>,\n) {\n const theme = useTheme()\n const id = useUniqueId(idProp)\n const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {\n ...fieldProps,\n error,\n })\n const inputRef = useRef<HTMLInputElement | null>(null)\n const pendingCaret = useRef<{ value: string; position: number } | null>(null)\n\n const setInputRef = useCallback(\n (node: HTMLInputElement | null) => {\n inputRef.current = node\n if (typeof ref === 'function') ref(node)\n else if (ref) ref.current = node\n },\n [ref],\n )\n\n const displayValue = formatThousands ? addThousandsSeparators(value) : value\n\n const applyPendingCaret = () => {\n const input = inputRef.current\n const pending = pendingCaret.current\n if (!input || !pending || input.value !== pending.value) return\n pendingCaret.current = null\n if (input.ownerDocument.activeElement === input) {\n input.setSelectionRange(pending.position, pending.position)\n }\n }\n\n useLayoutEffect(applyPendingCaret)\n\n const formatCurrency = (value: string) => {\n const decimalIndex = value.indexOf('.')\n\n if (!decimalNumber) {\n const numberValue = Number(value)\n return Number.isNaN(numberValue)\n ? value\n : Math.trunc(numberValue).toString()\n }\n\n if (decimalIndex >= 0 && value.length > decimalIndex + 1) {\n const fractionalString = value.substring(decimalIndex + 1).substring(0, 2)\n return `${value.substring(0, decimalIndex)}.${fractionalString}`\n } else {\n return value\n }\n }\n\n const applyMinMax = (value: string) => {\n const numberValue = Number(value)\n if (min && numberValue < min) return min.toString()\n if (max && numberValue > max) return max.toString()\n return value\n }\n\n const normalise = (value: string) => {\n const EMPTY_INPUT = ''\n if (value === EMPTY_INPUT) return value\n return applyMinMax(formatCurrency(value))\n }\n\n const handleChange = (value: string) => {\n if (onChange === undefined) return\n onChange(normalise(value))\n }\n\n return (\n <Field\n {...fieldProps}\n htmlFor={id}\n error={error}\n assistiveTextId={assistiveTextId}\n errorMsgId={errorMsgId}\n >\n <Box flex alignItems=\"center\" justifyContent=\"flex-start\">\n <InputLeadingIconContainer\n $size={20}\n $disabled={disabled}\n style={{ top: '-1px' }}\n >\n <FontAwesomeIcon\n icon={faSterlingSign}\n color={disabled ? theme.color.icon.subtle : theme.color.text.subtle}\n />\n </InputLeadingIconContainer>\n <Input\n ref={setInputRef}\n $error={error}\n disabled={disabled}\n type={formatThousands ? 'text' : 'number'}\n inputMode={formatThousands ? 'decimal' : undefined}\n id={id}\n name={name}\n placeholder={placeholder}\n value={displayValue}\n $frontIcon={true}\n $fallbackStyle={fallbackStyle}\n onChange={(e: FormEvent<HTMLInputElement>) => {\n if (formatThousands) {\n const { value: typed, selectionStart } = e.currentTarget\n const raw = stripFormatting(typed)\n const nextDisplay = addThousandsSeparators(\n onChange ? normalise(raw) : raw,\n )\n const significantBeforeCaret = countSignificant(\n typed.slice(0, selectionStart ?? typed.length),\n )\n pendingCaret.current = {\n value: nextDisplay,\n position: caretAfterSignificant(\n nextDisplay,\n significantBeforeCaret,\n ),\n }\n queueMicrotask(applyPendingCaret)\n if (onChange) handleChange(raw)\n } else if (onChange) {\n handleChange(e.currentTarget.value)\n }\n onInputChange?.(e)\n }}\n onWheel={\n formatThousands\n ? undefined\n : (e: WheelEvent<HTMLInputElement>) => e.currentTarget.blur()\n }\n {...controlAria}\n onBlur={onBlur}\n />\n </Box>\n </Field>\n )\n})\n"]}
1
+ {"version":3,"file":"CurrencyInput.js","sourceRoot":"","sources":["../../src/CurrencyInput/CurrencyInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAIL,UAAU,EACV,WAAW,EACX,eAAe,EACf,MAAM,GACP,MAAM,OAAO,CAAA;AAEd,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAA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C,GAAG,CAAC,CAAA;wBACjB,aAAa,EAAE,CAAC,CAAC,CAAC,CAAA;oBACpB,CAAC,KACG,WAAW,EACf,MAAM,EAAE,MAAM,GACd,IACE,GACA,CACT,CAAA;AACH,CAAC,CAAC,CAAA","sourcesContent":["import {\n FocusEvent,\n FormEvent,\n ForwardedRef,\n forwardRef,\n useCallback,\n useLayoutEffect,\n useRef,\n} from 'react'\n\nimport { Box } from '../Box'\nimport { Field } from '../fields/Field'\nimport { CommonFieldProps } from '../fields/commonFieldTypes'\n\nimport {\n Input,\n InputLeadingIconContainer,\n} from '../fields/components/CommonInput'\nimport { useUniqueId } from '../utils/id'\nimport { getFieldAria } from '../fields/fieldAria'\nimport { faSterlingSign } from '@awesome.me/kit-46ca99185c/icons/classic/regular'\nimport { FontAwesomeIcon } from '@fortawesome/react-fontawesome'\nimport { useTheme } from 'styled-components'\n\nexport interface Props extends CommonFieldProps {\n placeholder: string\n name?: string\n value: string\n decimalNumber?: boolean\n onBlur?: (e: FocusEvent<HTMLInputElement>) => void\n min?: number\n max?: number\n}\n\nconst stripFormatting = (value: string, allowNegative: boolean) => {\n const cleaned = allowNegative\n ? value.replace(/[^\\d.-]/g, '').replace(/(?!^)-/g, '')\n : value.replace(/[^\\d.]/g, '')\n const [integer, ...fraction] = cleaned.split('.')\n return fraction.length ? `${integer}.${fraction.join('')}` : integer\n}\n\nconst addThousandsSeparators = (value: string) => {\n if (!value) return value\n const [integer, fraction] = value.split('.')\n const grouped = integer.replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',')\n return fraction === undefined ? grouped : `${grouped}.${fraction}`\n}\n\nconst caretAfterSignificant = (formatted: string, count: number) => {\n let seen = 0\n for (let i = 0; i < formatted.length; i++) {\n if (seen === count) return i\n if (formatted[i] !== ',') seen++\n }\n return formatted.length\n}\n\n/** on change or on input required */\ntype InputProps =\n | {\n /** on change is required and on input optional */\n onChange: (e: string) => void\n onInputChange?: (e: FormEvent<HTMLInputElement>) => void\n }\n | {\n /** on input is required and on change optional */\n onChange?: (e: string) => void\n onInputChange: (e: FormEvent<HTMLInputElement>) => void\n }\n\nexport type CurrencyInputProps = Props & InputProps\n\nexport const CurrencyInput = forwardRef(function CurrencyInput(\n {\n id: idProp,\n placeholder,\n name,\n value,\n decimalNumber = true,\n onChange,\n onInputChange,\n onBlur,\n min,\n max,\n disabled = false,\n error = false,\n fallbackStyle,\n ...fieldProps\n }: CurrencyInputProps,\n ref: ForwardedRef<HTMLInputElement>,\n) {\n const theme = useTheme()\n const id = useUniqueId(idProp)\n const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {\n ...fieldProps,\n error,\n })\n const inputRef = useRef<HTMLInputElement | null>(null)\n const pendingCaret = useRef<{ value: string; position: number } | null>(null)\n\n const setInputRef = useCallback(\n (node: HTMLInputElement | null) => {\n inputRef.current = node\n if (typeof ref === 'function') ref(node)\n else if (ref) ref.current = node\n },\n [ref],\n )\n\n const allowNegative = min !== undefined && min < 0\n // Some apps pass a number or an already-formatted string despite the type\n const displayValue = addThousandsSeparators(\n stripFormatting(String(value ?? ''), allowNegative),\n )\n\n const applyPendingCaret = () => {\n const input = inputRef.current\n const pending = pendingCaret.current\n if (!input || !pending || input.value !== pending.value) return\n pendingCaret.current = null\n if (input.ownerDocument.activeElement === input) {\n input.setSelectionRange(pending.position, pending.position)\n }\n }\n\n useLayoutEffect(applyPendingCaret)\n\n const formatCurrency = (value: string) => {\n const decimalIndex = value.indexOf('.')\n\n if (!decimalNumber) return value.split('.')[0]\n\n if (decimalIndex >= 0 && value.length > decimalIndex + 1) {\n const fractionalString = value.substring(decimalIndex + 1).substring(0, 2)\n return `${value.substring(0, decimalIndex)}.${fractionalString}`\n } else {\n return value\n }\n }\n\n const applyMinMax = (value: string) => {\n const numberValue = Number(value)\n if (min !== undefined && numberValue < min) return min.toString()\n if (max !== undefined && numberValue > max) return max.toString()\n return value\n }\n\n const normalise = (value: string) => {\n const EMPTY_INPUT = ''\n if (value === EMPTY_INPUT) return value\n return applyMinMax(formatCurrency(value))\n }\n\n const handleChange = (value: string) => {\n if (onChange === undefined) return\n onChange(normalise(value))\n }\n\n return (\n <Field\n {...fieldProps}\n htmlFor={id}\n error={error}\n assistiveTextId={assistiveTextId}\n errorMsgId={errorMsgId}\n >\n <Box flex alignItems=\"center\" justifyContent=\"flex-start\">\n <InputLeadingIconContainer\n $size={20}\n $disabled={disabled}\n style={{ top: '-1px' }}\n >\n <FontAwesomeIcon\n icon={faSterlingSign}\n color={disabled ? theme.color.icon.subtle : theme.color.text.subtle}\n />\n </InputLeadingIconContainer>\n <Input\n ref={setInputRef}\n $error={error}\n disabled={disabled}\n type=\"text\"\n inputMode={decimalNumber ? 'decimal' : 'numeric'}\n id={id}\n name={name}\n placeholder={placeholder}\n value={displayValue}\n $frontIcon={true}\n $fallbackStyle={fallbackStyle}\n onChange={(e: FormEvent<HTMLInputElement>) => {\n const { value: typed, selectionStart } = e.currentTarget\n const raw = stripFormatting(typed, allowNegative)\n const nextDisplay = addThousandsSeparators(\n onChange ? normalise(raw) : raw,\n )\n const significantBeforeCaret = stripFormatting(\n typed.slice(0, selectionStart ?? typed.length),\n allowNegative,\n ).length\n pendingCaret.current = {\n value: nextDisplay,\n position: caretAfterSignificant(\n nextDisplay,\n significantBeforeCaret,\n ),\n }\n queueMicrotask(applyPendingCaret)\n handleChange(raw)\n onInputChange?.(e)\n }}\n {...controlAria}\n onBlur={onBlur}\n />\n </Box>\n </Field>\n )\n})\n"]}
@@ -12,7 +12,7 @@ interface Props extends CommonFieldProps {
12
12
  */
13
13
  onAutoFill?: () => void;
14
14
  }
15
- type InputMode = 'text' | 'email' | 'numeric';
15
+ type InputMode = 'text' | 'email' | 'numeric' | 'decimal' | 'tel';
16
16
  /** on change or on input required */
17
17
  type InputProps = ({
18
18
  /** on change is required and on input optional */
@@ -1 +1 @@
1
- {"version":3,"file":"TextInput.js","sourceRoot":"","sources":["../../src/TextInput/TextInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAKL,UA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AE,EACN,IAAI,EAAE,IAAI,EACV,GAAG,EAAE,GAAG,EACR,cAAc,EAAE,kBAAkB,EAClC,WAAW,EAAE,WAAW,EACxB,KAAK,EAAE,KAAK,EACZ,MAAM,EAAE,KAAK,EACb,UAAU,EAAE,OAAO,CAAC,iBAAiB,CAAC,EACtC,aAAa,EAAE,OAAO,CAAC,oBAAoB,CAAC,EAC5C,cAAc,EAAE,aAAa,EAC7B,YAAY,EAAE,gBAAgB,EAC9B,QAAQ,EAAE,CAAC,CAA8B,EAAE,EAAE;wBAC3C,QAAQ,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAAA;wBACjC,aAAa,EAAE,CAAC,CAAC,CAAC,CAAA;oBACpB,CAAC,EACD,MAAM,EAAE,MAAM,EACd,SAAS,EAAE,aAAa,KACpB,WAAW,GACf,EACD,oBAAoB,IACjB,GACA,CACT,CAAA;AACH,CAAC,CAAC,CAAA","sourcesContent":["import {\n FocusEvent,\n AnimationEvent,\n FormEvent,\n ForwardedRef,\n forwardRef,\n HTMLInputAutoCompleteAttribute,\n} from 'react'\n\nimport { Box } from '../Box'\nimport { Field } from '../fields/Field'\nimport { CommonFieldProps } from '../fields/commonFieldTypes'\nimport {\n Input,\n InputLeadingIconContainer,\n InputTrailingIconContainer,\n StyledFrontIcon,\n StyledTrailingIcon,\n} from '../fields/components/CommonInput'\nimport { useUniqueId } from '../utils/id'\nimport { getFieldAria } from '../fields/fieldAria'\nimport { useTheme } from 'styled-components'\n\ninterface Props extends CommonFieldProps {\n type?: 'text' | 'email' | 'password' | 'time' | 'date' | 'tel'\n placeholder: string\n name?: string\n value: string\n onBlur?: (e: FocusEvent<HTMLInputElement>) => void\n /**\n * Triggers after animation end (animation duration is 2s),\n * the animation starts when a user selects or hovers over an autofill option\n */\n onAutoFill?: () => void\n}\n\ntype InputMode = 'text' | 'email' | 'numeric'\n\n/** on change or on input required */\ntype InputProps = (\n | {\n /** on change is required and on input optional */\n onChange: (e: string) => void\n onInputChange?: (e: FormEvent<HTMLInputElement>) => void\n }\n | {\n /** on input is required and on change optional */\n onChange?: (e: string) => void\n onInputChange: (e: FormEvent<HTMLInputElement>) => void\n }\n) & {\n autoCompleteAttr?: HTMLInputAutoCompleteAttribute\n inputModeAttr?: InputMode\n}\n\nexport type TextInputProps = Props & InputProps\n\n/**\n * A reusable TextInput component that supports various input types, custom styling, icons,\n * and autofill detection.\n *\n * ### Caveats:\n * - `onAutoFill` triggers after animation end (animation duration is 2s),\n * the animation starts when a user selects or hovers over an autofill option\n */\nexport const TextInput = forwardRef(function TextInput(\n {\n id: idProp,\n type = 'text',\n placeholder,\n name,\n value,\n error = false,\n onBlur,\n onChange,\n onInputChange,\n onAutoFill,\n disabled = false,\n frontIcon,\n frontIconComponent,\n trailingIconComponent,\n trailingIcon,\n fallbackStyle,\n autoCompleteAttr = 'off',\n inputModeAttr,\n ...fieldProps\n }: TextInputProps,\n ref: ForwardedRef<HTMLInputElement>,\n) {\n const id = useUniqueId(idProp)\n const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {\n ...fieldProps,\n error,\n })\n const theme = useTheme()\n\n const handleAnimationEnd = (e: AnimationEvent<HTMLInputElement>) => {\n if (e.animationName === 'onAutoFillStart' && onAutoFill && !!value) {\n onAutoFill()\n }\n }\n\n const iconColor = disabled ? 'color.icon.subtle' : 'color.icon.base'\n const iconFill = disabled ? theme.color.icon.subtle : theme.color.text.subtle\n\n const frontIconToRender = frontIconComponent ? (\n <InputLeadingIconContainer\n $size={20}\n $disabled={disabled}\n $iconColor={iconFill}\n >\n {frontIconComponent}\n </InputLeadingIconContainer>\n ) : frontIcon ? (\n <StyledFrontIcon\n $disabled={disabled}\n render={frontIcon}\n color={iconColor}\n />\n ) : null\n\n const trailingIconToRender = trailingIconComponent ? (\n <InputTrailingIconContainer\n $size={20}\n $disabled={disabled}\n $iconColor={iconFill}\n >\n {trailingIconComponent}\n </InputTrailingIconContainer>\n ) : trailingIcon ? (\n <StyledTrailingIcon\n $disabled={disabled}\n render={trailingIcon}\n color={iconColor}\n />\n ) : null\n\n return (\n <Field\n {...fieldProps}\n htmlFor={id}\n error={error}\n assistiveTextId={assistiveTextId}\n errorMsgId={errorMsgId}\n >\n <Box flex alignItems=\"center\" justifyContent=\"flex-start\">\n {frontIconToRender}\n <Input\n disabled={disabled}\n type={type}\n id={id}\n name={name}\n ref={ref}\n onAnimationEnd={handleAnimationEnd}\n placeholder={placeholder}\n value={value}\n $error={error}\n $frontIcon={Boolean(frontIconToRender)}\n $trailingIcon={Boolean(trailingIconToRender)}\n $fallbackStyle={fallbackStyle}\n autoComplete={autoCompleteAttr}\n onChange={(e: FormEvent<HTMLInputElement>) => {\n onChange?.(e.currentTarget.value)\n onInputChange?.(e)\n }}\n onBlur={onBlur}\n inputMode={inputModeAttr}\n {...controlAria}\n />\n {trailingIconToRender}\n </Box>\n </Field>\n )\n})\n"]}
1
+ {"version":3,"file":"TextInput.js","sourceRoot":"","sources":["../../src/TextInput/TextInput.tsx"],"names":[],"mappings":";AAAA,OAAO,EAKL,UAAU,GAEX,MAAM,OAAO,CAAA;AAEd,OAAO,EAAE,GAAG,EAAE,MAAM,QAAQ,CAAA;AAC5B,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAA;AAEvC,OAAO,EACL,KAAK,EACL,yBAAyB,EACzB,0BAA0B,EAC1B,eAAe,EACf,kBAAkB,GACnB,MAAM,kCAAkC,CAAA;AACzC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAoC5C;;;;;;;GAOG;AACH,MAAM,CAAC,MAAM,SAAS,GAAG,UAAU,CAAC,SAAS,SAAS,CACpD,EACE,EAAE,EAAE,MAAM,EACV,IAAI,GAAG,MAAM,EACb,WAAW,EACX,IAAI,EACJ,KAAK,EACL,KAAK,GAAG,KAAK,EAC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AAA","sourcesContent":["import {\n FocusEvent,\n AnimationEvent,\n FormEvent,\n ForwardedRef,\n forwardRef,\n HTMLInputAutoCompleteAttribute,\n} from 'react'\n\nimport { Box } from '../Box'\nimport { Field } from '../fields/Field'\nimport { CommonFieldProps } from '../fields/commonFieldTypes'\nimport {\n Input,\n InputLeadingIconContainer,\n InputTrailingIconContainer,\n StyledFrontIcon,\n StyledTrailingIcon,\n} from '../fields/components/CommonInput'\nimport { useUniqueId } from '../utils/id'\nimport { getFieldAria } from '../fields/fieldAria'\nimport { useTheme } from 'styled-components'\n\ninterface Props extends CommonFieldProps {\n type?: 'text' | 'email' | 'password' | 'time' | 'date' | 'tel'\n placeholder: string\n name?: string\n value: string\n onBlur?: (e: FocusEvent<HTMLInputElement>) => void\n /**\n * Triggers after animation end (animation duration is 2s),\n * the animation starts when a user selects or hovers over an autofill option\n */\n onAutoFill?: () => void\n}\n\ntype InputMode = 'text' | 'email' | 'numeric' | 'decimal' | 'tel'\n\n/** on change or on input required */\ntype InputProps = (\n | {\n /** on change is required and on input optional */\n onChange: (e: string) => void\n onInputChange?: (e: FormEvent<HTMLInputElement>) => void\n }\n | {\n /** on input is required and on change optional */\n onChange?: (e: string) => void\n onInputChange: (e: FormEvent<HTMLInputElement>) => void\n }\n) & {\n autoCompleteAttr?: HTMLInputAutoCompleteAttribute\n inputModeAttr?: InputMode\n}\n\nexport type TextInputProps = Props & InputProps\n\n/**\n * A reusable TextInput component that supports various input types, custom styling, icons,\n * and autofill detection.\n *\n * ### Caveats:\n * - `onAutoFill` triggers after animation end (animation duration is 2s),\n * the animation starts when a user selects or hovers over an autofill option\n */\nexport const TextInput = forwardRef(function TextInput(\n {\n id: idProp,\n type = 'text',\n placeholder,\n name,\n value,\n error = false,\n onBlur,\n onChange,\n onInputChange,\n onAutoFill,\n disabled = false,\n frontIcon,\n frontIconComponent,\n trailingIconComponent,\n trailingIcon,\n fallbackStyle,\n autoCompleteAttr = 'off',\n inputModeAttr,\n ...fieldProps\n }: TextInputProps,\n ref: ForwardedRef<HTMLInputElement>,\n) {\n const id = useUniqueId(idProp)\n const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {\n ...fieldProps,\n error,\n })\n const theme = useTheme()\n\n const handleAnimationEnd = (e: AnimationEvent<HTMLInputElement>) => {\n if (e.animationName === 'onAutoFillStart' && onAutoFill && !!value) {\n onAutoFill()\n }\n }\n\n const iconColor = disabled ? 'color.icon.subtle' : 'color.icon.base'\n const iconFill = disabled ? theme.color.icon.subtle : theme.color.text.subtle\n\n const frontIconToRender = frontIconComponent ? (\n <InputLeadingIconContainer\n $size={20}\n $disabled={disabled}\n $iconColor={iconFill}\n >\n {frontIconComponent}\n </InputLeadingIconContainer>\n ) : frontIcon ? (\n <StyledFrontIcon\n $disabled={disabled}\n render={frontIcon}\n color={iconColor}\n />\n ) : null\n\n const trailingIconToRender = trailingIconComponent ? (\n <InputTrailingIconContainer\n $size={20}\n $disabled={disabled}\n $iconColor={iconFill}\n >\n {trailingIconComponent}\n </InputTrailingIconContainer>\n ) : trailingIcon ? (\n <StyledTrailingIcon\n $disabled={disabled}\n render={trailingIcon}\n color={iconColor}\n />\n ) : null\n\n return (\n <Field\n {...fieldProps}\n htmlFor={id}\n error={error}\n assistiveTextId={assistiveTextId}\n errorMsgId={errorMsgId}\n >\n <Box flex alignItems=\"center\" justifyContent=\"flex-start\">\n {frontIconToRender}\n <Input\n disabled={disabled}\n type={type}\n id={id}\n name={name}\n ref={ref}\n onAnimationEnd={handleAnimationEnd}\n placeholder={placeholder}\n value={value}\n $error={error}\n $frontIcon={Boolean(frontIconToRender)}\n $trailingIcon={Boolean(trailingIconToRender)}\n $fallbackStyle={fallbackStyle}\n autoComplete={autoCompleteAttr}\n onChange={(e: FormEvent<HTMLInputElement>) => {\n onChange?.(e.currentTarget.value)\n onInputChange?.(e)\n }}\n onBlur={onBlur}\n inputMode={inputModeAttr}\n {...controlAria}\n />\n {trailingIconToRender}\n </Box>\n </Field>\n )\n})\n"]}
@@ -12,7 +12,17 @@ type BaseProps = {
12
12
  disabled?: boolean;
13
13
  maxLength?: number;
14
14
  onBlur?: (e: FocusEvent<HTMLTextAreaElement>) => void;
15
+ /**
16
+ * Number of lines the textarea shows before it has any content to grow with. Defaults to 4.
17
+ * A `height` set in CSS on the textarea becomes the starting height instead.
18
+ */
15
19
  rows?: number;
20
+ /**
21
+ * The most lines the textarea grows to as the content gets longer. Past this it scrolls.
22
+ * Defaults to 8. A value lower than `rows` is treated as `rows`. A taller
23
+ * `height` set in CSS on the textarea raises the cap to match it.
24
+ */
25
+ maxRows?: number;
16
26
  fallbackStyle?: boolean;
17
27
  } & CommonFieldProps & MarginProps;
18
28
  type TruncateProps = {
@@ -1,33 +1,137 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
- import { forwardRef } from 'react';
2
+ import { forwardRef, useCallback, useLayoutEffect, useRef, } from 'react';
3
3
  import styled from 'styled-components';
4
+ import { useMergeRefs } from '@floating-ui/react';
4
5
  import { Field } from '../fields/Field';
5
6
  import { useUniqueId } from '../utils/id';
6
7
  import { getFieldAria } from '../fields/fieldAria';
7
8
  import { fieldDisabledStyle, fieldFocusAttrs, fieldFocusRing, fieldHoverBorderColor, } from '../fields/components/fieldStyles';
8
- export const Textarea = forwardRef(function Textarea({ id: idProp, name, value, onChange, onInputChange, resize = 'none', error = false, placeholder, disabled = false, maxLength, onBlur, rows = 4, fallbackStyle, ...fieldProps }, ref) {
9
+ const LINE_HEIGHT = 20;
10
+ const PADDING = 12;
11
+ const BORDER = 2;
12
+ // Padding and border (top and bottom) around the lines of text
13
+ const CHROME_HEIGHT = 2 * (PADDING + BORDER);
14
+ const DEFAULT_ROWS = 4;
15
+ const DEFAULT_MAX_ROWS = 8;
16
+ export const Textarea = forwardRef(function Textarea({ id: idProp, name, value, onChange, onInputChange, resize = 'none', error = false, placeholder, disabled = false, maxLength, onBlur, rows = DEFAULT_ROWS, maxRows = DEFAULT_MAX_ROWS, fallbackStyle, ...fieldProps }, ref) {
9
17
  const id = useUniqueId(idProp);
18
+ const innerRef = useRef(null);
19
+ const mergedRef = useMergeRefs([ref, innerRef]);
20
+ // Set once the user drags the resize handle. From then on their size wins
21
+ // and the height is no longer fitted to the content.
22
+ const userSizedRef = useRef(false);
23
+ const pointerDownRef = useRef(false);
24
+ // The height we last wrote, to tell our own size changes from the user's
25
+ const lastFitHeightRef = useRef(null);
10
26
  const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {
11
27
  ...fieldProps,
12
28
  error,
13
29
  });
14
- return (_jsx(Field, { ...fieldProps, htmlFor: id, error: error, assistiveTextId: assistiveTextId, errorMsgId: errorMsgId, children: _jsx(StyledTextArea, { ref: ref, $error: error, id: id, name: name, disabled: disabled, $resize: resize, $fallbackStyle: fallbackStyle, placeholder: placeholder, value: value, onChange: (e) => {
30
+ const fitHeightToContent = useCallback(() => {
31
+ const el = innerRef.current;
32
+ if (!el || userSizedRef.current)
33
+ return;
34
+ // Measure from the height the stylesheet gives the textarea, which is a
35
+ // height set in CSS if there is one, otherwise the `rows` height. Hide the
36
+ // scrollbar so it doesn't take up width and change how the text wraps.
37
+ el.style.overflowY = 'hidden';
38
+ el.style.height = '';
39
+ const minHeight = Math.max(el.offsetHeight, rows * LINE_HEIGHT + CHROME_HEIGHT);
40
+ const maxHeight = Math.max(Math.max(rows, maxRows) * LINE_HEIGHT + CHROME_HEIGHT, minHeight);
41
+ // scrollHeight is never less than the visible height, and includes the
42
+ // padding but not the border.
43
+ const contentHeight = el.scrollHeight + 2 * BORDER;
44
+ const height = Math.min(Math.max(contentHeight, minHeight), maxHeight);
45
+ lastFitHeightRef.current = height;
46
+ el.style.height = `${height}px`;
47
+ // A box the user has dragged smaller than its content still needs to scroll.
48
+ el.style.overflowY =
49
+ contentHeight > maxHeight || resize === 'both' ? 'auto' : 'hidden';
50
+ }, [rows, maxRows, resize]);
51
+ // Dragging the resize handle is only possible with resize="both". Track
52
+ // whether a pointer is down so the observer below can tell a drag from the
53
+ // container changing width. This is declared before the effect that fits the
54
+ // height, so that leaving "both" forgets the dragged size first and the fit
55
+ // that follows (its callback changes with `resize`) is not skipped.
56
+ useLayoutEffect(() => {
57
+ const el = innerRef.current;
58
+ if (!el || resize !== 'both') {
59
+ userSizedRef.current = false;
60
+ // Drop the width a drag left behind
61
+ if (el)
62
+ el.style.width = '';
63
+ return;
64
+ }
65
+ const onDown = () => {
66
+ pointerDownRef.current = true;
67
+ };
68
+ const onUp = () => {
69
+ pointerDownRef.current = false;
70
+ };
71
+ el.addEventListener('pointerdown', onDown);
72
+ // The pointer can be released outside the textarea
73
+ document.addEventListener('pointerup', onUp);
74
+ document.addEventListener('pointercancel', onUp);
75
+ return () => {
76
+ pointerDownRef.current = false;
77
+ el.removeEventListener('pointerdown', onDown);
78
+ document.removeEventListener('pointerup', onUp);
79
+ document.removeEventListener('pointercancel', onUp);
80
+ };
81
+ }, [resize]);
82
+ // Runs for typing and for the value being reset from outside.
83
+ useLayoutEffect(() => {
84
+ fitHeightToContent();
85
+ }, [fitHeightToContent, value]);
86
+ // A change in width rewraps the text, so the height is fitted again. Height
87
+ // changes are ignored so that resizing the box ourselves doesn't loop. A size
88
+ // we didn't write, while the pointer is down, is the user dragging the resize
89
+ // handle, so fitting stops for good.
90
+ useLayoutEffect(() => {
91
+ const el = innerRef.current;
92
+ if (!el || typeof ResizeObserver === 'undefined')
93
+ return;
94
+ let width = el.offsetWidth;
95
+ let frame = 0;
96
+ const observer = new ResizeObserver(() => {
97
+ if (pointerDownRef.current &&
98
+ (el.offsetHeight !== lastFitHeightRef.current ||
99
+ el.offsetWidth !== width)) {
100
+ userSizedRef.current = true;
101
+ cancelAnimationFrame(frame);
102
+ width = el.offsetWidth;
103
+ return;
104
+ }
105
+ if (el.offsetWidth === width)
106
+ return;
107
+ width = el.offsetWidth;
108
+ cancelAnimationFrame(frame);
109
+ frame = requestAnimationFrame(fitHeightToContent);
110
+ });
111
+ observer.observe(el);
112
+ return () => {
113
+ observer.disconnect();
114
+ cancelAnimationFrame(frame);
115
+ };
116
+ }, [fitHeightToContent]);
117
+ return (_jsx(Field, { ...fieldProps, htmlFor: id, error: error, assistiveTextId: assistiveTextId, errorMsgId: errorMsgId, children: _jsx(StyledTextArea, { ref: mergedRef, $error: error, id: id, name: name, disabled: disabled, $resize: resize, $fallbackStyle: fallbackStyle, placeholder: placeholder, value: value, onChange: (e) => {
15
118
  onChange?.(e.currentTarget.value);
16
119
  onInputChange?.(e);
17
120
  }, maxLength: maxLength, onBlur: onBlur, rows: rows, ...controlAria }) }));
18
121
  });
19
122
  const StyledTextArea = styled.textarea.attrs(fieldFocusAttrs) `
123
+ display: block;
20
124
  font-size: 16px;
21
125
  font: inherit;
22
- line-height: 20px;
126
+ line-height: ${LINE_HEIGHT}px;
23
127
  background: ${({ $fallbackStyle, theme }) => $fallbackStyle
24
128
  ? theme.color.surface.base[300]
25
129
  : theme.color.background['000']};
26
- border: 2px solid ${({ theme }) => theme.color.border.subtle};
130
+ border: ${BORDER}px solid ${({ theme }) => theme.color.border.subtle};
27
131
  box-sizing: border-box;
28
132
  border-radius: 12px;
29
133
  width: 100%;
30
- padding: 12px;
134
+ padding: ${PADDING}px;
31
135
  color: ${({ theme }) => theme.color.text.base};
32
136
  resize: ${({ $resize }) => $resize};
33
137
  cursor: ${({ disabled }) => (disabled ? 'not-allowed' : 'text')};
@@ -1 +1 @@
1
- {"version":3,"file":"Textarea.js","sourceRoot":"","sources":["../../src/Textarea/Textarea.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAuC,UAAU,EAAE,MAAM,OAAO,CAAA;AACvE,OAAO,MAAM,MAAM,mBAAmB,CAAA;AAEtC,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAA;AAEvC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EACL,kBAAkB,EAClB,eAAe,EACf,cAAc,EACd,qBAAqB,GACtB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IAAI,CAAC,MAAM;;CAElD,CAAA","sourcesContent":["import { FocusEvent, FormEvent, ForwardedRef, forwardRef } from 'react'\nimport styled from 'styled-components'\n\nimport { Field } from '../fields/Field'\nimport { CommonFieldProps } from '../fields/commonFieldTypes'\nimport { useUniqueId } from '../utils/id'\nimport { getFieldAria } from '../fields/fieldAria'\nimport {\n fieldDisabledStyle,\n fieldFocusAttrs,\n fieldFocusRing,\n fieldHoverBorderColor,\n} from '../fields/components/fieldStyles'\nimport { MarginProps } from '../utils/space'\n\ntype BaseProps = {\n id?: string\n placeholder?: string\n name?: string\n value: string\n error?: boolean\n errorMsg?: string\n resize?: 'none' | 'both'\n disabled?: boolean\n maxLength?: number\n onBlur?: (e: FocusEvent<HTMLTextAreaElement>) => void\n rows?: number\n fallbackStyle?: boolean\n} & CommonFieldProps &\n MarginProps\n\ntype TruncateProps =\n | {\n onChange: (e: string) => void\n onInputChange?: (e: FormEvent<HTMLTextAreaElement>) => void\n }\n | {\n onChange?: (e: string) => void\n onInputChange: (e: FormEvent<HTMLTextAreaElement>) => void\n }\n\nexport type TextareaProps = BaseProps & TruncateProps\n\nexport const Textarea = forwardRef(function Textarea(\n {\n id: idProp,\n name,\n value,\n onChange,\n onInputChange,\n resize = 'none',\n error = false,\n placeholder,\n disabled = false,\n maxLength,\n onBlur,\n rows = 4,\n fallbackStyle,\n ...fieldProps\n }: TextareaProps,\n ref: ForwardedRef<HTMLTextAreaElement>,\n) {\n const id = useUniqueId(idProp)\n const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {\n ...fieldProps,\n error,\n })\n return (\n <Field\n {...fieldProps}\n htmlFor={id}\n error={error}\n assistiveTextId={assistiveTextId}\n errorMsgId={errorMsgId}\n >\n <StyledTextArea\n ref={ref}\n $error={error}\n id={id}\n name={name}\n disabled={disabled}\n $resize={resize}\n $fallbackStyle={fallbackStyle}\n placeholder={placeholder}\n value={value}\n onChange={(e: FormEvent<HTMLTextAreaElement>) => {\n onChange?.(e.currentTarget.value)\n onInputChange?.(e)\n }}\n maxLength={maxLength}\n onBlur={onBlur}\n rows={rows}\n {...controlAria}\n />\n </Field>\n )\n})\n\ninterface TextArea {\n $resize: 'none' | 'both'\n disabled: boolean\n $error: boolean\n $fallbackStyle?: boolean\n}\n\nconst StyledTextArea = styled.textarea.attrs(fieldFocusAttrs)<TextArea>`\n font-size: 16px;\n font: inherit;\n line-height: 20px;\n background: ${({ $fallbackStyle, theme }) =>\n $fallbackStyle\n ? theme.color.surface.base[300]\n : theme.color.background['000']};\n border: 2px solid ${({ theme }) => theme.color.border.subtle};\n box-sizing: border-box;\n border-radius: 12px;\n width: 100%;\n padding: 12px;\n color: ${({ theme }) => theme.color.text.base};\n resize: ${({ $resize }) => $resize};\n cursor: ${({ disabled }) => (disabled ? 'not-allowed' : 'text')};\n border-color: ${({ $error, theme }) =>\n $error ? theme.color.feedback.negative[200] : theme.color.border.subtle};\n outline: none;\n\n &:hover:not(:disabled):not(:focus) {\n border-color: ${({ $error, theme }) => fieldHoverBorderColor(theme, $error)};\n }\n\n &:focus {\n border-color: ${({ $error, theme }) =>\n $error\n ? theme.color.feedback.negative[200]\n : theme.color.border.contrast};\n }\n\n ${fieldFocusRing}\n ${fieldDisabledStyle}\n\n &::placeholder {\n color: ${({ theme }) => theme.color.text.subtle};\n }\n`\n"]}
1
+ {"version":3,"file":"Textarea.js","sourceRoot":"","sources":["../../src/Textarea/Textarea.tsx"],"names":[],"mappings":";AAAA,OAAO,EAIL,UAAU,EACV,WAAW,EACX,eAAe,EACf,MAAM,GACP,MAAM,OAAO,CAAA;AACd,OAAO,MAAM,MAAM,mBAAmB,CAAA;AACtC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAA;AAEjD,OAAO,EAAE,KAAK,EAAE,MAAM,iBAAiB,CAAA;AAEvC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAA;AAClD,OAAO,EACL,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CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,MAAM;;;;oBAIvD,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,qBAAqB,CAAC,KAAK,EAAE,MAAM,CAAC;;;;oBAI3D,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,EAAE,EAAE,CACpC,MAAM;IACJ,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,QAAQ,CAAC,QAAQ,CAAC,GAAG,CAAC;IACpC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,QAAQ;;;IAGjC,cAAc;IACd,kBAAkB;;;aAGT,CAAC,EAAE,KAAK,EAAE,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM;;CAElD,CAAA","sourcesContent":["import {\n FocusEvent,\n FormEvent,\n ForwardedRef,\n forwardRef,\n useCallback,\n useLayoutEffect,\n useRef,\n} from 'react'\nimport styled from 'styled-components'\nimport { useMergeRefs } from '@floating-ui/react'\n\nimport { Field } from '../fields/Field'\nimport { CommonFieldProps } from '../fields/commonFieldTypes'\nimport { useUniqueId } from '../utils/id'\nimport { getFieldAria } from '../fields/fieldAria'\nimport {\n fieldDisabledStyle,\n fieldFocusAttrs,\n fieldFocusRing,\n fieldHoverBorderColor,\n} from '../fields/components/fieldStyles'\nimport { MarginProps } from '../utils/space'\n\ntype BaseProps = {\n id?: string\n placeholder?: string\n name?: string\n value: string\n error?: boolean\n errorMsg?: string\n resize?: 'none' | 'both'\n disabled?: boolean\n maxLength?: number\n onBlur?: (e: FocusEvent<HTMLTextAreaElement>) => void\n /**\n * Number of lines the textarea shows before it has any content to grow with. Defaults to 4.\n * A `height` set in CSS on the textarea becomes the starting height instead.\n */\n rows?: number\n /**\n * The most lines the textarea grows to as the content gets longer. Past this it scrolls.\n * Defaults to 8. A value lower than `rows` is treated as `rows`. A taller\n * `height` set in CSS on the textarea raises the cap to match it.\n */\n maxRows?: number\n fallbackStyle?: boolean\n} & CommonFieldProps &\n MarginProps\n\ntype TruncateProps =\n | {\n onChange: (e: string) => void\n onInputChange?: (e: FormEvent<HTMLTextAreaElement>) => void\n }\n | {\n onChange?: (e: string) => void\n onInputChange: (e: FormEvent<HTMLTextAreaElement>) => void\n }\n\nexport type TextareaProps = BaseProps & TruncateProps\n\nconst LINE_HEIGHT = 20\nconst PADDING = 12\nconst BORDER = 2\n// Padding and border (top and bottom) around the lines of text\nconst CHROME_HEIGHT = 2 * (PADDING + BORDER)\nconst DEFAULT_ROWS = 4\nconst DEFAULT_MAX_ROWS = 8\n\nexport const Textarea = forwardRef(function Textarea(\n {\n id: idProp,\n name,\n value,\n onChange,\n onInputChange,\n resize = 'none',\n error = false,\n placeholder,\n disabled = false,\n maxLength,\n onBlur,\n rows = DEFAULT_ROWS,\n maxRows = DEFAULT_MAX_ROWS,\n fallbackStyle,\n ...fieldProps\n }: TextareaProps,\n ref: ForwardedRef<HTMLTextAreaElement>,\n) {\n const id = useUniqueId(idProp)\n const innerRef = useRef<HTMLTextAreaElement | null>(null)\n const mergedRef = useMergeRefs([ref, innerRef])\n // Set once the user drags the resize handle. From then on their size wins\n // and the height is no longer fitted to the content.\n const userSizedRef = useRef(false)\n const pointerDownRef = useRef(false)\n // The height we last wrote, to tell our own size changes from the user's\n const lastFitHeightRef = useRef<number | null>(null)\n const { assistiveTextId, errorMsgId, controlAria } = getFieldAria(id, {\n ...fieldProps,\n error,\n })\n\n const fitHeightToContent = useCallback(() => {\n const el = innerRef.current\n if (!el || userSizedRef.current) return\n\n // Measure from the height the stylesheet gives the textarea, which is a\n // height set in CSS if there is one, otherwise the `rows` height. Hide the\n // scrollbar so it doesn't take up width and change how the text wraps.\n el.style.overflowY = 'hidden'\n el.style.height = ''\n const minHeight = Math.max(\n el.offsetHeight,\n rows * LINE_HEIGHT + CHROME_HEIGHT,\n )\n const maxHeight = Math.max(\n Math.max(rows, maxRows) * LINE_HEIGHT + CHROME_HEIGHT,\n minHeight,\n )\n // scrollHeight is never less than the visible height, and includes the\n // padding but not the border.\n const contentHeight = el.scrollHeight + 2 * BORDER\n\n const height = Math.min(Math.max(contentHeight, minHeight), maxHeight)\n lastFitHeightRef.current = height\n el.style.height = `${height}px`\n // A box the user has dragged smaller than its content still needs to scroll.\n el.style.overflowY =\n contentHeight > maxHeight || resize === 'both' ? 'auto' : 'hidden'\n }, [rows, maxRows, resize])\n\n // Dragging the resize handle is only possible with resize=\"both\". Track\n // whether a pointer is down so the observer below can tell a drag from the\n // container changing width. This is declared before the effect that fits the\n // height, so that leaving \"both\" forgets the dragged size first and the fit\n // that follows (its callback changes with `resize`) is not skipped.\n useLayoutEffect(() => {\n const el = innerRef.current\n if (!el || resize !== 'both') {\n userSizedRef.current = false\n // Drop the width a drag left behind\n if (el) el.style.width = ''\n return\n }\n\n const onDown = () => {\n pointerDownRef.current = true\n }\n const onUp = () => {\n pointerDownRef.current = false\n }\n el.addEventListener('pointerdown', onDown)\n // The pointer can be released outside the textarea\n document.addEventListener('pointerup', onUp)\n document.addEventListener('pointercancel', onUp)\n return () => {\n pointerDownRef.current = false\n el.removeEventListener('pointerdown', onDown)\n document.removeEventListener('pointerup', onUp)\n document.removeEventListener('pointercancel', onUp)\n }\n }, [resize])\n\n // Runs for typing and for the value being reset from outside.\n useLayoutEffect(() => {\n fitHeightToContent()\n }, [fitHeightToContent, value])\n\n // A change in width rewraps the text, so the height is fitted again. Height\n // changes are ignored so that resizing the box ourselves doesn't loop. A size\n // we didn't write, while the pointer is down, is the user dragging the resize\n // handle, so fitting stops for good.\n useLayoutEffect(() => {\n const el = innerRef.current\n if (!el || typeof ResizeObserver === 'undefined') return\n\n let width = el.offsetWidth\n let frame = 0\n const observer = new ResizeObserver(() => {\n if (\n pointerDownRef.current &&\n (el.offsetHeight !== lastFitHeightRef.current ||\n el.offsetWidth !== width)\n ) {\n userSizedRef.current = true\n cancelAnimationFrame(frame)\n width = el.offsetWidth\n return\n }\n if (el.offsetWidth === width) return\n width = el.offsetWidth\n cancelAnimationFrame(frame)\n frame = requestAnimationFrame(fitHeightToContent)\n })\n observer.observe(el)\n return () => {\n observer.disconnect()\n cancelAnimationFrame(frame)\n }\n }, [fitHeightToContent])\n\n return (\n <Field\n {...fieldProps}\n htmlFor={id}\n error={error}\n assistiveTextId={assistiveTextId}\n errorMsgId={errorMsgId}\n >\n <StyledTextArea\n ref={mergedRef}\n $error={error}\n id={id}\n name={name}\n disabled={disabled}\n $resize={resize}\n $fallbackStyle={fallbackStyle}\n placeholder={placeholder}\n value={value}\n onChange={(e: FormEvent<HTMLTextAreaElement>) => {\n onChange?.(e.currentTarget.value)\n onInputChange?.(e)\n }}\n maxLength={maxLength}\n onBlur={onBlur}\n rows={rows}\n {...controlAria}\n />\n </Field>\n )\n})\n\ninterface TextArea {\n $resize: 'none' | 'both'\n disabled: boolean\n $error: boolean\n $fallbackStyle?: boolean\n}\n\nconst StyledTextArea = styled.textarea.attrs(fieldFocusAttrs)<TextArea>`\n display: block;\n font-size: 16px;\n font: inherit;\n line-height: ${LINE_HEIGHT}px;\n background: ${({ $fallbackStyle, theme }) =>\n $fallbackStyle\n ? theme.color.surface.base[300]\n : theme.color.background['000']};\n border: ${BORDER}px solid ${({ theme }) => theme.color.border.subtle};\n box-sizing: border-box;\n border-radius: 12px;\n width: 100%;\n padding: ${PADDING}px;\n color: ${({ theme }) => theme.color.text.base};\n resize: ${({ $resize }) => $resize};\n cursor: ${({ disabled }) => (disabled ? 'not-allowed' : 'text')};\n border-color: ${({ $error, theme }) =>\n $error ? theme.color.feedback.negative[200] : theme.color.border.subtle};\n outline: none;\n\n &:hover:not(:disabled):not(:focus) {\n border-color: ${({ $error, theme }) => fieldHoverBorderColor(theme, $error)};\n }\n\n &:focus {\n border-color: ${({ $error, theme }) =>\n $error\n ? theme.color.feedback.negative[200]\n : theme.color.border.contrast};\n }\n\n ${fieldFocusRing}\n ${fieldDisabledStyle}\n\n &::placeholder {\n color: ${({ theme }) => theme.color.text.subtle};\n }\n`\n"]}
@@ -1 +1,2 @@
1
1
  export { Textarea } from './Textarea';
2
+ export type { TextareaProps } from './Textarea';
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/Textarea/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA","sourcesContent":["export { Textarea } from './Textarea'\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/Textarea/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA","sourcesContent":["export { Textarea } from './Textarea'\nexport type { TextareaProps } from './Textarea'\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mrshmllw/smores-react",
3
- "version": "16.11.5",
3
+ "version": "16.13.0",
4
4
  "description": "Collection of React components used by Marshmallow Technology",
5
5
  "main": "./dist/index.js",
6
6
  "type": "module",