@soyfri/shared-library 4.0.2 → 4.0.4
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.
- package/{Autocomplete-Bd3bN4Cw.cjs → Autocomplete-Baqwboth.cjs} +59 -38
- package/Autocomplete-Baqwboth.cjs.map +1 -0
- package/{Autocomplete-E5aSUGVK.js → Autocomplete-Cvf16lFk.js} +59 -38
- package/Autocomplete-Cvf16lFk.js.map +1 -0
- package/{DatePicker-D__RSgs-.js → DatePicker-D5BH4v1p.js} +3 -2
- package/{DatePicker-D__RSgs-.js.map → DatePicker-D5BH4v1p.js.map} +1 -1
- package/{DatePicker-CMcQddi1.cjs → DatePicker-mz7CYtVw.cjs} +3 -2
- package/{DatePicker-CMcQddi1.cjs.map → DatePicker-mz7CYtVw.cjs.map} +1 -1
- package/{DateTimePicker-LeaE716a.js → DateTimePicker-ZCf0Wh4r.js} +6 -2
- package/DateTimePicker-ZCf0Wh4r.js.map +1 -0
- package/{DateTimePicker-BVJGq1A0.cjs → DateTimePicker-ejQDpjgX.cjs} +6 -2
- package/DateTimePicker-ejQDpjgX.cjs.map +1 -0
- package/{Input-BibHlnGN.js → Input-CmvuMwXZ.js} +3 -2
- package/{Input-BibHlnGN.js.map → Input-CmvuMwXZ.js.map} +1 -1
- package/{Input-Bpjw7qwq.cjs → Input-hnQ7g6b7.cjs} +3 -2
- package/{Input-Bpjw7qwq.cjs.map → Input-hnQ7g6b7.cjs.map} +1 -1
- package/{Select-BIUq3ZPy.js → Select-CZ0BiKVN.js} +3 -2
- package/{Select-BIUq3ZPy.js.map → Select-CZ0BiKVN.js.map} +1 -1
- package/{Select-C06gHRqZ.cjs → Select-ZhFf4SBp.cjs} +3 -2
- package/{Select-C06gHRqZ.cjs.map → Select-ZhFf4SBp.cjs.map} +1 -1
- package/{StatusMessage-B3nXpuRl.cjs → StatusMessageContext-BMsbLKRq.cjs} +19 -1
- package/StatusMessageContext-BMsbLKRq.cjs.map +1 -0
- package/{StatusMessage-D0WgSBx7.js → StatusMessageContext-DgYiObYE.js} +21 -3
- package/StatusMessageContext-DgYiObYE.js.map +1 -0
- package/components/Autocomplete/Autocomplete.cjs +1 -1
- package/components/Autocomplete/Autocomplete.d.ts +30 -13
- package/components/Autocomplete/Autocomplete.helpers.d.ts +4 -4
- package/components/Autocomplete/Autocomplete.js +1 -1
- package/components/Autocomplete/_parts/AutocompleteChips.d.ts +7 -6
- package/components/Autocomplete/_parts/AutocompleteOption.d.ts +5 -5
- package/components/Autocomplete/index.d.ts +1 -1
- package/components/DatePicker/DatePicker.cjs +1 -1
- package/components/DatePicker/DatePicker.js +1 -1
- package/components/DateTimePicker/DateTimePicker.cjs +1 -1
- package/components/DateTimePicker/DateTimePicker.d.ts +9 -0
- package/components/DateTimePicker/DateTimePicker.js +1 -1
- package/components/Input/Input.cjs +1 -1
- package/components/Input/Input.js +1 -1
- package/components/Select/Select.cjs +1 -1
- package/components/Select/Select.js +1 -1
- package/components/StatusMessage/StatusMessage.cjs +5 -3
- package/components/StatusMessage/StatusMessage.cjs.map +1 -1
- package/components/StatusMessage/StatusMessage.js +4 -2
- package/components/StatusMessage/index.d.ts +2 -0
- package/components/_shared/resolvePreset.d.ts +9 -5
- package/index.cjs +25 -9
- package/index.cjs.map +1 -1
- package/index.d.ts +4 -4
- package/index.js +13 -9
- package/mui.d.ts +1 -1
- package/package.json +2 -3
- package/resolvePreset-CxTI6_Ln.cjs.map +1 -1
- package/resolvePreset-K6_BfWHD.js.map +1 -1
- package/Autocomplete-Bd3bN4Cw.cjs.map +0 -1
- package/Autocomplete-E5aSUGVK.js.map +0 -1
- package/DateTimePicker-BVJGq1A0.cjs.map +0 -1
- package/DateTimePicker-LeaE716a.js.map +0 -1
- package/README.md +0 -251
- package/StatusMessage-B3nXpuRl.cjs.map +0 -1
- package/StatusMessage-D0WgSBx7.js.map +0 -1
- package/local/affiliations/affiliations.dev.soyfri.com-key.pem +0 -28
- package/local/affiliations/affiliations.dev.soyfri.com.pem +0 -27
- package/local/aficiliaciones/afiliaciones.dev.soyfri.com-key.pem +0 -28
- package/local/aficiliaciones/afiliaciones.dev.soyfri.com.pem +0 -27
- package/local/afiliaciones/afiliaciones.dev.soyfri.com-key.pem +0 -28
- package/local/afiliaciones/afiliaciones.dev.soyfri.com.pem +0 -27
- package/local/root/rootCA-key.pem +0 -40
- package/local/root/rootCA.pem +0 -30
- package/local/soporte/supportweb.dev.soyfri.com-key.pem +0 -28
- package/local/soporte/supportweb.dev.soyfri.com.pem +0 -27
- package/local/support/supportweb.dev.soyfri.com-key.pem +0 -28
- package/local/support/supportweb.dev.soyfri.com.pem +0 -27
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Autocomplete-Cvf16lFk.js","sources":["../src/components/Autocomplete/Autocomplete.sx.ts","../src/components/Autocomplete/Autocomplete.helpers.ts","../src/components/Autocomplete/_parts/AutocompleteOption.tsx","../src/components/Autocomplete/_parts/AutocompleteChips.tsx","../src/components/Autocomplete/_parts/AutocompleteLoader.tsx","../src/components/Autocomplete/Autocomplete.tsx"],"sourcesContent":["import type { SxProps, Theme } from '@mui/material/styles';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport { FIELD_INPUT_PADDING_Y } from '../../theme/tokens';\nimport type { LabelPosition } from './Autocomplete';\n\n/**\n * Builder del sx del Autocomplete. Reutiliza `buildFormFieldSx` y añade\n * los paddings propios del Autocomplete (chips + input interno).\n */\nexport const buildAutocompleteSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): SxProps<Theme> =>\n buildFormFieldSx({\n borderRadius,\n labelPosition,\n extraOutsideSx: {\n // El Autocomplete es el único campo cuyo padding lo pinta MUI con\n // selectores calificados por tamaño (`.MuiOutlinedInput-root.MuiInputBase-sizeSmall`\n // y su descendiente `.MuiAutocomplete-input`). Un selector de menos clases\n // pierde por especificidad — por eso hay que repetir el calificador acá, o\n // el Autocomplete queda ~5px más bajo que Input/Select/pickers.\n '& .MuiOutlinedInput-root, & .MuiOutlinedInput-root.MuiInputBase-sizeSmall': {\n paddingTop: 0,\n paddingBottom: 0,\n },\n\n // La altura la fija el input interno, con el mismo token que el resto.\n '& .MuiOutlinedInput-root .MuiAutocomplete-input, & .MuiOutlinedInput-root.MuiInputBase-sizeSmall .MuiAutocomplete-input':\n {\n paddingTop: FIELD_INPUT_PADDING_Y,\n paddingBottom: FIELD_INPUT_PADDING_Y,\n },\n },\n });\n","import type { SxProps, Theme } from '@mui/material/styles';\nimport type { AutocompleteValueKey, SelectOption } from './Autocomplete';\n\n/** Resuelve un value único a su SelectOption dentro del pool. */\nexport const resolveSingleValue = <TValue,>(\n options: SelectOption<TValue>[],\n value: TValue | null | undefined,\n getKey: (v: TValue) => AutocompleteValueKey,\n): SelectOption<TValue> | null => {\n if (value === null || value === undefined) return null;\n const key = getKey(value);\n return options.find((o) => getKey(o.value) === key) ?? null;\n};\n\n/** Resuelve un array de values a sus SelectOption dentro del pool. */\nexport const resolveMultipleValue = <TValue,>(\n options: SelectOption<TValue>[],\n value: TValue[] | null | undefined,\n getKey: (v: TValue) => AutocompleteValueKey,\n): SelectOption<TValue>[] => {\n if (!Array.isArray(value)) return [];\n const keys = new Set(value.map(getKey));\n return options.filter((o) => keys.has(getKey(o.value)));\n};\n\n/** Merge de sx base + extra del consumer, respetando el contrato de MUI. */\nexport const mergeSx = (\n base: SxProps<Theme>,\n extra?: SxProps<Theme>,\n): SxProps<Theme> => {\n if (!extra) return base;\n return [base, ...(Array.isArray(extra) ? extra : [extra])] as SxProps<Theme>;\n};\n\n/**\n * Compara dos SelectOption por todas sus props (shallow). Se usa para detectar\n * cambios de metadata (p.ej. `label`, `img`) cuando `value` no cambió, para\n * que la estabilización no tape datos frescos del server. Para `value` se\n * compara vía `getKey` (no por `===`), de modo que values objeto con misma\n * identidad lógica pero referencia distinta no rompan la estabilización.\n */\nconst areOptionsShallowEqual = <TValue,>(\n a: SelectOption<TValue>,\n b: SelectOption<TValue>,\n getKey: (v: TValue) => AutocompleteValueKey,\n): boolean => {\n const keysA = Object.keys(a);\n const keysB = Object.keys(b);\n if (keysA.length !== keysB.length) return false;\n return keysA.every((k) => {\n if (k === 'value') return getKey(a.value) === getKey(b.value);\n return a[k] === b[k];\n });\n};\n\n/**\n * Compara dos valores resueltos (single o multiple) estructuralmente para\n * decidir si se puede reusar la referencia previa. Se usa para estabilizar la\n * referencia que se pasa a MUI Autocomplete (MUI compara value por referencia\n * con `!==`, y una nueva referencia — aunque el contenido sea igual — dispara\n * `resetInputValue` y borra el texto mientras el usuario tipea).\n *\n * Comparamos todas las props del SelectOption, no solo `value`, para que un\n * refresh de metadata (label/img/etc.) invalide la referencia estabilizada\n * y la UI muestre los datos actualizados.\n */\nexport const areResolvedValuesEqual = <TValue,>(\n prev: SelectOption<TValue> | SelectOption<TValue>[] | null,\n next: SelectOption<TValue> | SelectOption<TValue>[] | null,\n multiple: boolean,\n getKey: (v: TValue) => AutocompleteValueKey,\n): boolean => {\n if (multiple) {\n if (!Array.isArray(prev) || !Array.isArray(next)) return false;\n if (prev.length !== next.length) return false;\n return prev.every((o, i) => {\n const n = next[i];\n return !!n && areOptionsShallowEqual(o, n, getKey);\n });\n }\n const p = prev as SelectOption<TValue> | null;\n const n = next as SelectOption<TValue> | null;\n if (p === n) return true;\n if (!p || !n) return false;\n return areOptionsShallowEqual(p, n, getKey);\n};\n\n/** Determina si un valor resuelto está vacío (para placeholder/shrink). */\nexport const isResolvedValueEmpty = (\n resolvedValue: unknown,\n multiple: boolean,\n): boolean => {\n if (multiple) {\n return !Array.isArray(resolvedValue) || resolvedValue.length === 0;\n }\n return !resolvedValue;\n};\n","import React from 'react';\nimport type {\n AutocompleteValueKey,\n SelectOption,\n RenderOptionItem,\n} from '../Autocomplete';\n\ninterface AutocompleteOptionProps<TValue = AutocompleteValueKey> {\n liProps: React.HTMLAttributes<HTMLLIElement>;\n option: SelectOption<TValue>;\n customRender?: RenderOptionItem<TValue>;\n}\n\n/**\n * Render por defecto de un `<li>` del dropdown del Autocomplete.\n * MUI lo invoca desde `renderOption={(props, option) => ...}` en el padre.\n *\n * La `key` la maneja el padre (`renderOption` en Autocomplete.tsx). Este\n * componente solo recibe los props restantes del `<li>` para spread.\n */\nexport const AutocompleteOption = <TValue,>({\n liProps,\n option,\n customRender,\n}: AutocompleteOptionProps<TValue>) => {\n return (\n <li {...liProps}>\n {customRender ? customRender(option) : option.label}\n </li>\n );\n};\n\nexport default AutocompleteOption;\n","import { Avatar, Chip } from '@mui/material';\nimport ClearIcon from '@mui/icons-material/Clear';\n\nimport type {\n AutocompleteValueKey,\n SelectOption,\n RenderChipLabel,\n AutocompleteSize,\n} from '../Autocomplete';\n\ninterface AutocompleteChipsProps<TValue = AutocompleteValueKey> {\n value: SelectOption<TValue>[];\n getTagProps: (args: { index: number }) => Record<string, any>;\n size: AutocompleteSize;\n maxChipsToShow: number;\n renderChipLabel?: RenderChipLabel<TValue>;\n /** Key estable del value: React key del chip. Ver `getOptionKey`. */\n getKey: (value: TValue) => AutocompleteValueKey;\n}\n\n/**\n * Render de los chips del Autocomplete en modo multiple.\n * Trunca después de `maxChipsToShow` con un chip \"+N más\".\n * El `getTagProps({ index })` viene de MUI y contiene el handler de delete,\n * la key, etc. — se spreadea tal cual al Chip.\n */\nexport const AutocompleteChips = <TValue,>({\n value,\n getTagProps,\n size,\n maxChipsToShow,\n renderChipLabel,\n getKey,\n}: AutocompleteChipsProps<TValue>) => {\n const displayed = value.slice(0, maxChipsToShow);\n const hidden = value.length - maxChipsToShow;\n\n return (\n <>\n {displayed.map((option, index) => {\n const { key: _ignored, ...tagProps } = getTagProps({ index });\n return (\n <Chip\n key={getKey(option.value)}\n {...tagProps}\n size={size}\n label={renderChipLabel ? renderChipLabel(option) : option.label}\n avatar={option.img ? <Avatar src={option.img} /> : undefined}\n deleteIcon={<ClearIcon />}\n />\n );\n })}\n {hidden > 0 && <Chip size={size} label={`+${hidden} más`} />}\n </>\n );\n};\n\nexport default AutocompleteChips;\n","import React from 'react';\nimport { Box, CircularProgress, Typography } from '@mui/material';\n\n/**\n * Loader por defecto para el `loadingText` del Autocomplete.\n * El consumer puede sobrescribirlo pasando `loadingText` al componente padre.\n */\nexport const AutocompleteLoader: React.FC<{ text?: string }> = ({\n text = 'Cargando...',\n}) => (\n <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>\n <CircularProgress size={16} />\n <Typography variant=\"body2\">{text}</Typography>\n </Box>\n);\n\nexport default AutocompleteLoader;\n","import React, {\n useMemo,\n useRef,\n useState,\n type ReactNode,\n type SyntheticEvent,\n} from 'react';\nimport {\n Autocomplete as MuiAutocomplete,\n TextField,\n type TextFieldProps,\n} from '@mui/material';\nimport { useTheme, type SxProps, type Theme } from '@mui/material/styles';\nimport { Controller, type RegisterOptions } from 'react-hook-form';\n\nimport { buildAutocompleteSx } from './Autocomplete.sx';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\nimport {\n areResolvedValuesEqual,\n isResolvedValueEmpty,\n resolveMultipleValue,\n resolveSingleValue,\n} from './Autocomplete.helpers';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { AutocompleteOption } from './_parts/AutocompleteOption';\nimport { AutocompleteChips } from './_parts/AutocompleteChips';\nimport { AutocompleteLoader } from './_parts/AutocompleteLoader';\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\n/** Key estable usada para comparar values, indexar caches y como React key. */\nexport type AutocompleteValueKey = string | number;\n\nexport interface SelectOption<TValue = AutocompleteValueKey> {\n value: TValue;\n label: string;\n img?: string;\n disabled?: boolean;\n group?: string;\n [key: string]: any; //campos extras que puede tener la opcion\n}\n\nexport type LabelPosition = 'outside' | 'floating';\nexport type AutocompleteSize = 'small' | 'medium';\n\n// ── Render slots ─────────────────────────────────────────────────────────\nexport type RenderOptionItem<TValue = AutocompleteValueKey> = (\n item: SelectOption<TValue>,\n) => ReactNode;\nexport type RenderChipLabel<TValue = AutocompleteValueKey> = (\n item: SelectOption<TValue>,\n) => ReactNode;\nexport type RenderSingleValue<TValue = AutocompleteValueKey> = (\n item: SelectOption<TValue>,\n) => ReactNode;\n\n// ── Props base ───────────────────────────────────────────────────────────\nexport type BaseAutocompleteProps<TValue = AutocompleteValueKey> = {\n label?: string;\n options: SelectOption<TValue>[];\n placeholder?: string;\n multiple?: boolean;\n disabled?: boolean;\n readOnly?: boolean;\n loading?: boolean;\n error?: boolean;\n helperText?: string;\n maxChipsToShow?: number;\n renderOptionItem?: RenderOptionItem<TValue>;\n renderChipLabel?: RenderChipLabel<TValue>;\n /**\n * Renderiza JSX custom como `startAdornment` del input en single mode.\n * Recibe la `SelectOption` seleccionada. Útil para mostrar avatars, iconos,\n * etc. junto al texto del label. En `multiple` no aplica (se usa `renderChipLabel`).\n */\n renderSingleValue?: RenderSingleValue<TValue>;\n /**\n * Extrae una key estable (string | number) desde el `value`. Obligatorio\n * cuando `TValue` es un objeto: se usa para comparar values (`isOptionEqualToValue`,\n * resolución desde el value del form), indexar el cache interno de opciones\n * vistas y como React key en chips/options del dropdown. Para primitivos se\n * puede omitir (default: identidad, o sea `===`).\n */\n getOptionKey?: (value: TValue) => AutocompleteValueKey;\n /** Border radius del input. Default: 10. */\n borderRadius?: number | string;\n /** \"outside\" (default) = label arriba del input; \"floating\" = comportamiento nativo MUI. */\n labelPosition?: LabelPosition;\n /** Tamaño del TextField. Default: 'small'. */\n size?: AutocompleteSize;\n /** Texto cuando no hay coincidencias. */\n noOptionsText?: ReactNode;\n /** Texto cuando está cargando. */\n loadingText?: ReactNode;\n sx?: SxProps<Theme>;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.Autocomplete`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n /** Props para el TextField subyacente. */\n textFieldProps?: Partial<TextFieldProps>;\n\n // ── Búsqueda asíncrona / remota ──────────────────────────────────────\n /** Se dispara cada vez que el usuario escribe. Útil para llamadas a servicios\n * (debounce recomendado en el consumer). */\n onInputChange?: (\n event: SyntheticEvent,\n value: string,\n reason: 'input' | 'reset' | 'clear' | 'blur' | 'selectOption' | 'removeOption',\n ) => void;\n /** Valor controlado del texto de búsqueda. */\n inputValue?: string;\n /** Filtro custom. Para búsqueda remota pasar `(x) => x` y confiar sólo en el servicio. */\n filterOptions?: (\n options: SelectOption<TValue>[],\n state: any,\n ) => SelectOption<TValue>[];\n /** Permite valores arbitrarios (no solo de la lista). */\n freeSolo?: boolean;\n open?: boolean;\n onOpen?: (event: SyntheticEvent) => void;\n onClose?: (event: SyntheticEvent, reason: string) => void;\n};\n\n// ── Variantes discriminadas (RHF vs controlado) ──────────────────────────\nexport interface ControlledAutocompleteProps<TValue = AutocompleteValueKey>\n extends BaseAutocompleteProps<TValue> {\n value: TValue | TValue[] | null;\n onChange: (val: TValue | TValue[] | null) => void;\n name?: string;\n control?: never;\n validation?: never;\n}\n\nexport interface RHFAutocompleteProps<TValue = AutocompleteValueKey>\n extends BaseAutocompleteProps<TValue> {\n name: string;\n // `any` plano (no `Control<any>`): RHF tipa `Control<T>` con generics en\n // posiciones tanto contravariantes como covariantes (ej. `_subjects.state`).\n // Cuando el componente o su uso involucra generics adicionales, TS se\n // confunde narroweando el discriminated union y `Control<any>` no logra\n // absorber `Control<MyForm>` en la comparación estructural profunda. El\n // `any` plano elimina ese ruido. RHF adentro sigue teniendo sus tipos\n // fuertes — solo degradamos la superficie del prop del componente.\n control: any;\n validation?: RegisterOptions;\n /**\n * Side-effect que corre después de que RHF actualiza el form state.\n * Útil para cascadas entre campos. NO reemplaza al handler de RHF.\n */\n onValueChange?: (val: TValue | TValue[] | null) => void;\n value?: never;\n onChange?: never;\n}\n\n// ── API pública final ────────────────────────────────────────────────────\nexport type AutocompleteProps<TValue = AutocompleteValueKey> =\n | ControlledAutocompleteProps<TValue>\n | RHFAutocompleteProps<TValue>;\n\nexport function Autocomplete<TValue = AutocompleteValueKey>(\n props: AutocompleteProps<TValue>,\n) {\n const {\n label,\n options,\n placeholder,\n multiple = false,\n disabled = false,\n readOnly = false,\n loading = false,\n error: errorProp = false,\n helperText,\n maxChipsToShow = 3,\n renderOptionItem,\n renderChipLabel,\n renderSingleValue,\n getOptionKey,\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n size = 'small',\n noOptionsText = 'No hay opciones',\n loadingText,\n sx,\n preset,\n textFieldProps,\n onInputChange,\n inputValue,\n filterOptions,\n freeSolo,\n open,\n onOpen,\n onClose,\n } = props as BaseAutocompleteProps<TValue>;\n\n // Default identidad: para primitivos (string|number) funciona como `===`.\n // Para values objeto, el consumer DEBE pasar `getOptionKey` o la igualdad\n // caerá a referencia (Map/Set agruparían por identidad).\n const getKey = (getOptionKey ??\n ((v: TValue) => v as unknown as AutocompleteValueKey)) as (\n v: TValue,\n ) => AutocompleteValueKey;\n\n // Focus tracking para mostrar placeholder solo cuando el label sube.\n const [isFocused, setIsFocused] = useState(false);\n\n // Cache interno de opciones vistas (indexado por key estable). Crítico para\n // async multiple: cuando `options` cambian por un nuevo search, los items\n // ya seleccionados no desaparecen de los chips porque los recordamos acá.\n const seenOptionsRef = useRef<\n Map<AutocompleteValueKey, SelectOption<TValue>>\n >(new Map());\n for (const opt of options) {\n seenOptionsRef.current.set(getKey(opt.value), opt);\n }\n\n // Pool de opciones para resolver values (merge de options + vistas).\n const resolvePool = useMemo<SelectOption<TValue>[]>(() => {\n const merged = new Map(seenOptionsRef.current);\n for (const opt of options) merged.set(getKey(opt.value), opt);\n return Array.from(merged.values());\n // eslint-disable-next-line react-hooks/exhaustive-deps\n }, [options]);\n\n // Estabiliza la referencia del resolvedValue que pasamos a MUI Autocomplete.\n // MUI compara value con `!==`: una referencia nueva con mismo contenido\n // dispara resetInputValue() y borra el texto que el usuario está escribiendo.\n const prevResolvedRef = useRef<\n SelectOption<TValue>[] | SelectOption<TValue> | null\n >(multiple ? [] : null);\n\n const stabilizeResolved = (\n newVal: SelectOption<TValue>[] | SelectOption<TValue> | null,\n ): SelectOption<TValue>[] | SelectOption<TValue> | null => {\n if (\n areResolvedValuesEqual(prevResolvedRef.current, newVal, multiple, getKey)\n ) {\n return prevResolvedRef.current;\n }\n prevResolvedRef.current = newVal;\n return newVal;\n };\n\n const theme = useTheme();\n const presetSx = resolvePreset('Autocomplete', preset, theme);\n\n // Built-in primero, preset encima (ver Input).\n const mergedSx = [\n buildAutocompleteSx(borderRadius, labelPosition),\n ...(presetSx ? [presetSx] : []),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n const renderAutocomplete = (\n resolvedValue: any,\n handleChange: (event: any, newValue: any) => void,\n onBlur?: () => void,\n inputRef?: React.Ref<any>,\n rhfError?: boolean,\n rhfHelperText?: string,\n ) => {\n const finalError = !!rhfError || !!errorProp;\n const finalHelperText = rhfHelperText || helperText;\n\n const isEmpty = isResolvedValueEmpty(resolvedValue, multiple);\n const showPlaceholder = isEmpty && isFocused && !!placeholder;\n const singleAdornment =\n !multiple && resolvedValue && renderSingleValue\n ? renderSingleValue(resolvedValue as SelectOption<TValue>)\n : null;\n\n return (\n <MuiAutocomplete\n multiple={multiple}\n options={options}\n value={resolvedValue}\n disabled={disabled}\n readOnly={readOnly}\n loading={loading}\n sx={mergedSx}\n freeSolo={freeSolo as any}\n open={open}\n onOpen={onOpen}\n onClose={onClose}\n inputValue={inputValue}\n onInputChange={onInputChange}\n filterOptions={filterOptions as any}\n getOptionLabel={(opt) =>\n typeof opt === 'string' ? opt : (opt?.label ?? '')\n }\n isOptionEqualToValue={(a, b) => {\n if (typeof a === 'string' || typeof b === 'string') return a === b;\n if (!a || !b) return a === b;\n return getKey(a.value) === getKey(b.value);\n }}\n getOptionDisabled={(opt) =>\n typeof opt === 'string' ? false : !!opt?.disabled\n }\n onChange={handleChange}\n onFocus={() => setIsFocused(true)}\n onBlur={() => {\n setIsFocused(false);\n onBlur?.();\n }}\n renderOption={(liProps, option) => {\n // MUI inyecta la `key` dentro de `liProps`. React necesita la key\n // en el elemento más externo que devuelve `renderOption` (acá el\n // wrapper), no en el `<li>` interno. El resto de `liProps` viaja\n // al `<li>`. La key auto-generada por MUI cae a `getOptionLabel`,\n // que colisiona si hay opciones con label duplicado. Usamos la key\n // estable del value para garantizar uniqueness aunque haya labels\n // repetidos.\n const { key: _muiKey, ...liRest } = liProps as React.HTMLAttributes<HTMLLIElement> & {\n key?: React.Key;\n };\n return (\n <AutocompleteOption<TValue>\n key={getKey(option.value)}\n liProps={liRest}\n option={option}\n customRender={renderOptionItem}\n />\n );\n }}\n renderValue={\n multiple\n ? (value, getItemProps) => (\n <AutocompleteChips<TValue>\n value={value as SelectOption<TValue>[]}\n getTagProps={getItemProps}\n size={size}\n maxChipsToShow={maxChipsToShow}\n renderChipLabel={renderChipLabel}\n getKey={getKey}\n />\n )\n : undefined\n }\n noOptionsText={noOptionsText}\n loadingText={loadingText ?? <AutocompleteLoader />}\n renderInput={(params) => {\n const paramsInputLabel = (params as any).InputLabelProps as\n | Record<string, any>\n | undefined;\n const consumerInputLabel =\n (textFieldProps?.slotProps as any)?.inputLabel ??\n (textFieldProps as any)?.InputLabelProps;\n // Para inyectar `singleAdornment` necesitamos pasar `slotProps.input`\n // a TextField, pero `slotProps.input` gana sobre `params.InputProps`\n // (que trae endAdornment con chevron + clear). Por eso, cuando hay\n // adornment custom, mergeamos params.InputProps + lo que el consumer\n // haya pasado por textFieldProps + nuestro startAdornment. Si no hay\n // adornment, no tocamos `slotProps.input` y se preserva el flujo legacy.\n const muiInputProps = (params as any).InputProps as\n | Record<string, any>\n | undefined;\n const consumerInputProps =\n (textFieldProps?.slotProps as any)?.input ??\n (textFieldProps as any)?.InputProps;\n const inputSlot = singleAdornment\n ? {\n ...muiInputProps,\n ...consumerInputProps,\n startAdornment: (\n <>\n {singleAdornment}\n {consumerInputProps?.startAdornment}\n {muiInputProps?.startAdornment}\n </>\n ),\n }\n : undefined;\n\n return (\n // @ts-ignore — Ref<any> type mismatch between @types/react versions in monorepo\n <TextField\n {...params}\n label={label}\n size={size}\n variant=\"outlined\"\n placeholder={showPlaceholder ? placeholder : undefined}\n error={finalError}\n helperText={finalHelperText}\n inputRef={inputRef}\n {...textFieldProps}\n slotProps={{\n ...textFieldProps?.slotProps,\n ...(inputSlot ? { input: inputSlot } : {}),\n inputLabel: {\n ...paramsInputLabel,\n ...consumerInputLabel,\n shrink:\n labelPosition === 'outside'\n ? !isEmpty || isFocused\n : paramsInputLabel?.shrink,\n },\n }}\n />\n );\n }}\n />\n );\n };\n\n //obtiene el primitivo (o el objeto) value desde la opción seleccionada\n const extractValue = (opt: any): TValue | null => {\n if (opt === null || opt === undefined) return null;\n if (typeof opt === 'string') return opt as unknown as TValue;\n return (opt?.value ?? null) as TValue | null;\n };\n\n const handleControlledChange = (_event: any, newValue: any) => {\n const onChange = (props as ControlledAutocompleteProps<TValue>).onChange;\n if (multiple) {\n const values = (newValue ?? [])\n .map((opt: SelectOption<TValue> | string) => extractValue(opt))\n .filter((v: TValue | null): v is TValue => v !== null);\n onChange(values);\n } else {\n onChange(extractValue(newValue));\n }\n };\n\n // --- RHF mode ---\n if ('control' in props && props.control) {\n const { name, control, validation, onValueChange } =\n props as RHFAutocompleteProps<TValue>;\n return (\n <Controller\n name={name}\n control={control}\n rules={validation}\n render={({ field, fieldState: { error: fieldError } }) => {\n const resolvedValue = stabilizeResolved(\n multiple\n ? resolveMultipleValue(resolvePool, field.value, getKey)\n : resolveSingleValue(resolvePool, field.value, getKey),\n );\n\n const handleChange = (_event: any, newValue: any) => {\n if (multiple) {\n const next = (newValue ?? [])\n .map((opt: SelectOption<TValue> | string) => extractValue(opt))\n .filter((v: TValue | null): v is TValue => v !== null);\n field.onChange(next);\n onValueChange?.(next);\n } else {\n const next = extractValue(newValue);\n field.onChange(next);\n onValueChange?.(next);\n }\n };\n\n return renderAutocomplete(\n resolvedValue,\n handleChange,\n field.onBlur,\n field.ref,\n !!fieldError,\n fieldError?.message,\n );\n }}\n />\n );\n }\n\n // --- Controlled mode ---\n const controlledValue = (props as ControlledAutocompleteProps<TValue>).value;\n const resolvedValue = stabilizeResolved(\n multiple\n ? resolveMultipleValue(resolvePool, controlledValue as TValue[], getKey)\n : resolveSingleValue(resolvePool, controlledValue as TValue, getKey),\n );\n\n return renderAutocomplete(resolvedValue, handleControlledChange);\n}\n\n/** Alias de `Autocomplete`. Ambos nombres son equivalentes. */\nexport const AutocompleteSelect = Autocomplete;\n\nexport default Autocomplete;\n"],"names":["n","resolvedValue","MuiAutocomplete"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUO,MAAM,sBAAsB,CACjC,cACA,kBAEA,iBAAiB;AAAA,EACf;AAAA,EACA;AAAA,EACA,gBAAgB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAMd,6EAA6E;AAAA,MAC3E,YAAY;AAAA,MACZ,eAAe;AAAA,IAAA;AAAA;AAAA,IAIjB,2HACE;AAAA,MACE,YAAY;AAAA,MACZ,eAAe;AAAA,IAAA;AAAA,EACjB;AAEN,CAAC;AC/BI,MAAM,qBAAqB,CAChC,SACA,OACA,WACgC;;AAChC,MAAI,UAAU,QAAQ,UAAU,OAAW,QAAO;AAClD,QAAM,MAAM,OAAO,KAAK;AACxB,UAAO,aAAQ,KAAK,CAAC,MAAM,OAAO,EAAE,KAAK,MAAM,GAAG,MAA3C,YAAgD;AACzD;AAGO,MAAM,uBAAuB,CAClC,SACA,OACA,WAC2B;AAC3B,MAAI,CAAC,MAAM,QAAQ,KAAK,UAAU,CAAA;AAClC,QAAM,OAAO,IAAI,IAAI,MAAM,IAAI,MAAM,CAAC;AACtC,SAAO,QAAQ,OAAO,CAAC,MAAM,KAAK,IAAI,OAAO,EAAE,KAAK,CAAC,CAAC;AACxD;AAkBA,MAAM,yBAAyB,CAC7B,GACA,GACA,WACY;AACZ,QAAM,QAAQ,OAAO,KAAK,CAAC;AAC3B,QAAM,QAAQ,OAAO,KAAK,CAAC;AAC3B,MAAI,MAAM,WAAW,MAAM,OAAQ,QAAO;AAC1C,SAA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SAAS;AACvC,UAAM,EAAE,MAAM,SAAS,YAAY,kBACjC;AACF,WACE;AAAA,MAAC;AAAA,MAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA,OAAO;AAAA,QACP,QAAQ,CAAC,EAAE,OAAO,YAAY,EAAE,OAAO,WAAA,QAAmB;AACxD,gBAAMA,iBAAgB;AAAA,YACpB,WACI,qBAAqB,aAAa,MAAM,OAAO,MAAM,IACrD,mBAAmB,aAAa,MAAM,OAAO,MAAM;AAAA,UAAA;AAGzD,gBAAM,eAAe,CAAC,QAAa,aAAkB;AACnD,gBAAI,UAAU;AACZ,oBAAM,QAAQ,8BAAY,CAAA,GACvB,IAAI,CAAC,QAAuC,aAAa,GAAG,CAAC,EAC7D,OAAO,CAAC,MAAkC,MAAM,IAAI;AACvD,oBAAM,SAAS,IAAI;AACnB,6DAAgB;AAAA,YAClB,OAAO;AACL,oBAAM,OAAO,aAAa,QAAQ;AAClC,oBAAM,SAAS,IAAI;AACnB,6DAAgB;AAAA,YAClB;AAAA,UACF;AAEA,iBAAO;AAAA,YACLA;AAAAA,YACA;AAAA,YACA,MAAM;AAAA,YACN,MAAM;AAAA,YACN,CAAC,CAAC;AAAA,YACF,yCAAY;AAAA,UAAA;AAAA,QAEhB;AAAA,MAAA;AAAA,IAAA;AAAA,EAGN;AAGA,QAAM,kBAAmB,MAA8C;AACvE,QAAM,gBAAgB;AAAA,IACpB,WACI,qBAAqB,aAAa,iBAA6B,MAAM,IACrE,mBAAmB,aAAa,iBAA2B,MAAM;AAAA,EAAA;AAGvE,SAAO,mBAAmB,eAAe,sBAAsB;AACjE;AAGO,MAAM,qBAAqB;"}
|
|
@@ -136,7 +136,8 @@ const DatePicker = (_a) => {
|
|
|
136
136
|
const theme = useTheme();
|
|
137
137
|
const presetSx = resolvePreset("DatePicker", preset, theme);
|
|
138
138
|
const mergedSx = [
|
|
139
|
-
|
|
139
|
+
buildDatePickerSx(borderRadius, labelPosition),
|
|
140
|
+
...presetSx ? [presetSx] : [],
|
|
140
141
|
...Array.isArray(sx) ? sx : sx ? [sx] : []
|
|
141
142
|
];
|
|
142
143
|
const finalError = !!validationErrorMessage || !!errorProp;
|
|
@@ -178,4 +179,4 @@ const DatePicker = (_a) => {
|
|
|
178
179
|
export {
|
|
179
180
|
DatePicker as D
|
|
180
181
|
};
|
|
181
|
-
//# sourceMappingURL=DatePicker-
|
|
182
|
+
//# sourceMappingURL=DatePicker-D5BH4v1p.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatePicker-D__RSgs-.js","sources":["../node_modules/dayjs/locale/en-gb.js","../src/components/DatePicker/DatePicker.sx.ts","../src/components/DatePicker/DatePicker.helpers.ts","../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["!function(e,a){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=a(require(\"dayjs\")):\"function\"==typeof define&&define.amd?define([\"dayjs\"],a):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_locale_en_gb=a(e.dayjs)}(this,(function(e){\"use strict\";function a(e){return e&&\"object\"==typeof e&&\"default\"in e?e:{default:e}}var t=a(e),_={name:\"en-gb\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),weekdaysShort:\"Sun_Mon_Tue_Wed_Thu_Fri_Sat\".split(\"_\"),weekdaysMin:\"Su_Mo_Tu_We_Th_Fr_Sa\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),monthsShort:\"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec\".split(\"_\"),weekStart:1,yearStart:4,relativeTime:{future:\"in %s\",past:\"%s ago\",s:\"a few seconds\",m:\"a minute\",mm:\"%d minutes\",h:\"an hour\",hh:\"%d hours\",d:\"a day\",dd:\"%d days\",M:\"a month\",MM:\"%d months\",y:\"a year\",yy:\"%d years\"},formats:{LT:\"HH:mm\",LTS:\"HH:mm:ss\",L:\"DD/MM/YYYY\",LL:\"D MMMM YYYY\",LLL:\"D MMMM YYYY HH:mm\",LLLL:\"dddd, D MMMM YYYY HH:mm\"},ordinal:function(e){var a=[\"th\",\"st\",\"nd\",\"rd\"],t=e%100;return\"[\"+e+(a[(t-20)%10]||a[t]||a[0])+\"]\"}};return t.default.locale(_,null,!0),_}));","import type { SxProps, Theme } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport type { LabelPosition } from './DatePicker';\n\n/**\n * Builder de sx para el DatePicker. Reutiliza `buildFormFieldSx` con\n * `includePickersApi: true` para cubrir tanto la API clásica (MuiInputBase /\n * MuiOutlinedInput) como la nueva (MuiPickersInputBase / MuiPickersOutlinedInput)\n * del DatePicker de MUI X v8.\n */\nexport const buildDatePickerSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): SxProps<Theme> =>\n buildFormFieldSx({\n borderRadius,\n labelPosition,\n includePickersApi: true,\n });\n","import type { DateValidationError } from '@mui/x-date-pickers/models';\n\n/**\n * Traduce el código de error del DatePicker de MUI X a un mensaje en español.\n * Se usa internamente para poblar `helperText` cuando hay error de validación\n * y el consumer no pasó un mensaje propio.\n */\nexport const getDateValidationMessage = (\n error: DateValidationError | null,\n): string => {\n switch (error) {\n case 'minDate':\n case 'maxDate':\n return 'Fecha fuera del rango permitido';\n case 'invalidDate':\n return 'Formato de fecha inválido';\n case 'disableFuture':\n return 'No se permiten fechas futuras';\n case 'disablePast':\n return 'No se permiten fechas pasadas';\n default:\n return '';\n }\n};\n","import React, { useMemo } from 'react';\nimport type { SxProps, Theme } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';\nimport { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';\nimport {\n DatePicker as MuiDatePicker,\n type DatePickerProps as MuiDatePickerProps,\n} from '@mui/x-date-pickers/DatePicker';\nimport { DateValidationError } from '@mui/x-date-pickers/models';\nimport { esES } from '@mui/x-date-pickers/locales';\nimport dayjs, { Dayjs } from 'dayjs';\nimport enGbLocale from 'dayjs/locale/en-gb';\n\nimport { buildDatePickerSx } from './DatePicker.sx';\nimport { getDateValidationMessage } from './DatePicker.helpers';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// Registrar el locale por defecto sin activarlo globalmente. El binding usado\n// (no un side-effect import pelado) evita que el tree-shaking del build de la\n// librería elimine el locale — con solo `import 'dayjs/locale/en-gb'` el chunk\n// publicado lo perdía y los pickers caían al formato 'en' (MM/DD/YYYY).\ndayjs.locale(enGbLocale, undefined, true);\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type LabelPosition = 'outside' | 'floating';\nexport type DatePickerSize = 'small' | 'medium';\n\n// ── Props base ───────────────────────────────────────────────────────────\nexport interface BaseDatePickerProps\n extends Omit<MuiDatePickerProps, 'value' | 'onChange' | 'slotProps'> {\n label?: string;\n minDate?: Dayjs;\n maxDate?: Dayjs;\n disabled?: boolean;\n readOnly?: boolean;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n /** Tamaño del TextField renderizado. Default: 'small' */\n size?: DatePickerSize;\n /** helperText pasado al TextField (se sobrescribe por el error de validación si hay). */\n helperText?: string;\n /** Error external override. */\n error?: boolean;\n /** sx que se mergea al TextField interno del picker. */\n sx?: SxProps<Theme>;\n className?: string;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.DatePicker`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n /** Locale para el adaptador dayjs. Default: 'en-gb'. */\n adapterLocale?: string;\n /** Passthrough a slotProps.textField. */\n textFieldProps?: Record<string, any>;\n /** Passthrough completo a slotProps del MuiDatePicker. */\n slotProps?: MuiDatePickerProps['slotProps'];\n}\n\n// ── API pública ──────────────────────────────────────────────────────────\nexport interface DatePickerProps extends BaseDatePickerProps {\n selectedDate: Dayjs | null;\n onDateChange: (date: Dayjs | null) => void;\n}\n\nexport const DatePicker: React.FC<DatePickerProps> = ({\n label,\n selectedDate,\n onDateChange,\n minDate,\n maxDate,\n disabled,\n readOnly,\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n size = 'small',\n helperText,\n error: errorProp,\n sx,\n className,\n preset,\n adapterLocale = 'en-gb',\n textFieldProps,\n slotProps: slotPropsProp,\n ...rest\n}) => {\n const [validationError, setValidationError] = React.useState<DateValidationError | null>(null);\n\n const validationErrorMessage = useMemo(\n () => getDateValidationMessage(validationError),\n [validationError],\n );\n\n const theme = useTheme();\n const presetSx = resolvePreset('DatePicker', preset, theme);\n\n const mergedSx = [\n ...(presetSx ? [presetSx] : [buildDatePickerSx(borderRadius, labelPosition)]),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n const finalError = !!validationErrorMessage || !!errorProp;\n const finalHelperText = validationErrorMessage || helperText;\n\n return (\n <LocalizationProvider\n dateAdapter={AdapterDayjs}\n adapterLocale={adapterLocale}\n localeText={esES.components.MuiLocalizationProvider.defaultProps.localeText}\n >\n <MuiDatePicker\n label={label}\n value={selectedDate}\n onChange={onDateChange}\n minDate={minDate}\n maxDate={maxDate}\n onError={setValidationError}\n disabled={disabled}\n readOnly={readOnly}\n className={className}\n sx={mergedSx}\n slotProps={{\n ...slotPropsProp,\n textField: {\n fullWidth: true,\n size,\n variant: 'outlined',\n ...(slotPropsProp?.textField as Record<string, any> | undefined),\n ...textFieldProps,\n error: !!finalError,\n helperText: finalHelperText,\n } as any,\n }}\n {...rest}\n />\n </LocalizationProvider>\n );\n};\n\nexport default DatePicker;\n"],"names":["this","e","a","t","dayjs","React","MuiDatePicker"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAC,SAAS,GAAE,GAA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AAa;AAAA,MAEjE,UAAA;AAAA,QAACC;AAAAA,QAAA;AAAA,UACC;AAAA,UACA,OAAO;AAAA,UACP,UAAU;AAAA,UACV;AAAA,UACA;AAAA,UACA,SAAS;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,UACA,IAAI;AAAA,UACJ,WAAW,iCACN,gBADM;AAAA,YAET,WAAW;AAAA,cACT,WAAW;AAAA,cACX;AAAA,cACA,SAAS;AAAA,eACL,+CAAe,YAChB,iBALM;AAAA,cAMT,OAAO,CAAC,CAAC;AAAA,cACT,YAAY;AAAA,YAAA;AAAA,UACd;AAAA,WAEE;AAAA,MAAA;AAAA,IACN;AAAA,EAAA;AAGN;","x_google_ignoreList":[0]}
|
|
1
|
+
{"version":3,"file":"DatePicker-D5BH4v1p.js","sources":["../node_modules/dayjs/locale/en-gb.js","../src/components/DatePicker/DatePicker.sx.ts","../src/components/DatePicker/DatePicker.helpers.ts","../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["!function(e,a){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=a(require(\"dayjs\")):\"function\"==typeof define&&define.amd?define([\"dayjs\"],a):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_locale_en_gb=a(e.dayjs)}(this,(function(e){\"use strict\";function a(e){return e&&\"object\"==typeof e&&\"default\"in e?e:{default:e}}var t=a(e),_={name:\"en-gb\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),weekdaysShort:\"Sun_Mon_Tue_Wed_Thu_Fri_Sat\".split(\"_\"),weekdaysMin:\"Su_Mo_Tu_We_Th_Fr_Sa\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),monthsShort:\"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec\".split(\"_\"),weekStart:1,yearStart:4,relativeTime:{future:\"in %s\",past:\"%s ago\",s:\"a few seconds\",m:\"a minute\",mm:\"%d minutes\",h:\"an hour\",hh:\"%d hours\",d:\"a day\",dd:\"%d days\",M:\"a month\",MM:\"%d months\",y:\"a year\",yy:\"%d years\"},formats:{LT:\"HH:mm\",LTS:\"HH:mm:ss\",L:\"DD/MM/YYYY\",LL:\"D MMMM YYYY\",LLL:\"D MMMM YYYY HH:mm\",LLLL:\"dddd, D MMMM YYYY HH:mm\"},ordinal:function(e){var a=[\"th\",\"st\",\"nd\",\"rd\"],t=e%100;return\"[\"+e+(a[(t-20)%10]||a[t]||a[0])+\"]\"}};return t.default.locale(_,null,!0),_}));","import type { SxProps, Theme } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport type { LabelPosition } from './DatePicker';\n\n/**\n * Builder de sx para el DatePicker. Reutiliza `buildFormFieldSx` con\n * `includePickersApi: true` para cubrir tanto la API clásica (MuiInputBase /\n * MuiOutlinedInput) como la nueva (MuiPickersInputBase / MuiPickersOutlinedInput)\n * del DatePicker de MUI X v8.\n */\nexport const buildDatePickerSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): SxProps<Theme> =>\n buildFormFieldSx({\n borderRadius,\n labelPosition,\n includePickersApi: true,\n });\n","import type { DateValidationError } from '@mui/x-date-pickers/models';\n\n/**\n * Traduce el código de error del DatePicker de MUI X a un mensaje en español.\n * Se usa internamente para poblar `helperText` cuando hay error de validación\n * y el consumer no pasó un mensaje propio.\n */\nexport const getDateValidationMessage = (\n error: DateValidationError | null,\n): string => {\n switch (error) {\n case 'minDate':\n case 'maxDate':\n return 'Fecha fuera del rango permitido';\n case 'invalidDate':\n return 'Formato de fecha inválido';\n case 'disableFuture':\n return 'No se permiten fechas futuras';\n case 'disablePast':\n return 'No se permiten fechas pasadas';\n default:\n return '';\n }\n};\n","import React, { useMemo } from 'react';\nimport type { SxProps, Theme } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';\nimport { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';\nimport {\n DatePicker as MuiDatePicker,\n type DatePickerProps as MuiDatePickerProps,\n} from '@mui/x-date-pickers/DatePicker';\nimport { DateValidationError } from '@mui/x-date-pickers/models';\nimport { esES } from '@mui/x-date-pickers/locales';\nimport dayjs, { Dayjs } from 'dayjs';\nimport enGbLocale from 'dayjs/locale/en-gb';\n\nimport { buildDatePickerSx } from './DatePicker.sx';\nimport { getDateValidationMessage } from './DatePicker.helpers';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// Registrar el locale por defecto sin activarlo globalmente. El binding usado\n// (no un side-effect import pelado) evita que el tree-shaking del build de la\n// librería elimine el locale — con solo `import 'dayjs/locale/en-gb'` el chunk\n// publicado lo perdía y los pickers caían al formato 'en' (MM/DD/YYYY).\ndayjs.locale(enGbLocale, undefined, true);\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type LabelPosition = 'outside' | 'floating';\nexport type DatePickerSize = 'small' | 'medium';\n\n// ── Props base ───────────────────────────────────────────────────────────\nexport interface BaseDatePickerProps\n extends Omit<MuiDatePickerProps, 'value' | 'onChange' | 'slotProps'> {\n label?: string;\n minDate?: Dayjs;\n maxDate?: Dayjs;\n disabled?: boolean;\n readOnly?: boolean;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n /** Tamaño del TextField renderizado. Default: 'small' */\n size?: DatePickerSize;\n /** helperText pasado al TextField (se sobrescribe por el error de validación si hay). */\n helperText?: string;\n /** Error external override. */\n error?: boolean;\n /** sx que se mergea al TextField interno del picker. */\n sx?: SxProps<Theme>;\n className?: string;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.DatePicker`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n /** Locale para el adaptador dayjs. Default: 'en-gb'. */\n adapterLocale?: string;\n /** Passthrough a slotProps.textField. */\n textFieldProps?: Record<string, any>;\n /** Passthrough completo a slotProps del MuiDatePicker. */\n slotProps?: MuiDatePickerProps['slotProps'];\n}\n\n// ── API pública ──────────────────────────────────────────────────────────\nexport interface DatePickerProps extends BaseDatePickerProps {\n selectedDate: Dayjs | null;\n onDateChange: (date: Dayjs | null) => void;\n}\n\nexport const DatePicker: React.FC<DatePickerProps> = ({\n label,\n selectedDate,\n onDateChange,\n minDate,\n maxDate,\n disabled,\n readOnly,\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n size = 'small',\n helperText,\n error: errorProp,\n sx,\n className,\n preset,\n adapterLocale = 'en-gb',\n textFieldProps,\n slotProps: slotPropsProp,\n ...rest\n}) => {\n const [validationError, setValidationError] = React.useState<DateValidationError | null>(null);\n\n const validationErrorMessage = useMemo(\n () => getDateValidationMessage(validationError),\n [validationError],\n );\n\n const theme = useTheme();\n const presetSx = resolvePreset('DatePicker', preset, theme);\n\n // Built-in primero, preset encima (ver Input): el preset complementa el estilo\n // base del paquete, nunca lo sustituye.\n const mergedSx = [\n buildDatePickerSx(borderRadius, labelPosition),\n ...(presetSx ? [presetSx] : []),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n const finalError = !!validationErrorMessage || !!errorProp;\n const finalHelperText = validationErrorMessage || helperText;\n\n return (\n <LocalizationProvider\n dateAdapter={AdapterDayjs}\n adapterLocale={adapterLocale}\n localeText={esES.components.MuiLocalizationProvider.defaultProps.localeText}\n >\n <MuiDatePicker\n label={label}\n value={selectedDate}\n onChange={onDateChange}\n minDate={minDate}\n maxDate={maxDate}\n onError={setValidationError}\n disabled={disabled}\n readOnly={readOnly}\n className={className}\n sx={mergedSx}\n slotProps={{\n ...slotPropsProp,\n textField: {\n fullWidth: true,\n size,\n variant: 'outlined',\n ...(slotPropsProp?.textField as Record<string, any> | undefined),\n ...textFieldProps,\n error: !!finalError,\n helperText: fin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EAAE,IAAI,CAAA;AAAA,EAAC;AAG5C,QAAM,aAAa,CAAC,CAAC,0BAA0B,CAAC,CAAC;AACjD,QAAM,kBAAkB,0BAA0B;AAElD,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,aAAa;AAAA,MACb;AAAA,MACA,YAAY,KAAK,WAAW,wBAAwB,aAAa;AAAA,MAEjE,UAAA;AAAA,QAACC;AAAAA,QAAA;AAAA,UACC;AAAA,UACA,OAAO;AAAA,UACP,UAAU;AAAA,UACV;AAAA,UACA;AAAA,UACA,SAAS;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,UACA,IAAI;AAAA,UACJ,WAAW,iCACN,gBADM;AAAA,YAET,WAAW;AAAA,cACT,WAAW;AAAA,cACX;AAAA,cACA,SAAS;AAAA,eACL,+CAAe,YAChB,iBALM;AAAA,cAMT,OAAO,CAAC,CAAC;AAAA,cACT,YAAY;AAAA,YAAA;AAAA,UACd;AAAA,WAEE;AAAA,MAAA;AAAA,IACN;AAAA,EAAA;AAGN;","x_google_ignoreList":[0]}
|
|
@@ -137,7 +137,8 @@ const DatePicker = (_a) => {
|
|
|
137
137
|
const theme = styles.useTheme();
|
|
138
138
|
const presetSx = resolvePreset.resolvePreset("DatePicker", preset, theme);
|
|
139
139
|
const mergedSx = [
|
|
140
|
-
|
|
140
|
+
buildDatePickerSx(borderRadius, labelPosition),
|
|
141
|
+
...presetSx ? [presetSx] : [],
|
|
141
142
|
...Array.isArray(sx) ? sx : sx ? [sx] : []
|
|
142
143
|
];
|
|
143
144
|
const finalError = !!validationErrorMessage || !!errorProp;
|
|
@@ -177,4 +178,4 @@ const DatePicker = (_a) => {
|
|
|
177
178
|
);
|
|
178
179
|
};
|
|
179
180
|
exports.DatePicker = DatePicker;
|
|
180
|
-
//# sourceMappingURL=DatePicker-
|
|
181
|
+
//# sourceMappingURL=DatePicker-mz7CYtVw.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"DatePicker-CMcQddi1.cjs","sources":["../node_modules/dayjs/locale/en-gb.js","../src/components/DatePicker/DatePicker.sx.ts","../src/components/DatePicker/DatePicker.helpers.ts","../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["!function(e,a){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=a(require(\"dayjs\")):\"function\"==typeof define&&define.amd?define([\"dayjs\"],a):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_locale_en_gb=a(e.dayjs)}(this,(function(e){\"use strict\";function a(e){return e&&\"object\"==typeof e&&\"default\"in e?e:{default:e}}var t=a(e),_={name:\"en-gb\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),weekdaysShort:\"Sun_Mon_Tue_Wed_Thu_Fri_Sat\".split(\"_\"),weekdaysMin:\"Su_Mo_Tu_We_Th_Fr_Sa\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),monthsShort:\"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec\".split(\"_\"),weekStart:1,yearStart:4,relativeTime:{future:\"in %s\",past:\"%s ago\",s:\"a few seconds\",m:\"a minute\",mm:\"%d minutes\",h:\"an hour\",hh:\"%d hours\",d:\"a day\",dd:\"%d days\",M:\"a month\",MM:\"%d months\",y:\"a year\",yy:\"%d years\"},formats:{LT:\"HH:mm\",LTS:\"HH:mm:ss\",L:\"DD/MM/YYYY\",LL:\"D MMMM YYYY\",LLL:\"D MMMM YYYY HH:mm\",LLLL:\"dddd, D MMMM YYYY HH:mm\"},ordinal:function(e){var a=[\"th\",\"st\",\"nd\",\"rd\"],t=e%100;return\"[\"+e+(a[(t-20)%10]||a[t]||a[0])+\"]\"}};return t.default.locale(_,null,!0),_}));","import type { SxProps, Theme } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport type { LabelPosition } from './DatePicker';\n\n/**\n * Builder de sx para el DatePicker. Reutiliza `buildFormFieldSx` con\n * `includePickersApi: true` para cubrir tanto la API clásica (MuiInputBase /\n * MuiOutlinedInput) como la nueva (MuiPickersInputBase / MuiPickersOutlinedInput)\n * del DatePicker de MUI X v8.\n */\nexport const buildDatePickerSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): SxProps<Theme> =>\n buildFormFieldSx({\n borderRadius,\n labelPosition,\n includePickersApi: true,\n });\n","import type { DateValidationError } from '@mui/x-date-pickers/models';\n\n/**\n * Traduce el código de error del DatePicker de MUI X a un mensaje en español.\n * Se usa internamente para poblar `helperText` cuando hay error de validación\n * y el consumer no pasó un mensaje propio.\n */\nexport const getDateValidationMessage = (\n error: DateValidationError | null,\n): string => {\n switch (error) {\n case 'minDate':\n case 'maxDate':\n return 'Fecha fuera del rango permitido';\n case 'invalidDate':\n return 'Formato de fecha inválido';\n case 'disableFuture':\n return 'No se permiten fechas futuras';\n case 'disablePast':\n return 'No se permiten fechas pasadas';\n default:\n return '';\n }\n};\n","import React, { useMemo } from 'react';\nimport type { SxProps, Theme } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';\nimport { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';\nimport {\n DatePicker as MuiDatePicker,\n type DatePickerProps as MuiDatePickerProps,\n} from '@mui/x-date-pickers/DatePicker';\nimport { DateValidationError } from '@mui/x-date-pickers/models';\nimport { esES } from '@mui/x-date-pickers/locales';\nimport dayjs, { Dayjs } from 'dayjs';\nimport enGbLocale from 'dayjs/locale/en-gb';\n\nimport { buildDatePickerSx } from './DatePicker.sx';\nimport { getDateValidationMessage } from './DatePicker.helpers';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// Registrar el locale por defecto sin activarlo globalmente. El binding usado\n// (no un side-effect import pelado) evita que el tree-shaking del build de la\n// librería elimine el locale — con solo `import 'dayjs/locale/en-gb'` el chunk\n// publicado lo perdía y los pickers caían al formato 'en' (MM/DD/YYYY).\ndayjs.locale(enGbLocale, undefined, true);\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type LabelPosition = 'outside' | 'floating';\nexport type DatePickerSize = 'small' | 'medium';\n\n// ── Props base ───────────────────────────────────────────────────────────\nexport interface BaseDatePickerProps\n extends Omit<MuiDatePickerProps, 'value' | 'onChange' | 'slotProps'> {\n label?: string;\n minDate?: Dayjs;\n maxDate?: Dayjs;\n disabled?: boolean;\n readOnly?: boolean;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n /** Tamaño del TextField renderizado. Default: 'small' */\n size?: DatePickerSize;\n /** helperText pasado al TextField (se sobrescribe por el error de validación si hay). */\n helperText?: string;\n /** Error external override. */\n error?: boolean;\n /** sx que se mergea al TextField interno del picker. */\n sx?: SxProps<Theme>;\n className?: string;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.DatePicker`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n /** Locale para el adaptador dayjs. Default: 'en-gb'. */\n adapterLocale?: string;\n /** Passthrough a slotProps.textField. */\n textFieldProps?: Record<string, any>;\n /** Passthrough completo a slotProps del MuiDatePicker. */\n slotProps?: MuiDatePickerProps['slotProps'];\n}\n\n// ── API pública ──────────────────────────────────────────────────────────\nexport interface DatePickerProps extends BaseDatePickerProps {\n selectedDate: Dayjs | null;\n onDateChange: (date: Dayjs | null) => void;\n}\n\nexport const DatePicker: React.FC<DatePickerProps> = ({\n label,\n selectedDate,\n onDateChange,\n minDate,\n maxDate,\n disabled,\n readOnly,\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n size = 'small',\n helperText,\n error: errorProp,\n sx,\n className,\n preset,\n adapterLocale = 'en-gb',\n textFieldProps,\n slotProps: slotPropsProp,\n ...rest\n}) => {\n const [validationError, setValidationError] = React.useState<DateValidationError | null>(null);\n\n const validationErrorMessage = useMemo(\n () => getDateValidationMessage(validationError),\n [validationError],\n );\n\n const theme = useTheme();\n const presetSx = resolvePreset('DatePicker', preset, theme);\n\n const mergedSx = [\n ...(presetSx ? [presetSx] : [buildDatePickerSx(borderRadius, labelPosition)]),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n const finalError = !!validationErrorMessage || !!errorProp;\n const finalHelperText = validationErrorMessage || helperText;\n\n return (\n <LocalizationProvider\n dateAdapter={AdapterDayjs}\n adapterLocale={adapterLocale}\n localeText={esES.components.MuiLocalizationProvider.defaultProps.localeText}\n >\n <MuiDatePicker\n label={label}\n value={selectedDate}\n onChange={onDateChange}\n minDate={minDate}\n maxDate={maxDate}\n onError={setValidationError}\n disabled={disabled}\n readOnly={readOnly}\n className={className}\n sx={mergedSx}\n slotProps={{\n ...slotPropsProp,\n textField: {\n fullWidth: true,\n size,\n variant: 'outlined',\n ...(slotPropsProp?.textField as Record<string, any> | undefined),\n ...textFieldProps,\n error: !!finalError,\n helperText: finalHelperText,\n } as any,\n }}\n {...rest}\n />\n </LocalizationProvider>\n );\n};\n\nexport default DatePicker;\n"],"names":["module","this","e","a","t","buildFormFieldSx","dayjs","FIELD_BORDER_RADIUS","useMemo","useTheme","resolvePreset","jsx","LocalizationProvider","AdapterDayjs","esES","MuiDatePicker"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,MAAC,SAAS,GAAE,GAAE;AAAsD,MAAAA,QAAA,UAAe,EAAE,UAAgB;AAAA,IAA+I,GAAEC,OAAM,SAAS,GAAE;AAAc,eAAS,EAAEC,IAAE;AAAC,eAAOA,MAAG,YAAU,OAAOA,MAAG,aAAYA,KAAEA,KAAE,EAAC,SAAQA,GAAC;AAAA,MAAC;AAAC,UAAI,IAAE,EAAE,CAAC,GAAE,IAAE,EAAC,MAAK,SA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AAAA,UACA;AAAA,UACA,IAAI;AAAA,UACJ,WAAW,iCACN,gBADM;AAAA,YAET,WAAW;AAAA,cACT,WAAW;AAAA,cACX;AAAA,cACA,SAAS;AAAA,eACL,+CAAe,YAChB,iBALM;AAAA,cAMT,OAAO,CAAC,CAAC;AAAA,cACT,YAAY;AAAA,YAAA;AAAA,UACd;AAAA,WAEE;AAAA,MAAA;AAAA,IACN;AAAA,EAAA;AAGN;;","x_google_ignoreList":[0]}
|
|
1
|
+
{"version":3,"file":"DatePicker-mz7CYtVw.cjs","sources":["../node_modules/dayjs/locale/en-gb.js","../src/components/DatePicker/DatePicker.sx.ts","../src/components/DatePicker/DatePicker.helpers.ts","../src/components/DatePicker/DatePicker.tsx"],"sourcesContent":["!function(e,a){\"object\"==typeof exports&&\"undefined\"!=typeof module?module.exports=a(require(\"dayjs\")):\"function\"==typeof define&&define.amd?define([\"dayjs\"],a):(e=\"undefined\"!=typeof globalThis?globalThis:e||self).dayjs_locale_en_gb=a(e.dayjs)}(this,(function(e){\"use strict\";function a(e){return e&&\"object\"==typeof e&&\"default\"in e?e:{default:e}}var t=a(e),_={name:\"en-gb\",weekdays:\"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday\".split(\"_\"),weekdaysShort:\"Sun_Mon_Tue_Wed_Thu_Fri_Sat\".split(\"_\"),weekdaysMin:\"Su_Mo_Tu_We_Th_Fr_Sa\".split(\"_\"),months:\"January_February_March_April_May_June_July_August_September_October_November_December\".split(\"_\"),monthsShort:\"Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec\".split(\"_\"),weekStart:1,yearStart:4,relativeTime:{future:\"in %s\",past:\"%s ago\",s:\"a few seconds\",m:\"a minute\",mm:\"%d minutes\",h:\"an hour\",hh:\"%d hours\",d:\"a day\",dd:\"%d days\",M:\"a month\",MM:\"%d months\",y:\"a year\",yy:\"%d years\"},formats:{LT:\"HH:mm\",LTS:\"HH:mm:ss\",L:\"DD/MM/YYYY\",LL:\"D MMMM YYYY\",LLL:\"D MMMM YYYY HH:mm\",LLLL:\"dddd, D MMMM YYYY HH:mm\"},ordinal:function(e){var a=[\"th\",\"st\",\"nd\",\"rd\"],t=e%100;return\"[\"+e+(a[(t-20)%10]||a[t]||a[0])+\"]\"}};return t.default.locale(_,null,!0),_}));","import type { SxProps, Theme } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport type { LabelPosition } from './DatePicker';\n\n/**\n * Builder de sx para el DatePicker. Reutiliza `buildFormFieldSx` con\n * `includePickersApi: true` para cubrir tanto la API clásica (MuiInputBase /\n * MuiOutlinedInput) como la nueva (MuiPickersInputBase / MuiPickersOutlinedInput)\n * del DatePicker de MUI X v8.\n */\nexport const buildDatePickerSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): SxProps<Theme> =>\n buildFormFieldSx({\n borderRadius,\n labelPosition,\n includePickersApi: true,\n });\n","import type { DateValidationError } from '@mui/x-date-pickers/models';\n\n/**\n * Traduce el código de error del DatePicker de MUI X a un mensaje en español.\n * Se usa internamente para poblar `helperText` cuando hay error de validación\n * y el consumer no pasó un mensaje propio.\n */\nexport const getDateValidationMessage = (\n error: DateValidationError | null,\n): string => {\n switch (error) {\n case 'minDate':\n case 'maxDate':\n return 'Fecha fuera del rango permitido';\n case 'invalidDate':\n return 'Formato de fecha inválido';\n case 'disableFuture':\n return 'No se permiten fechas futuras';\n case 'disablePast':\n return 'No se permiten fechas pasadas';\n default:\n return '';\n }\n};\n","import React, { useMemo } from 'react';\nimport type { SxProps, Theme } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';\nimport { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';\nimport {\n DatePicker as MuiDatePicker,\n type DatePickerProps as MuiDatePickerProps,\n} from '@mui/x-date-pickers/DatePicker';\nimport { DateValidationError } from '@mui/x-date-pickers/models';\nimport { esES } from '@mui/x-date-pickers/locales';\nimport dayjs, { Dayjs } from 'dayjs';\nimport enGbLocale from 'dayjs/locale/en-gb';\n\nimport { buildDatePickerSx } from './DatePicker.sx';\nimport { getDateValidationMessage } from './DatePicker.helpers';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// Registrar el locale por defecto sin activarlo globalmente. El binding usado\n// (no un side-effect import pelado) evita que el tree-shaking del build de la\n// librería elimine el locale — con solo `import 'dayjs/locale/en-gb'` el chunk\n// publicado lo perdía y los pickers caían al formato 'en' (MM/DD/YYYY).\ndayjs.locale(enGbLocale, undefined, true);\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type LabelPosition = 'outside' | 'floating';\nexport type DatePickerSize = 'small' | 'medium';\n\n// ── Props base ───────────────────────────────────────────────────────────\nexport interface BaseDatePickerProps\n extends Omit<MuiDatePickerProps, 'value' | 'onChange' | 'slotProps'> {\n label?: string;\n minDate?: Dayjs;\n maxDate?: Dayjs;\n disabled?: boolean;\n readOnly?: boolean;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n /** Tamaño del TextField renderizado. Default: 'small' */\n size?: DatePickerSize;\n /** helperText pasado al TextField (se sobrescribe por el error de validación si hay). */\n helperText?: string;\n /** Error external override. */\n error?: boolean;\n /** sx que se mergea al TextField interno del picker. */\n sx?: SxProps<Theme>;\n className?: string;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.DatePicker`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n /** Locale para el adaptador dayjs. Default: 'en-gb'. */\n adapterLocale?: string;\n /** Passthrough a slotProps.textField. */\n textFieldProps?: Record<string, any>;\n /** Passthrough completo a slotProps del MuiDatePicker. */\n slotProps?: MuiDatePickerProps['slotProps'];\n}\n\n// ── API pública ──────────────────────────────────────────────────────────\nexport interface DatePickerProps extends BaseDatePickerProps {\n selectedDate: Dayjs | null;\n onDateChange: (date: Dayjs | null) => void;\n}\n\nexport const DatePicker: React.FC<DatePickerProps> = ({\n label,\n selectedDate,\n onDateChange,\n minDate,\n maxDate,\n disabled,\n readOnly,\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n size = 'small',\n helperText,\n error: errorProp,\n sx,\n className,\n preset,\n adapterLocale = 'en-gb',\n textFieldProps,\n slotProps: slotPropsProp,\n ...rest\n}) => {\n const [validationError, setValidationError] = React.useState<DateValidationError | null>(null);\n\n const validationErrorMessage = useMemo(\n () => getDateValidationMessage(validationError),\n [validationError],\n );\n\n const theme = useTheme();\n const presetSx = resolvePreset('DatePicker', preset, theme);\n\n // Built-in primero, preset encima (ver Input): el preset complementa el estilo\n // base del paquete, nunca lo sustituye.\n const mergedSx = [\n buildDatePickerSx(borderRadius, labelPosition),\n ...(presetSx ? [presetSx] : []),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n const finalError = !!validationErrorMessage || !!errorProp;\n const finalHelperText = validationErrorMessage || helperText;\n\n return (\n <LocalizationProvider\n dateAdapter={AdapterDayjs}\n adapterLocale={adapterLocale}\n localeText={esES.components.MuiLocalizationProvider.defaultProps.localeText}\n >\n <MuiDatePicker\n label={label}\n value={selectedDate}\n onChange={onDateChange}\n minDate={minDate}\n maxDate={maxDate}\n onError={setValidationError}\n disabled={disabled}\n readOnly={readOnly}\n className={className}\n sx={mergedSx}\n slotProps={{\n ...slotPropsProp,\n textField: {\n fullWidth: true,\n size,\n variant: 'outlined',\n ...(slotPropsProp?.textField as Record<string, any> | undefined),\n ...textFieldProps,\n error: !!finalError,\n helperText: finalHelperText,\n } as any,\n }}\n {...rest}\n />\n </LocalizationProvider>\n );\n};\n\nexport default DatePicker;\n"],"names":["module","this","e","a","t","buildFormFieldSx","dayjs","FIELD_BORDER_RADIUS","useMemo","useTheme","resolvePreset","js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AAC;AAG5C,QAAM,aAAa,CAAC,CAAC,0BAA0B,CAAC,CAAC;AACjD,QAAM,kBAAkB,0BAA0B;AAElD,SACEC,2BAAAA;AAAAA,IAACC,qBAAAA;AAAAA,IAAA;AAAA,MACC,aAAaC,aAAAA;AAAAA,MACb;AAAA,MACA,YAAYC,QAAAA,KAAK,WAAW,wBAAwB,aAAa;AAAA,MAEjE,UAAAH,2BAAAA;AAAAA,QAACI,aAAAA;AAAAA,QAAA;AAAA,UACC;AAAA,UACA,OAAO;AAAA,UACP,UAAU;AAAA,UACV;AAAA,UACA;AAAA,UACA,SAAS;AAAA,UACT;AAAA,UACA;AAAA,UACA;AAAA,UACA,IAAI;AAAA,UACJ,WAAW,iCACN,gBADM;AAAA,YAET,WAAW;AAAA,cACT,WAAW;AAAA,cACX;AAAA,cACA,SAAS;AAAA,eACL,+CAAe,YAChB,iBALM;AAAA,cAMT,OAAO,CAAC,CAAC;AAAA,cACT,YAAY;AAAA,YAAA;AAAA,UACd;AAAA,WAEE;AAAA,MAAA;AAAA,IACN;AAAA,EAAA;AAGN;;","x_google_ignoreList":[0]}
|
|
@@ -96,6 +96,7 @@ const DateTimePicker = (props) => {
|
|
|
96
96
|
ampm = false,
|
|
97
97
|
viewRenderers,
|
|
98
98
|
timeSteps,
|
|
99
|
+
views,
|
|
99
100
|
textFieldProps,
|
|
100
101
|
slotProps: slotPropsProp
|
|
101
102
|
} = _a, rest = __objRest(_a, [
|
|
@@ -122,6 +123,7 @@ const DateTimePicker = (props) => {
|
|
|
122
123
|
"ampm",
|
|
123
124
|
"viewRenderers",
|
|
124
125
|
"timeSteps",
|
|
126
|
+
"views",
|
|
125
127
|
"textFieldProps",
|
|
126
128
|
"slotProps"
|
|
127
129
|
]);
|
|
@@ -137,7 +139,8 @@ const DateTimePicker = (props) => {
|
|
|
137
139
|
const theme = useTheme();
|
|
138
140
|
const presetSx = resolvePreset("DateTimePicker", preset, theme);
|
|
139
141
|
const mergedSx = [
|
|
140
|
-
|
|
142
|
+
buildDateTimePickerSx(borderRadius, labelPosition),
|
|
143
|
+
...presetSx ? [presetSx] : [],
|
|
141
144
|
...Array.isArray(sx) ? sx : sx ? [sx] : []
|
|
142
145
|
];
|
|
143
146
|
const renderPicker = (value, onChange, onBlur, inputRef, rhfError, rhfHelperText) => {
|
|
@@ -167,6 +170,7 @@ const DateTimePicker = (props) => {
|
|
|
167
170
|
ampm,
|
|
168
171
|
viewRenderers,
|
|
169
172
|
timeSteps,
|
|
173
|
+
views,
|
|
170
174
|
sx: mergedSx,
|
|
171
175
|
slotProps: __spreadProps(__spreadValues({}, slotPropsProp), {
|
|
172
176
|
textField: __spreadProps(__spreadValues(__spreadValues({
|
|
@@ -219,4 +223,4 @@ const DateTimePicker = (props) => {
|
|
|
219
223
|
export {
|
|
220
224
|
DateTimePicker as D
|
|
221
225
|
};
|
|
222
|
-
//# sourceMappingURL=DateTimePicker-
|
|
226
|
+
//# sourceMappingURL=DateTimePicker-ZCf0Wh4r.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DateTimePicker-ZCf0Wh4r.js","sources":["../src/components/DateTimePicker/DateTimePicker.sx.ts","../src/components/DateTimePicker/DateTimePicker.helpers.ts","../src/components/DateTimePicker/DateTimePicker.tsx"],"sourcesContent":["import type { SxProps, Theme } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport type { LabelPosition } from './DateTimePicker';\n\n/**\n * Builder de sx para el DateTimePicker. Mismo patrón que DatePicker.\n * Usa `includePickersApi: true` para soportar la API nueva de MUI X v8.\n */\nexport const buildDateTimePickerSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): SxProps<Theme> =>\n buildFormFieldSx({\n borderRadius,\n labelPosition,\n includePickersApi: true,\n });\n","import type { DateTimeValidationError } from '@mui/x-date-pickers/models';\n\n/**\n * Traduce el error del DateTimePicker a un mensaje en español. Se usa\n * internamente para poblar `helperText` cuando hay error de validación.\n * Cubre tanto errores de fecha (`minDate`, `maxDate`, etc.) como de hora\n * (`minTime`, `maxTime`, `minutesStep`, etc.).\n */\nexport const getDateTimeValidationMessage = (\n error: DateTimeValidationError | null,\n): string => {\n switch (error) {\n case 'minDate':\n case 'maxDate':\n case 'minTime':\n case 'maxTime':\n return 'Fecha/hora fuera del rango permitido';\n case 'invalidDate':\n return 'Formato de fecha/hora inválido';\n case 'disableFuture':\n return 'No se permiten fechas/horas futuras';\n case 'disablePast':\n return 'No se permiten fechas/horas pasadas';\n case 'minutesStep':\n return 'Minutos no válidos para el paso configurado';\n default:\n return '';\n }\n};\n\n/**\n * Construye el `localeText` que MUI acepta para overridear los labels de los\n * botones del popover (Cancel / OK / Clear).\n */\nexport const buildLocaleText = (\n clearButtonText?: string,\n cancelButtonText?: string,\n acceptButtonText?: string,\n): Record<string, string> => {\n const text: Record<string, string> = {};\n if (clearButtonText) text.clearButtonLabel = clearButtonText;\n if (cancelButtonText) text.cancelButtonLabel = cancelButtonText;\n if (acceptButtonText) text.okButtonLabel = acceptButtonText;\n return text;\n};\n","import React, { useMemo } from 'react';\nimport type { SxProps, Theme } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';\nimport { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';\nimport {\n DateTimePicker as MuiDateTimePicker,\n type DateTimePickerProps as MuiDateTimePickerProps,\n} from '@mui/x-date-pickers/DateTimePicker';\nimport type { DateTimeValidationError } from '@mui/x-date-pickers/models';\nimport { esES } from '@mui/x-date-pickers/locales';\nimport { Dayjs } from 'dayjs';\nimport { Controller, type Control, type RegisterOptions } from 'react-hook-form';\n\nimport { buildDateTimePickerSx } from './DateTimePicker.sx';\nimport {\n buildLocaleText,\n getDateTimeValidationMessage,\n} from './DateTimePicker.helpers';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type LabelPosition = 'outside' | 'floating';\nexport type DateTimePickerSize = 'small' | 'medium';\n\n// ── Props base ───────────────────────────────────────────────────────────\nexport interface BaseDateTimePickerProps\n extends Omit<MuiDateTimePickerProps, 'value' | 'onChange' | 'slotProps' | 'format'> {\n label?: string;\n minDateTime?: Dayjs;\n maxDateTime?: Dayjs;\n disabled?: boolean;\n readOnly?: boolean;\n /** Formato de la fecha/hora. Default: 'DD/MM/YYYY HH:mm'. */\n inputFormat?: string;\n /** Border radius del input. Default: 10. */\n borderRadius?: number | string;\n /** \"outside\" (default) o \"floating\". */\n labelPosition?: LabelPosition;\n /** Tamaño del TextField. Default: 'small'. */\n size?: DateTimePickerSize;\n helperText?: string;\n error?: boolean;\n sx?: SxProps<Theme>;\n className?: string;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.DateTimePicker`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n /** Locale del adaptador dayjs. */\n adapterLocale?: string;\n /** Textos de los botones del popover. */\n clearButtonText?: string;\n cancelButtonText?: string;\n acceptButtonText?: string;\n minutesStep?: number;\n minTime?: Dayjs;\n /** Si es true usa formato 12h (AM/PM), false = 24h. Default: false. */\n ampm?: boolean;\n viewRenderers?: MuiDateTimePickerProps['viewRenderers'];\n timeSteps?: MuiDateTimePickerProps['timeSteps'];\n /**\n * Vistas a mostrar en el popover. Default: todas (year, month, day, hours, minutes).\n * Ej: `['hours']` solo permite elegir la hora. `['hours','minutes']` oculta el calendar.\n *\n * Va declarado explícito (y no se hereda del `Omit<MuiDateTimePickerProps>`)\n * porque se desestructura del `props` y se pasa a mano al picker: si sólo\n * viviera en el tipo base caería en el `...rest` y quedaría duplicado.\n */\n views?: MuiDateTimePickerProps['views'];\n textFieldProps?: Record<string, any>;\n /** Passthrough completo a slotProps del MuiDateTimePicker. */\n slotProps?: MuiDateTimePickerProps['slotProps'];\n}\n\n// ── Variantes discriminadas (RHF vs controlado) ──────────────────────────\nexport interface RHFDateTimePickerProps extends BaseDateTimePickerProps {\n name: string;\n // `any` plano (no `Control<any>`): RHF tipa `Control<T>` con generics en\n // posiciones tanto contravariantes como covariantes (ej. `_subjects.state`).\n // Cuando el componente o su uso involucra generics adicionales, TS se\n // confunde narroweando el discriminated union y `Control<any>` no logra\n // absorber `Control<MyForm>` en la comparación estructural profunda. El\n // `any` plano elimina ese ruido. RHF adentro sigue teniendo sus tipos\n // fuertes — solo degradamos la superficie del prop del componente.\n control: any;\n validation?: RegisterOptions;\n /**\n * Side-effect que corre después de que RHF actualiza el form state.\n * Útil para cascadas entre campos. NO reemplaza al handler de RHF.\n */\n onValueChange?: (dateTime: Dayjs | null) => void;\n selectedDateTime?: never;\n onDateTimeChange?: never;\n}\n\nexport interface ControlledDateTimePickerProps extends BaseDateTimePickerProps {\n name?: string;\n control?: never;\n validation?: never;\n selectedDateTime: Dayjs | null;\n onDateTimeChange: (dateTime: Dayjs | null) => void;\n}\n\n// ── API pública final ────────────────────────────────────────────────────\nexport type DateTimePickerProps =\n | RHFDateTimePickerProps\n | ControlledDateTimePickerProps;\n\nexport const DateTimePicker: React.FC<DateTimePickerProps> = (props) => {\n const {\n label,\n minDateTime,\n maxDateTime,\n disabled,\n readOnly,\n inputFormat,\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n size = 'small',\n helperText,\n error: errorProp,\n sx,\n className,\n preset,\n adapterLocale,\n clearButtonText,\n cancelButtonText,\n acceptButtonText,\n minutesStep,\n minTime,\n ampm = false,\n viewRenderers,\n timeSteps,\n views,\n textFieldProps,\n slotProps: slotPropsProp,\n ...rest\n } = props as ControlledDateTimePickerProps & {\n control?: Control<any>;\n validation?: RegisterOptions;\n };\n\n const [validationError, setValidationError] = React.useState<DateTimeValidationError | null>(null);\n\n const validationErrorMessage = useMemo(\n () => getDateTimeValidationMessage(validationError),\n [validationError],\n );\n\n const customLocaleText = useMemo(\n () => buildLocaleText(clearButtonText, cancelButtonText, acceptButtonText),\n [clearButtonText, cancelButtonText, acceptButtonText],\n );\n\n const theme = useTheme();\n const presetSx = resolvePreset('DateTimePicker', preset, theme);\n\n // Built-in primero, preset encima (ver Input).\n const mergedSx = [\n buildDateTimePickerSx(borderRadius, labelPosition),\n ...(presetSx ? [presetSx] : []),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n const renderPicker = (\n value: Dayjs | null,\n onChange: (date: Dayjs | null) => void,\n onBlur?: () => void,\n inputRef?: React.Ref<any>,\n rhfError?: boolean,\n rhfHelperText?: string,\n ) => {\n const finalError = rhfError || !!validationErrorMessage || !!errorProp;\n const finalHelperText = rhfHelperText || validationErrorMessage || helperText;\n\n return (\n <LocalizationProvider\n dateAdapter={AdapterDayjs}\n adapterLocale={adapterLocale}\n localeText={esES.components.MuiLocalizationProvider.defaultProps.localeText}\n >\n <MuiDateTimePicker\n className={className}\n label={label}\n value={value}\n onChange={onChange}\n onError={setValidationError}\n minDateTime={minDateTime}\n maxDateTime={maxDateTime}\n minutesStep={minutesStep}\n disabled={disabled}\n readOnly={readOnly}\n minTime={minTime}\n format={inputFormat ?? 'DD/MM/YYYY HH:mm'}\n ampm={ampm}\n viewRenderers={viewRenderers}\n timeSteps={timeSteps}\n views={views}\n sx={mergedSx}\n slotProps={{\n ...slotPropsProp,\n textField: {\n fullWidth: true,\n size,\n variant: 'outlined',\n // Consumer overrides visuales / de comportamiento opcionales.\n ...(slotPropsProp?.textField as Record<string, any> | undefined),\n ...textFieldProps,\n // Props críticas al final: ganan al consumer para no romper la\n // integración con RHF ni desactivar el visual de error.\n onBlur,\n inputRef,\n error: !!finalError,\n helperText: finalHelperText,\n } as any,\n }}\n localeText={customLocaleText}\n {...rest}\n />\n </LocalizationProvider>\n );\n };\n\n if ('control' in props && props.control) {\n const { name, control, validation, onValueChange } = props as RHFDateTimePickerProps;\n return (\n <Controller\n name={name}\n control={control}\n rules={validation}\n render={({ field, fieldState: { error: fieldError } }) =>\n renderPicker(\n field.value ?? null,\n (next) => {\n field.onChange(next);\n onValueChange?.(next);\n },\n field.onBlur,\n field.ref,\n !!fieldError,\n fieldError?.message,\n )\n }\n />\n );\n }\n\n const { selectedDateTime, onDateTimeChange } = props as ControlledDateTimePickerProps;\n return renderPicker(selectedDateTime, onDateTimeChange);\n};\n\nexport default DateTimePicker;\n"],"names":["React","MuiDateTimePicker","_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,MAAM,wBAAwB,CACnC,cACA,kBAEA,iBAAiB;AAAA,EACf;AAAA,EACA;AAAA,EACA,mBAAmB;AACrB,CAAC;ACTI,MAAM,+BAA+B,CAC1C,UACW;AACX,UAAQ,OAAA;AAAA,IACN,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EAAA;AAEb;AAMO,MAAM,kBAAkB,CAC7B,iBACA,kBACA,qBAC2B;AAC3B,QAAM,OAA+B,CAAA;AACrC,MAAI,sBAAsB,mBAAmB;AAC7C,MAAI,uBAAuB,oBAAoB;AAC/C,MAAI,uBAAuB,gBAAgB;AAC3C,SAAO;AACT;ACoEO,MAAM,iBAAgD,CAAC,UAAU;AACtE,QA4BI,YA3BF;AAAA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,eAAe;AAAA,IACf,gBAAgB;AAAA,IAChB,OAAO;AAAA,IACP;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,OAAO;AAAA,IACP;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW;AA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AAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA,QAAQ,oCAAe;AAAA,YACvB;AAAA,YACA;AAAA,YACA;AAAA,YACA;AAAA,YACA,IAAI;AAAA,YACJ,WAAW,iCACN,gBADM;AAAA,cAET,WAAW;AAAA,gBACT,WAAW;AAAA,gBACX;AAAA,gBACA,SAAS;AAAA,iBAEL,+CAAe,YAChB,iBANM;AAAA;AAAA;AAAA,gBAST;AAAA,gBACA;AAAA,gBACA,OAAO,CAAC,CAAC;AAAA,gBACT,YAAY;AAAA,cAAA;AAAA,YACd;AAAA,YAEF,YAAY;AAAA,aACR;AAAA,QAAA;AAAA,MACN;AAAA,IAAA;AAAA,EAGN;AAEA,MAAI,aAAa,SAAS,MAAM,SAAS;AACvC,UAAM,EAAE,MAAM,SAAS,YAAY,kBAAkB;AACrD,WACE;AAAA,MAAC;AAAA,MAAA;AAAA,QACC;AAAA,QACA;AAAA,QACA,OAAO;AAAA,QACP,QAAQ,CAAC,EAAE,OAAO,YAAY,EAAE,OAAO,WAAA,EAAW;;AAChD;AAAA,aACEC,MAAA,MAAM,UAAN,OAAAA,MAAe;AAAA,YACf,CAAC,SAAS;AACR,oBAAM,SAAS,IAAI;AACnB,6DAAgB;AAAA,YAClB;AAAA,YACA,MAAM;AAAA,YACN,MAAM;AAAA,YACN,CAAC,CAAC;AAAA,YACF,yCAAY;AAAA,UAAA;AAAA;AAAA,MACd;AAAA,IAAA;AAAA,EAIR;AAEA,QAAM,EAAE,kBAAkB,iBAAA,IAAqB;AAC/C,SAAO,aAAa,kBAAkB,gBAAgB;AACxD;"}
|
|
@@ -97,6 +97,7 @@ const DateTimePicker = (props) => {
|
|
|
97
97
|
ampm = false,
|
|
98
98
|
viewRenderers,
|
|
99
99
|
timeSteps,
|
|
100
|
+
views,
|
|
100
101
|
textFieldProps,
|
|
101
102
|
slotProps: slotPropsProp
|
|
102
103
|
} = _a, rest = __objRest(_a, [
|
|
@@ -123,6 +124,7 @@ const DateTimePicker = (props) => {
|
|
|
123
124
|
"ampm",
|
|
124
125
|
"viewRenderers",
|
|
125
126
|
"timeSteps",
|
|
127
|
+
"views",
|
|
126
128
|
"textFieldProps",
|
|
127
129
|
"slotProps"
|
|
128
130
|
]);
|
|
@@ -138,7 +140,8 @@ const DateTimePicker = (props) => {
|
|
|
138
140
|
const theme = styles.useTheme();
|
|
139
141
|
const presetSx = resolvePreset.resolvePreset("DateTimePicker", preset, theme);
|
|
140
142
|
const mergedSx = [
|
|
141
|
-
|
|
143
|
+
buildDateTimePickerSx(borderRadius, labelPosition),
|
|
144
|
+
...presetSx ? [presetSx] : [],
|
|
142
145
|
...Array.isArray(sx) ? sx : sx ? [sx] : []
|
|
143
146
|
];
|
|
144
147
|
const renderPicker = (value, onChange, onBlur, inputRef, rhfError, rhfHelperText) => {
|
|
@@ -168,6 +171,7 @@ const DateTimePicker = (props) => {
|
|
|
168
171
|
ampm,
|
|
169
172
|
viewRenderers,
|
|
170
173
|
timeSteps,
|
|
174
|
+
views,
|
|
171
175
|
sx: mergedSx,
|
|
172
176
|
slotProps: __spreadProps(__spreadValues({}, slotPropsProp), {
|
|
173
177
|
textField: __spreadProps(__spreadValues(__spreadValues({
|
|
@@ -218,4 +222,4 @@ const DateTimePicker = (props) => {
|
|
|
218
222
|
return renderPicker(selectedDateTime, onDateTimeChange);
|
|
219
223
|
};
|
|
220
224
|
exports.DateTimePicker = DateTimePicker;
|
|
221
|
-
//# sourceMappingURL=DateTimePicker-
|
|
225
|
+
//# sourceMappingURL=DateTimePicker-ejQDpjgX.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"DateTimePicker-ejQDpjgX.cjs","sources":["../src/components/DateTimePicker/DateTimePicker.sx.ts","../src/components/DateTimePicker/DateTimePicker.helpers.ts","../src/components/DateTimePicker/DateTimePicker.tsx"],"sourcesContent":["import type { SxProps, Theme } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport type { LabelPosition } from './DateTimePicker';\n\n/**\n * Builder de sx para el DateTimePicker. Mismo patrón que DatePicker.\n * Usa `includePickersApi: true` para soportar la API nueva de MUI X v8.\n */\nexport const buildDateTimePickerSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): SxProps<Theme> =>\n buildFormFieldSx({\n borderRadius,\n labelPosition,\n includePickersApi: true,\n });\n","import type { DateTimeValidationError } from '@mui/x-date-pickers/models';\n\n/**\n * Traduce el error del DateTimePicker a un mensaje en español. Se usa\n * internamente para poblar `helperText` cuando hay error de validación.\n * Cubre tanto errores de fecha (`minDate`, `maxDate`, etc.) como de hora\n * (`minTime`, `maxTime`, `minutesStep`, etc.).\n */\nexport const getDateTimeValidationMessage = (\n error: DateTimeValidationError | null,\n): string => {\n switch (error) {\n case 'minDate':\n case 'maxDate':\n case 'minTime':\n case 'maxTime':\n return 'Fecha/hora fuera del rango permitido';\n case 'invalidDate':\n return 'Formato de fecha/hora inválido';\n case 'disableFuture':\n return 'No se permiten fechas/horas futuras';\n case 'disablePast':\n return 'No se permiten fechas/horas pasadas';\n case 'minutesStep':\n return 'Minutos no válidos para el paso configurado';\n default:\n return '';\n }\n};\n\n/**\n * Construye el `localeText` que MUI acepta para overridear los labels de los\n * botones del popover (Cancel / OK / Clear).\n */\nexport const buildLocaleText = (\n clearButtonText?: string,\n cancelButtonText?: string,\n acceptButtonText?: string,\n): Record<string, string> => {\n const text: Record<string, string> = {};\n if (clearButtonText) text.clearButtonLabel = clearButtonText;\n if (cancelButtonText) text.cancelButtonLabel = cancelButtonText;\n if (acceptButtonText) text.okButtonLabel = acceptButtonText;\n return text;\n};\n","import React, { useMemo } from 'react';\nimport type { SxProps, Theme } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs';\nimport { LocalizationProvider } from '@mui/x-date-pickers/LocalizationProvider';\nimport {\n DateTimePicker as MuiDateTimePicker,\n type DateTimePickerProps as MuiDateTimePickerProps,\n} from '@mui/x-date-pickers/DateTimePicker';\nimport type { DateTimeValidationError } from '@mui/x-date-pickers/models';\nimport { esES } from '@mui/x-date-pickers/locales';\nimport { Dayjs } from 'dayjs';\nimport { Controller, type Control, type RegisterOptions } from 'react-hook-form';\n\nimport { buildDateTimePickerSx } from './DateTimePicker.sx';\nimport {\n buildLocaleText,\n getDateTimeValidationMessage,\n} from './DateTimePicker.helpers';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type LabelPosition = 'outside' | 'floating';\nexport type DateTimePickerSize = 'small' | 'medium';\n\n// ── Props base ───────────────────────────────────────────────────────────\nexport interface BaseDateTimePickerProps\n extends Omit<MuiDateTimePickerProps, 'value' | 'onChange' | 'slotProps' | 'format'> {\n label?: string;\n minDateTime?: Dayjs;\n maxDateTime?: Dayjs;\n disabled?: boolean;\n readOnly?: boolean;\n /** Formato de la fecha/hora. Default: 'DD/MM/YYYY HH:mm'. */\n inputFormat?: string;\n /** Border radius del input. Default: 10. */\n borderRadius?: number | string;\n /** \"outside\" (default) o \"floating\". */\n labelPosition?: LabelPosition;\n /** Tamaño del TextField. Default: 'small'. */\n size?: DateTimePickerSize;\n helperText?: string;\n error?: boolean;\n sx?: SxProps<Theme>;\n className?: string;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.DateTimePicker`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n /** Locale del adaptador dayjs. */\n adapterLocale?: string;\n /** Textos de los botones del popover. */\n clearButtonText?: string;\n cancelButtonText?: string;\n acceptButtonText?: string;\n minutesStep?: number;\n minTime?: Dayjs;\n /** Si es true usa formato 12h (AM/PM), false = 24h. Default: false. */\n ampm?: boolean;\n viewRenderers?: MuiDateTimePickerProps['viewRenderers'];\n timeSteps?: MuiDateTimePickerProps['timeSteps'];\n /**\n * Vistas a mostrar en el popover. Default: todas (year, month, day, hours, minutes).\n * Ej: `['hours']` solo permite elegir la hora. `['hours','minutes']` oculta el calendar.\n *\n * Va declarado explícito (y no se hereda del `Omit<MuiDateTimePickerProps>`)\n * porque se desestructura del `props` y se pasa a mano al picker: si sólo\n * viviera en el tipo base caería en el `...rest` y quedaría duplicado.\n */\n views?: MuiDateTimePickerProps['views'];\n textFieldProps?: Record<string, any>;\n /** Passthrough completo a slotProps del MuiDateTimePicker. */\n slotProps?: MuiDateTimePickerProps['slotProps'];\n}\n\n// ── Variantes discriminadas (RHF vs controlado) ──────────────────────────\nexport interface RHFDateTimePickerProps extends BaseDateTimePickerProps {\n name: string;\n // `any` plano (no `Control<any>`): RHF tipa `Control<T>` con generics en\n // posiciones tanto contravariantes como covariantes (ej. `_subjects.state`).\n // Cuando el componente o su uso involucra generics adicionales, TS se\n // confunde narroweando el discriminated union y `Control<any>` no logra\n // absorber `Control<MyForm>` en la comparación estructural profunda. El\n // `any` plano elimina ese ruido. RHF adentro sigue teniendo sus tipos\n // fuertes — solo degradamos la superficie del prop del componente.\n control: any;\n validation?: RegisterOptions;\n /**\n * Side-effect que corre después de que RHF actualiza el form state.\n * Útil para cascadas entre campos. NO reemplaza al handler de RHF.\n */\n onValueChange?: (dateTime: Dayjs | null) => void;\n selectedDateTime?: never;\n onDateTimeChange?: never;\n}\n\nexport interface ControlledDateTimePickerProps extends BaseDateTimePickerProps {\n name?: string;\n control?: never;\n validation?: never;\n selectedDateTime: Dayjs | null;\n onDateTimeChange: (dateTime: Dayjs | null) => void;\n}\n\n// ── API pública final ────────────────────────────────────────────────────\nexport type DateTimePickerProps =\n | RHFDateTimePickerProps\n | ControlledDateTimePickerProps;\n\nexport const DateTimePicker: React.FC<DateTimePickerProps> = (props) => {\n const {\n label,\n minDateTime,\n maxDateTime,\n disabled,\n readOnly,\n inputFormat,\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n size = 'small',\n helperText,\n error: errorProp,\n sx,\n className,\n preset,\n adapterLocale,\n clearButtonText,\n cancelButtonText,\n acceptButtonText,\n minutesStep,\n minTime,\n ampm = false,\n viewRenderers,\n timeSteps,\n views,\n textFieldProps,\n slotProps: slotPropsProp,\n ...rest\n } = props as ControlledDateTimePickerProps & {\n control?: Control<any>;\n validation?: RegisterOptions;\n };\n\n const [validationError, setValidationError] = React.useState<DateTimeValidationError | null>(null);\n\n const validationErrorMessage = useMemo(\n () => getDateTimeValidationMessage(validationError),\n [validationError],\n );\n\n const customLocaleText = useMemo(\n () => buildLocaleText(clearButtonText, cancelButtonText, acceptButtonText),\n [clearButtonText, cancelButtonText, acceptButtonText],\n );\n\n const theme = useTheme();\n const presetSx = resolvePreset('DateTimePicker', preset, theme);\n\n // Built-in primero, preset encima (ver Input).\n const mergedSx = [\n buildDateTimePickerSx(borderRadius, labelPosition),\n ...(presetSx ? [presetSx] : []),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n const renderPicker = (\n value: Dayjs | null,\n onChange: (date: Dayjs | null) => void,\n onBlur?: () => void,\n inputRef?: React.Ref<any>,\n rhfError?: boolean,\n rhfHelperText?: string,\n ) => {\n const finalError = rhfError || !!validationErrorMessage || !!errorProp;\n const finalHelperText = rhfHelperText || validationErrorMessage || helperText;\n\n return (\n <LocalizationProvider\n dateAdapter={AdapterDayjs}\n adapterLocale={adapterLocale}\n localeText={esES.components.MuiLocalizationProvider.defaultProps.localeText}\n >\n <MuiDateTimePicker\n className={className}\n label={label}\n value={value}\n onChange={onChange}\n onError={setValidationError}\n minDateTime={minDateTime}\n maxDateTime={maxDateTime}\n minutesStep={minutesStep}\n disabled={disabled}\n readOnly={readOnly}\n minTime={minTime}\n format={inputFormat ?? 'DD/MM/YYYY HH:mm'}\n ampm={ampm}\n viewRenderers={viewRenderers}\n timeSteps={timeSteps}\n views={views}\n sx={mergedSx}\n slotProps={{\n ...slotPropsProp,\n textField: {\n fullWidth: true,\n size,\n variant: 'outlined',\n // Consumer overrides visuales / de comportamiento opcionales.\n ...(slotPropsProp?.textField as Record<string, any> | undefined),\n ...textFieldProps,\n // Props críticas al final: ganan al consumer para no romper la\n // integración con RHF ni desactivar el visual de error.\n onBlur,\n inputRef,\n error: !!finalError,\n helperText: finalHelperText,\n } as any,\n }}\n localeText={customLocaleText}\n {...rest}\n />\n </LocalizationProvider>\n );\n };\n\n if ('control' in props && props.control) {\n const { name, control, validation, onValueChange } = props as RHFDateTimePickerProps;\n return (\n <Controller\n name={name}\n control={control}\n rules={validation}\n render={({ field, fieldState: { error: fieldError } }) =>\n renderPicker(\n field.value ?? null,\n (next) => {\n field.onChange(next);\n onValueChange?.(next);\n },\n field.onBlur,\n field.ref,\n !!fieldError,\n fieldError?.message,\n )\n }\n />\n );\n }\n\n const { selectedDateTime, onDateTimeChange } = props as ControlledDateTimePickerProps;\n return renderPicker(selectedDateTime, onDateTimeChange);\n};\n\nexport default DateTimePicker;\n"],"names":["buildFormFieldSx","FIELD_BORDER_RADIUS","useMemo","useTheme","resolvePreset","jsx","LocalizationProvider","AdapterDayjs","esES","MuiDateTimePicker","Controller","_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,MAAM,wBAAwB,CACnC,cACA,kBAEAA,8BAAiB;AAAA,EACf;AAAA,EACA;AAAA,EACA,mBAAmB;AACrB,CAAC;ACTI,MAAM,+BAA+B,CAC1C,UACW;AACX,UAAQ,OAAA;AAAA,IACN,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EAAA;AAEb;AAMO,MAAM,kBAAkB,CAC7B,iBACA,kBACA,qBAC2B;AAC3B,QAAM,OAA+B,CAAA;AACrC,MAAI,sBAAsB,mBA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AO,WAAA,EAAW;;AAChD;AAAA,aACEC,MAAA,MAAM,UAAN,OAAAA,MAAe;AAAA,YACf,CAAC,SAAS;AACR,oBAAM,SAAS,IAAI;AACnB,6DAAgB;AAAA,YAClB;AAAA,YACA,MAAM;AAAA,YACN,MAAM;AAAA,YACN,CAAC,CAAC;AAAA,YACF,yCAAY;AAAA,UAAA;AAAA;AAAA,MACd;AAAA,IAAA;AAAA,EAIR;AAEA,QAAM,EAAE,kBAAkB,iBAAA,IAAqB;AAC/C,SAAO,aAAa,kBAAkB,gBAAgB;AACxD;;"}
|
|
@@ -127,7 +127,8 @@ const Input = (props) => {
|
|
|
127
127
|
endAdornment
|
|
128
128
|
);
|
|
129
129
|
const mergedSx = [
|
|
130
|
-
|
|
130
|
+
buildInputSx(borderRadius, labelPosition),
|
|
131
|
+
...presetSx ? [presetSx] : [],
|
|
131
132
|
...Array.isArray(sx) ? sx : sx ? [sx] : []
|
|
132
133
|
];
|
|
133
134
|
if ("control" in props && props.control) {
|
|
@@ -190,4 +191,4 @@ const Input = (props) => {
|
|
|
190
191
|
export {
|
|
191
192
|
Input as I
|
|
192
193
|
};
|
|
193
|
-
//# sourceMappingURL=Input-
|
|
194
|
+
//# sourceMappingURL=Input-CmvuMwXZ.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Input-BibHlnGN.js","sources":["../src/components/Input/Input.helpers.ts","../src/components/Input/Input.sx.ts","../src/components/Input/Input.tsx"],"sourcesContent":["import type { InputHTMLAttributes, ReactNode } from 'react';\nimport type { TextFieldProps } from '@mui/material';\nimport type { InputType } from './Input';\n\n/**\n * Convierte el valor raw del evento al tipo apropiado.\n * Para type=\"number\" intenta parsear a número; si falla, devuelve el raw\n * (permite estados intermedios como \"\" o \"-\" mientras el usuario tipea).\n */\nexport const parseValue = (raw: string, type: InputType): string | number => {\n if (type !== 'number') return raw;\n if (raw === '' || raw === '-') return raw;\n const n = parseFloat(raw);\n return isNaN(n) ? raw : n;\n};\n\n/**\n * Construye los slotProps del TextField consolidando htmlInput + inputLabel.\n * Maneja los atributos min/max cuando type=\"number\", maxLength y readOnly.\n */\nexport const buildSlotProps = (\n type: InputType,\n min: number | undefined,\n max: number | undefined,\n maxLength: number | undefined,\n customSlotProps: TextFieldProps['slotProps'],\n customInputProps: InputHTMLAttributes<HTMLInputElement> | undefined,\n readOnly?: boolean,\n startAdornment?: ReactNode,\n endAdornment?: ReactNode,\n): TextFieldProps['slotProps'] => {\n const numberAttrs =\n type === 'number'\n ? { min: min ?? Number.NEGATIVE_INFINITY, ...(max !== undefined && { max }) }\n : {};\n\n // Atajos `startAdornment`/`endAdornment` → slot `input` (OutlinedInput).\n // Lo que el consumidor pase en `slotProps.input` gana (no lo pisamos).\n const customInputSlot = (customSlotProps as any)?.input;\n const inputSlot = {\n ...(startAdornment !== undefined && { startAdornment }),\n ...(endAdornment !== undefined && { endAdornment }),\n ...customInputSlot,\n };\n const hasInputSlot = Object.keys(inputSlot).length > 0;\n\n return {\n ...customSlotProps,\n ...(hasInputSlot && { input: inputSlot }),\n htmlInput: {\n ...customInputProps,\n ...(customSlotProps as any)?.htmlInput,\n ...numberAttrs,\n ...(maxLength !== undefined && { maxLength }),\n ...(readOnly && { readOnly: true }),\n },\n // Dejamos que MUI maneje el shrink nativamente (animación inside → up).\n // El consumidor puede forzar shrink con slotProps.inputLabel.shrink=true si lo necesita.\n inputLabel: {\n ...(customSlotProps as any)?.inputLabel,\n },\n };\n};\n","import type { TextFieldProps } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport { FIELD_INPUT_PADDING_Y } from '../../theme/tokens';\nimport type { LabelPosition } from './Input';\n\n/**\n * Builder de sx para el Input. Usa el builder compartido\n * `buildFormFieldSx` y añade overrides específicos de TextField\n * (padding del input base, filled, standard).\n */\nexport const buildInputSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): TextFieldProps['sx'] => {\n const radius = typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius;\n\n return buildFormFieldSx({\n borderRadius,\n labelPosition,\n extraOutsideSx: {\n // El padding vertical del input base lo fija `buildFormFieldSx`\n // (misma altura para los cinco campos). Acá solo van las variantes.\n\n // Filled: quitar el padding-top reservado para el label flotante dentro.\n '& .MuiFilledInput-root': {\n paddingTop: 0,\n borderRadius: `${radius} ${radius} 0 0`,\n },\n '& .MuiFilledInput-input': {\n paddingTop: FIELD_INPUT_PADDING_Y,\n },\n\n // Standard: quitar el margin-top reservado para el label flotante.\n '& .MuiInput-root': {\n marginTop: 0,\n },\n },\n });\n};\n","import { TextField, type TextFieldProps } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { Controller, type Control, type RegisterOptions } from 'react-hook-form';\n\nimport { parseValue, buildSlotProps } from './Input.helpers';\nimport { buildInputSx } from './Input.sx';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type InputType =\n | 'text' | 'number' | 'email' | 'password' | 'tel'\n | 'url' | 'search' | 'date' | 'datetime-local'\n | 'month' | 'week' | 'time' | 'color';\n\nexport type LabelPosition = 'outside' | 'floating';\n\n// ── Props base (todo lo común entre RHF y controlado) ────────────────────\nexport interface BaseInputProps\n extends Omit<TextFieldProps, 'value' | 'onChange' | 'type'> {\n type?: InputType;\n min?: number;\n max?: number;\n maxLength?: number;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n readOnly?: boolean;\n /** Contenido al inicio del input (ej. icono de búsqueda). Atajo de `slotProps.input.startAdornment`. */\n startAdornment?: React.ReactNode;\n /** Contenido al final del input (ej. botón clear). Atajo de `slotProps.input.endAdornment`. */\n endAdornment?: React.ReactNode;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.Input`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n}\n\n// ── Variantes discriminadas (RHF vs controlado) ──────────────────────────\nexport interface RHFInputProps extends BaseInputProps {\n name: string;\n // `any` plano (no `Control<any>`): RHF tipa `Control<T>` con generics en\n // posiciones tanto contravariantes como covariantes (ej. `_subjects.state`).\n // Cuando el componente o su uso involucra generics adicionales, TS se\n // confunde narroweando el discriminated union y `Control<any>` no logra\n // absorber `Control<MyForm>` en la comparación estructural profunda. El\n // `any` plano elimina ese ruido. RHF adentro sigue teniendo sus tipos\n // fuertes — solo degradamos la superficie del prop del componente.\n control: any;\n validation?: RegisterOptions;\n /**\n * Side-effect que corre después de que RHF actualiza el form state.\n * Útil para cascadas entre campos (ej. reset de municipio al cambiar\n * departamento). NO reemplaza al handler de RHF.\n */\n onValueChange?: (value: string | number) => void;\n value?: never;\n onChange?: never;\n}\n\nexport interface ControlledInputProps extends BaseInputProps {\n name?: string;\n control?: never;\n validation?: never;\n value: string | number;\n onChange: (value: string | number) => void;\n}\n\n// ── API pública final ────────────────────────────────────────────────────\nexport type InputProps = RHFInputProps | ControlledInputProps;\n\nexport const Input: React.FC<InputProps> = (props) => {\n const {\n type = 'text',\n variant = 'outlined',\n size = 'small',\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n preset,\n min,\n max,\n maxLength,\n readOnly,\n inputProps,\n slotProps,\n startAdornment,\n endAdornment,\n sx,\n onBlur,\n ...rest\n } = props as ControlledInputProps & {\n control?: Control<any>;\n validation?: RegisterOptions;\n };\n\n const theme = useTheme();\n const presetSx = resolvePreset('Input', preset, theme);\n\n const finalSlotProps = buildSlotProps(\n type,\n min,\n max,\n maxLength,\n slotProps,\n inputProps,\n readOnly,\n startAdornment,\n endAdornment,\n );\n const mergedSx = [\n ...(presetSx ? [presetSx] : [buildInputSx(borderRadius, labelPosition)]),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n if ('control' in props && props.control) {\n const { name, control, validation, onValueChange } = props as RHFInputProps;\n return (\n <Controller\n name={name}\n control={control}\n rules={validation}\n render={({ field, fieldState: { error } }) => (\n <TextField\n fullWidth\n {...rest}\n name={field.name}\n value={field.value ?? ''}\n onChange={(e) => {\n const parsed = parseValue(e.target.value, type);\n field.onChange(parsed);\n onValueChange?.(parsed);\n }}\n onBlur={(e) => {\n field.onBlur();\n onBlur?.(e);\n }}\n inputRef={field.ref}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n error={!!error || rest.error}\n helperText={error?.message ?? rest.helperText}\n />\n )}\n />\n );\n }\n\n const { value, onChange } = props as ControlledInputProps;\n return (\n <TextField\n fullWidth\n {...rest}\n value={value ?? ''}\n onChange={(e) => onChange(parseValue(e.target.value, type))}\n onBlur={onBlur}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n />\n );\n};\n\nexport default Input;\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,MAAM,aAAa,CAAC,KAAa,SAAqC;AAC3E,MAAI,SAAS,SAAU,QAAO;AAC9B,MAAI,QAAQ,MAAM,QAAQ,IAAK,QAAO;AACtC,QAAM,IAAI,WAAW,GAAG;AACxB,SAAO,MAAM,CAAC,IAAI,MAAM;AAC1B;AAMO,MAAM,iBAAiB,CAC5B,MACA,KACA,KACA,WACA,iBACA,kBACA,UACA,gBACA,iBACgC;AAChC,QAAM,cACJ,SAAS,WACL,iBAAE,KAAK,oBAAO,OAAO,qBAAuB,QAAQ,UAAa,EAAE,IAAA,KACnE,CAAA;AAIN,QAAM,kBAAmB,mDAAyB;AAClD,QAAM,YAAY,iDACZ,mBAAmB,UAAa,EAAE,eAAA,IAClC,iBAAiB,UAAa,EAAE,aAAA,IACjC;AAEL,QAAM,eAAe,OAAO,KAAK,SAAS,EAAE,SAAS;AAErD,SAAO,gDACF,kBACC,gBAAgB,EAAE,OAAO,UAAA,IAFxB;AAA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AAAA,MACA,WAAW;AAAA,MACX,IAAI;AAAA,IAAA;AAAA,EAAA;AAGV;"}
|
|
1
|
+
{"version":3,"file":"Input-CmvuMwXZ.js","sources":["../src/components/Input/Input.helpers.ts","../src/components/Input/Input.sx.ts","../src/components/Input/Input.tsx"],"sourcesContent":["import type { InputHTMLAttributes, ReactNode } from 'react';\nimport type { TextFieldProps } from '@mui/material';\nimport type { InputType } from './Input';\n\n/**\n * Convierte el valor raw del evento al tipo apropiado.\n * Para type=\"number\" intenta parsear a número; si falla, devuelve el raw\n * (permite estados intermedios como \"\" o \"-\" mientras el usuario tipea).\n */\nexport const parseValue = (raw: string, type: InputType): string | number => {\n if (type !== 'number') return raw;\n if (raw === '' || raw === '-') return raw;\n const n = parseFloat(raw);\n return isNaN(n) ? raw : n;\n};\n\n/**\n * Construye los slotProps del TextField consolidando htmlInput + inputLabel.\n * Maneja los atributos min/max cuando type=\"number\", maxLength y readOnly.\n */\nexport const buildSlotProps = (\n type: InputType,\n min: number | undefined,\n max: number | undefined,\n maxLength: number | undefined,\n customSlotProps: TextFieldProps['slotProps'],\n customInputProps: InputHTMLAttributes<HTMLInputElement> | undefined,\n readOnly?: boolean,\n startAdornment?: ReactNode,\n endAdornment?: ReactNode,\n): TextFieldProps['slotProps'] => {\n const numberAttrs =\n type === 'number'\n ? { min: min ?? Number.NEGATIVE_INFINITY, ...(max !== undefined && { max }) }\n : {};\n\n // Atajos `startAdornment`/`endAdornment` → slot `input` (OutlinedInput).\n // Lo que el consumidor pase en `slotProps.input` gana (no lo pisamos).\n const customInputSlot = (customSlotProps as any)?.input;\n const inputSlot = {\n ...(startAdornment !== undefined && { startAdornment }),\n ...(endAdornment !== undefined && { endAdornment }),\n ...customInputSlot,\n };\n const hasInputSlot = Object.keys(inputSlot).length > 0;\n\n return {\n ...customSlotProps,\n ...(hasInputSlot && { input: inputSlot }),\n htmlInput: {\n ...customInputProps,\n ...(customSlotProps as any)?.htmlInput,\n ...numberAttrs,\n ...(maxLength !== undefined && { maxLength }),\n ...(readOnly && { readOnly: true }),\n },\n // Dejamos que MUI maneje el shrink nativamente (animación inside → up).\n // El consumidor puede forzar shrink con slotProps.inputLabel.shrink=true si lo necesita.\n inputLabel: {\n ...(customSlotProps as any)?.inputLabel,\n },\n };\n};\n","import type { TextFieldProps } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport { FIELD_INPUT_PADDING_Y } from '../../theme/tokens';\nimport type { LabelPosition } from './Input';\n\n/**\n * Builder de sx para el Input. Usa el builder compartido\n * `buildFormFieldSx` y añade overrides específicos de TextField\n * (padding del input base, filled, standard).\n */\nexport const buildInputSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): TextFieldProps['sx'] => {\n const radius = typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius;\n\n return buildFormFieldSx({\n borderRadius,\n labelPosition,\n extraOutsideSx: {\n // El padding vertical del input base lo fija `buildFormFieldSx`\n // (misma altura para los cinco campos). Acá solo van las variantes.\n\n // Filled: quitar el padding-top reservado para el label flotante dentro.\n '& .MuiFilledInput-root': {\n paddingTop: 0,\n borderRadius: `${radius} ${radius} 0 0`,\n },\n '& .MuiFilledInput-input': {\n paddingTop: FIELD_INPUT_PADDING_Y,\n },\n\n // Standard: quitar el margin-top reservado para el label flotante.\n '& .MuiInput-root': {\n marginTop: 0,\n },\n },\n });\n};\n","import { TextField, type TextFieldProps } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { Controller, type Control, type RegisterOptions } from 'react-hook-form';\n\nimport { parseValue, buildSlotProps } from './Input.helpers';\nimport { buildInputSx } from './Input.sx';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type InputType =\n | 'text' | 'number' | 'email' | 'password' | 'tel'\n | 'url' | 'search' | 'date' | 'datetime-local'\n | 'month' | 'week' | 'time' | 'color';\n\nexport type LabelPosition = 'outside' | 'floating';\n\n// ── Props base (todo lo común entre RHF y controlado) ────────────────────\nexport interface BaseInputProps\n extends Omit<TextFieldProps, 'value' | 'onChange' | 'type'> {\n type?: InputType;\n min?: number;\n max?: number;\n maxLength?: number;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n readOnly?: boolean;\n /** Contenido al inicio del input (ej. icono de búsqueda). Atajo de `slotProps.input.startAdornment`. */\n startAdornment?: React.ReactNode;\n /** Contenido al final del input (ej. botón clear). Atajo de `slotProps.input.endAdornment`. */\n endAdornment?: React.ReactNode;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.Input`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n}\n\n// ── Variantes discriminadas (RHF vs controlado) ──────────────────────────\nexport interface RHFInputProps extends BaseInputProps {\n name: string;\n // `any` plano (no `Control<any>`): RHF tipa `Control<T>` con generics en\n // posiciones tanto contravariantes como covariantes (ej. `_subjects.state`).\n // Cuando el componente o su uso involucra generics adicionales, TS se\n // confunde narroweando el discriminated union y `Control<any>` no logra\n // absorber `Control<MyForm>` en la comparación estructural profunda. El\n // `any` plano elimina ese ruido. RHF adentro sigue teniendo sus tipos\n // fuertes — solo degradamos la superficie del prop del componente.\n control: any;\n validation?: RegisterOptions;\n /**\n * Side-effect que corre después de que RHF actualiza el form state.\n * Útil para cascadas entre campos (ej. reset de municipio al cambiar\n * departamento). NO reemplaza al handler de RHF.\n */\n onValueChange?: (value: string | number) => void;\n value?: never;\n onChange?: never;\n}\n\nexport interface ControlledInputProps extends BaseInputProps {\n name?: string;\n control?: never;\n validation?: never;\n value: string | number;\n onChange: (value: string | number) => void;\n}\n\n// ── API pública final ────────────────────────────────────────────────────\nexport type InputProps = RHFInputProps | ControlledInputProps;\n\nexport const Input: React.FC<InputProps> = (props) => {\n const {\n type = 'text',\n variant = 'outlined',\n size = 'small',\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n preset,\n min,\n max,\n maxLength,\n readOnly,\n inputProps,\n slotProps,\n startAdornment,\n endAdornment,\n sx,\n onBlur,\n ...rest\n } = props as ControlledInputProps & {\n control?: Control<any>;\n validation?: RegisterOptions;\n };\n\n const theme = useTheme();\n const presetSx = resolvePreset('Input', preset, theme);\n\n const finalSlotProps = buildSlotProps(\n type,\n min,\n max,\n maxLength,\n slotProps,\n inputProps,\n readOnly,\n startAdornment,\n endAdornment,\n );\n // El estilo built-in va SIEMPRE primero: el preset se mergea encima, no lo\n // reemplaza (si no, un preset `default` registrado en el theme del consumer\n // borraría altura/labelPosition sin que nadie lo pidiera).\n const mergedSx = [\n buildInputSx(borderRadius, labelPosition),\n ...(presetSx ? [presetSx] : []),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n if ('control' in props && props.control) {\n const { name, control, validation, onValueChange } = props as RHFInputProps;\n return (\n <Controller\n name={name}\n control={control}\n rules={validation}\n render={({ field, fieldState: { error } }) => (\n <TextField\n fullWidth\n {...rest}\n name={field.name}\n value={field.value ?? ''}\n onChange={(e) => {\n const parsed = parseValue(e.target.value, type);\n field.onChange(parsed);\n onValueChange?.(parsed);\n }}\n onBlur={(e) => {\n field.onBlur();\n onBlur?.(e);\n }}\n inputRef={field.ref}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n error={!!error || rest.error}\n helperText={error?.message ?? rest.helperText}\n />\n )}\n />\n );\n }\n\n const { value, onChange } = props as ControlledInputProps;\n return (\n <TextField\n fullWidth\n {...rest}\n value={value ?? ''}\n onChange={(e) => onChange(parseValue(e.target.value, type))}\n onBlur={onBlur}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n />\n );\n};\n\nexport default Input;\n"],"names":["_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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AAC9C,sBAAM,SAAS,MAAM;AACrB,+DAAgB;AAAA,cAClB;AAAA,cACA,QAAQ,CAAC,MAAM;AACb,sBAAM,OAAA;AACN,iDAAS;AAAA,cACX;AAAA,cACA,UAAU,MAAM;AAAA,cAChB;AAAA,cACA;AAAA,cACA;AAAA,cACA,WAAW;AAAA,cACX,IAAI;AAAA,cACJ,OAAO,CAAC,CAAC,SAAS,KAAK;AAAA,cACvB,aAAY,oCAAO,YAAP,YAAkB,KAAK;AAAA,YAAA;AAAA,UAAA;AAAA;AAAA,MACrC;AAAA,IAAA;AAAA,EAIR;AAEA,QAAM,EAAE,OAAO,SAAA,IAAa;AAC5B,SACE;AAAA,IAAC;AAAA,IAAA;AAAA,MACC,WAAS;AAAA,OACL,OAFL;AAAA,MAGC,OAAO,wBAAS;AAAA,MAChB,UAAU,CAAC,MAAM,SAAS,WAAW,EAAE,OAAO,OAAO,IAAI,CAAC;AAAA,MAC1D;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,IAAI;AAAA,IAAA;AAAA,EAAA;AAGV;"}
|
|
@@ -128,7 +128,8 @@ const Input = (props) => {
|
|
|
128
128
|
endAdornment
|
|
129
129
|
);
|
|
130
130
|
const mergedSx = [
|
|
131
|
-
|
|
131
|
+
buildInputSx(borderRadius, labelPosition),
|
|
132
|
+
...presetSx ? [presetSx] : [],
|
|
132
133
|
...Array.isArray(sx) ? sx : sx ? [sx] : []
|
|
133
134
|
];
|
|
134
135
|
if ("control" in props && props.control) {
|
|
@@ -189,4 +190,4 @@ const Input = (props) => {
|
|
|
189
190
|
);
|
|
190
191
|
};
|
|
191
192
|
exports.Input = Input;
|
|
192
|
-
//# sourceMappingURL=Input-
|
|
193
|
+
//# sourceMappingURL=Input-hnQ7g6b7.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Input-Bpjw7qwq.cjs","sources":["../src/components/Input/Input.helpers.ts","../src/components/Input/Input.sx.ts","../src/components/Input/Input.tsx"],"sourcesContent":["import type { InputHTMLAttributes, ReactNode } from 'react';\nimport type { TextFieldProps } from '@mui/material';\nimport type { InputType } from './Input';\n\n/**\n * Convierte el valor raw del evento al tipo apropiado.\n * Para type=\"number\" intenta parsear a número; si falla, devuelve el raw\n * (permite estados intermedios como \"\" o \"-\" mientras el usuario tipea).\n */\nexport const parseValue = (raw: string, type: InputType): string | number => {\n if (type !== 'number') return raw;\n if (raw === '' || raw === '-') return raw;\n const n = parseFloat(raw);\n return isNaN(n) ? raw : n;\n};\n\n/**\n * Construye los slotProps del TextField consolidando htmlInput + inputLabel.\n * Maneja los atributos min/max cuando type=\"number\", maxLength y readOnly.\n */\nexport const buildSlotProps = (\n type: InputType,\n min: number | undefined,\n max: number | undefined,\n maxLength: number | undefined,\n customSlotProps: TextFieldProps['slotProps'],\n customInputProps: InputHTMLAttributes<HTMLInputElement> | undefined,\n readOnly?: boolean,\n startAdornment?: ReactNode,\n endAdornment?: ReactNode,\n): TextFieldProps['slotProps'] => {\n const numberAttrs =\n type === 'number'\n ? { min: min ?? Number.NEGATIVE_INFINITY, ...(max !== undefined && { max }) }\n : {};\n\n // Atajos `startAdornment`/`endAdornment` → slot `input` (OutlinedInput).\n // Lo que el consumidor pase en `slotProps.input` gana (no lo pisamos).\n const customInputSlot = (customSlotProps as any)?.input;\n const inputSlot = {\n ...(startAdornment !== undefined && { startAdornment }),\n ...(endAdornment !== undefined && { endAdornment }),\n ...customInputSlot,\n };\n const hasInputSlot = Object.keys(inputSlot).length > 0;\n\n return {\n ...customSlotProps,\n ...(hasInputSlot && { input: inputSlot }),\n htmlInput: {\n ...customInputProps,\n ...(customSlotProps as any)?.htmlInput,\n ...numberAttrs,\n ...(maxLength !== undefined && { maxLength }),\n ...(readOnly && { readOnly: true }),\n },\n // Dejamos que MUI maneje el shrink nativamente (animación inside → up).\n // El consumidor puede forzar shrink con slotProps.inputLabel.shrink=true si lo necesita.\n inputLabel: {\n ...(customSlotProps as any)?.inputLabel,\n },\n };\n};\n","import type { TextFieldProps } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport { FIELD_INPUT_PADDING_Y } from '../../theme/tokens';\nimport type { LabelPosition } from './Input';\n\n/**\n * Builder de sx para el Input. Usa el builder compartido\n * `buildFormFieldSx` y añade overrides específicos de TextField\n * (padding del input base, filled, standard).\n */\nexport const buildInputSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): TextFieldProps['sx'] => {\n const radius = typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius;\n\n return buildFormFieldSx({\n borderRadius,\n labelPosition,\n extraOutsideSx: {\n // El padding vertical del input base lo fija `buildFormFieldSx`\n // (misma altura para los cinco campos). Acá solo van las variantes.\n\n // Filled: quitar el padding-top reservado para el label flotante dentro.\n '& .MuiFilledInput-root': {\n paddingTop: 0,\n borderRadius: `${radius} ${radius} 0 0`,\n },\n '& .MuiFilledInput-input': {\n paddingTop: FIELD_INPUT_PADDING_Y,\n },\n\n // Standard: quitar el margin-top reservado para el label flotante.\n '& .MuiInput-root': {\n marginTop: 0,\n },\n },\n });\n};\n","import { TextField, type TextFieldProps } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { Controller, type Control, type RegisterOptions } from 'react-hook-form';\n\nimport { parseValue, buildSlotProps } from './Input.helpers';\nimport { buildInputSx } from './Input.sx';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type InputType =\n | 'text' | 'number' | 'email' | 'password' | 'tel'\n | 'url' | 'search' | 'date' | 'datetime-local'\n | 'month' | 'week' | 'time' | 'color';\n\nexport type LabelPosition = 'outside' | 'floating';\n\n// ── Props base (todo lo común entre RHF y controlado) ────────────────────\nexport interface BaseInputProps\n extends Omit<TextFieldProps, 'value' | 'onChange' | 'type'> {\n type?: InputType;\n min?: number;\n max?: number;\n maxLength?: number;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n readOnly?: boolean;\n /** Contenido al inicio del input (ej. icono de búsqueda). Atajo de `slotProps.input.startAdornment`. */\n startAdornment?: React.ReactNode;\n /** Contenido al final del input (ej. botón clear). Atajo de `slotProps.input.endAdornment`. */\n endAdornment?: React.ReactNode;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.Input`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n}\n\n// ── Variantes discriminadas (RHF vs controlado) ──────────────────────────\nexport interface RHFInputProps extends BaseInputProps {\n name: string;\n // `any` plano (no `Control<any>`): RHF tipa `Control<T>` con generics en\n // posiciones tanto contravariantes como covariantes (ej. `_subjects.state`).\n // Cuando el componente o su uso involucra generics adicionales, TS se\n // confunde narroweando el discriminated union y `Control<any>` no logra\n // absorber `Control<MyForm>` en la comparación estructural profunda. El\n // `any` plano elimina ese ruido. RHF adentro sigue teniendo sus tipos\n // fuertes — solo degradamos la superficie del prop del componente.\n control: any;\n validation?: RegisterOptions;\n /**\n * Side-effect que corre después de que RHF actualiza el form state.\n * Útil para cascadas entre campos (ej. reset de municipio al cambiar\n * departamento). NO reemplaza al handler de RHF.\n */\n onValueChange?: (value: string | number) => void;\n value?: never;\n onChange?: never;\n}\n\nexport interface ControlledInputProps extends BaseInputProps {\n name?: string;\n control?: never;\n validation?: never;\n value: string | number;\n onChange: (value: string | number) => void;\n}\n\n// ── API pública final ────────────────────────────────────────────────────\nexport type InputProps = RHFInputProps | ControlledInputProps;\n\nexport const Input: React.FC<InputProps> = (props) => {\n const {\n type = 'text',\n variant = 'outlined',\n size = 'small',\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n preset,\n min,\n max,\n maxLength,\n readOnly,\n inputProps,\n slotProps,\n startAdornment,\n endAdornment,\n sx,\n onBlur,\n ...rest\n } = props as ControlledInputProps & {\n control?: Control<any>;\n validation?: RegisterOptions;\n };\n\n const theme = useTheme();\n const presetSx = resolvePreset('Input', preset, theme);\n\n const finalSlotProps = buildSlotProps(\n type,\n min,\n max,\n maxLength,\n slotProps,\n inputProps,\n readOnly,\n startAdornment,\n endAdornment,\n );\n const mergedSx = [\n ...(presetSx ? [presetSx] : [buildInputSx(borderRadius, labelPosition)]),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n if ('control' in props && props.control) {\n const { name, control, validation, onValueChange } = props as RHFInputProps;\n return (\n <Controller\n name={name}\n control={control}\n rules={validation}\n render={({ field, fieldState: { error } }) => (\n <TextField\n fullWidth\n {...rest}\n name={field.name}\n value={field.value ?? ''}\n onChange={(e) => {\n const parsed = parseValue(e.target.value, type);\n field.onChange(parsed);\n onValueChange?.(parsed);\n }}\n onBlur={(e) => {\n field.onBlur();\n onBlur?.(e);\n }}\n inputRef={field.ref}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n error={!!error || rest.error}\n helperText={error?.message ?? rest.helperText}\n />\n )}\n />\n );\n }\n\n const { value, onChange } = props as ControlledInputProps;\n return (\n <TextField\n fullWidth\n {...rest}\n value={value ?? ''}\n onChange={(e) => onChange(parseValue(e.target.value, type))}\n onBlur={onBlur}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n />\n );\n};\n\nexport default Input;\n"],"names":["buildFormFieldSx","FIELD_INPUT_PADDING_Y","FIELD_BORDER_RADIUS","useTheme","resolvePreset","jsx","Controller","TextField","_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,MAAM,aAAa,CAAC,KAAa,SAAqC;AAC3E,MAAI,SAAS,SAAU,QAAO;AAC9B,MAAI,QAAQ,MAAM,QAAQ,IAAK,QAAO;AACtC,QAAM,IAAI,WAAW,GAAG;AACxB,SAAO,MAAM,CAAC,IA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,cACX;AAAA,cACA,UAAU,MAAM;AAAA,cAChB;AAAA,cACA;AAAA,cACA;AAAA,cACA,WAAW;AAAA,cACX,IAAI;AAAA,cACJ,OAAO,CAAC,CAAC,SAAS,KAAK;AAAA,cACvB,aAAY,oCAAO,YAAP,YAAkB,KAAK;AAAA,YAAA;AAAA,UAAA;AAAA;AAAA,MACrC;AAAA,IAAA;AAAA,EAIR;AAEA,QAAM,EAAE,OAAO,SAAA,IAAa;AAC5B,SACEH,2BAAAA;AAAAA,IAACE,SAAAA;AAAAA,IAAA;AAAA,MACC,WAAS;AAAA,OACL,OAFL;AAAA,MAGC,OAAO,wBAAS;AAAA,MAChB,UAAU,CAAC,MAAM,SAAS,WAAW,EAAE,OAAO,OAAO,IAAI,CAAC;AAAA,MAC1D;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,IAAI;AAAA,IAAA;AAAA,EAAA;AAGV;;"}
|
|
1
|
+
{"version":3,"file":"Input-hnQ7g6b7.cjs","sources":["../src/components/Input/Input.helpers.ts","../src/components/Input/Input.sx.ts","../src/components/Input/Input.tsx"],"sourcesContent":["import type { InputHTMLAttributes, ReactNode } from 'react';\nimport type { TextFieldProps } from '@mui/material';\nimport type { InputType } from './Input';\n\n/**\n * Convierte el valor raw del evento al tipo apropiado.\n * Para type=\"number\" intenta parsear a número; si falla, devuelve el raw\n * (permite estados intermedios como \"\" o \"-\" mientras el usuario tipea).\n */\nexport const parseValue = (raw: string, type: InputType): string | number => {\n if (type !== 'number') return raw;\n if (raw === '' || raw === '-') return raw;\n const n = parseFloat(raw);\n return isNaN(n) ? raw : n;\n};\n\n/**\n * Construye los slotProps del TextField consolidando htmlInput + inputLabel.\n * Maneja los atributos min/max cuando type=\"number\", maxLength y readOnly.\n */\nexport const buildSlotProps = (\n type: InputType,\n min: number | undefined,\n max: number | undefined,\n maxLength: number | undefined,\n customSlotProps: TextFieldProps['slotProps'],\n customInputProps: InputHTMLAttributes<HTMLInputElement> | undefined,\n readOnly?: boolean,\n startAdornment?: ReactNode,\n endAdornment?: ReactNode,\n): TextFieldProps['slotProps'] => {\n const numberAttrs =\n type === 'number'\n ? { min: min ?? Number.NEGATIVE_INFINITY, ...(max !== undefined && { max }) }\n : {};\n\n // Atajos `startAdornment`/`endAdornment` → slot `input` (OutlinedInput).\n // Lo que el consumidor pase en `slotProps.input` gana (no lo pisamos).\n const customInputSlot = (customSlotProps as any)?.input;\n const inputSlot = {\n ...(startAdornment !== undefined && { startAdornment }),\n ...(endAdornment !== undefined && { endAdornment }),\n ...customInputSlot,\n };\n const hasInputSlot = Object.keys(inputSlot).length > 0;\n\n return {\n ...customSlotProps,\n ...(hasInputSlot && { input: inputSlot }),\n htmlInput: {\n ...customInputProps,\n ...(customSlotProps as any)?.htmlInput,\n ...numberAttrs,\n ...(maxLength !== undefined && { maxLength }),\n ...(readOnly && { readOnly: true }),\n },\n // Dejamos que MUI maneje el shrink nativamente (animación inside → up).\n // El consumidor puede forzar shrink con slotProps.inputLabel.shrink=true si lo necesita.\n inputLabel: {\n ...(customSlotProps as any)?.inputLabel,\n },\n };\n};\n","import type { TextFieldProps } from '@mui/material';\n\nimport { buildFormFieldSx } from '../_shared/formField.sx';\nimport { FIELD_INPUT_PADDING_Y } from '../../theme/tokens';\nimport type { LabelPosition } from './Input';\n\n/**\n * Builder de sx para el Input. Usa el builder compartido\n * `buildFormFieldSx` y añade overrides específicos de TextField\n * (padding del input base, filled, standard).\n */\nexport const buildInputSx = (\n borderRadius: number | string,\n labelPosition: LabelPosition,\n): TextFieldProps['sx'] => {\n const radius = typeof borderRadius === 'number' ? `${borderRadius}px` : borderRadius;\n\n return buildFormFieldSx({\n borderRadius,\n labelPosition,\n extraOutsideSx: {\n // El padding vertical del input base lo fija `buildFormFieldSx`\n // (misma altura para los cinco campos). Acá solo van las variantes.\n\n // Filled: quitar el padding-top reservado para el label flotante dentro.\n '& .MuiFilledInput-root': {\n paddingTop: 0,\n borderRadius: `${radius} ${radius} 0 0`,\n },\n '& .MuiFilledInput-input': {\n paddingTop: FIELD_INPUT_PADDING_Y,\n },\n\n // Standard: quitar el margin-top reservado para el label flotante.\n '& .MuiInput-root': {\n marginTop: 0,\n },\n },\n });\n};\n","import { TextField, type TextFieldProps } from '@mui/material';\nimport { useTheme } from '@mui/material/styles';\nimport { Controller, type Control, type RegisterOptions } from 'react-hook-form';\n\nimport { parseValue, buildSlotProps } from './Input.helpers';\nimport { buildInputSx } from './Input.sx';\nimport { resolvePreset } from '../_shared/resolvePreset';\nimport { FIELD_BORDER_RADIUS } from '../../theme/tokens';\n\n// ── Tipos de dominio ─────────────────────────────────────────────────────\nexport type InputType =\n | 'text' | 'number' | 'email' | 'password' | 'tel'\n | 'url' | 'search' | 'date' | 'datetime-local'\n | 'month' | 'week' | 'time' | 'color';\n\nexport type LabelPosition = 'outside' | 'floating';\n\n// ── Props base (todo lo común entre RHF y controlado) ────────────────────\nexport interface BaseInputProps\n extends Omit<TextFieldProps, 'value' | 'onChange' | 'type'> {\n type?: InputType;\n min?: number;\n max?: number;\n maxLength?: number;\n /** Border radius del input. Default: 10 */\n borderRadius?: number | string;\n /** \"outside\" = label arriba del campo (default). \"floating\" = label clásico MUI dentro del borde */\n labelPosition?: LabelPosition;\n readOnly?: boolean;\n /** Contenido al inicio del input (ej. icono de búsqueda). Atajo de `slotProps.input.startAdornment`. */\n startAdornment?: React.ReactNode;\n /** Contenido al final del input (ej. botón clear). Atajo de `slotProps.input.endAdornment`. */\n endAdornment?: React.ReactNode;\n /**\n * Nombre del preset de estilo registrado en `theme.styles.Input`.\n * - `\"default\"` (o ausente) = estilo built-in del paquete.\n * - Cualquier otro string = mergea el preset encima del estilo built-in.\n */\n preset?: string;\n}\n\n// ── Variantes discriminadas (RHF vs controlado) ──────────────────────────\nexport interface RHFInputProps extends BaseInputProps {\n name: string;\n // `any` plano (no `Control<any>`): RHF tipa `Control<T>` con generics en\n // posiciones tanto contravariantes como covariantes (ej. `_subjects.state`).\n // Cuando el componente o su uso involucra generics adicionales, TS se\n // confunde narroweando el discriminated union y `Control<any>` no logra\n // absorber `Control<MyForm>` en la comparación estructural profunda. El\n // `any` plano elimina ese ruido. RHF adentro sigue teniendo sus tipos\n // fuertes — solo degradamos la superficie del prop del componente.\n control: any;\n validation?: RegisterOptions;\n /**\n * Side-effect que corre después de que RHF actualiza el form state.\n * Útil para cascadas entre campos (ej. reset de municipio al cambiar\n * departamento). NO reemplaza al handler de RHF.\n */\n onValueChange?: (value: string | number) => void;\n value?: never;\n onChange?: never;\n}\n\nexport interface ControlledInputProps extends BaseInputProps {\n name?: string;\n control?: never;\n validation?: never;\n value: string | number;\n onChange: (value: string | number) => void;\n}\n\n// ── API pública final ────────────────────────────────────────────────────\nexport type InputProps = RHFInputProps | ControlledInputProps;\n\nexport const Input: React.FC<InputProps> = (props) => {\n const {\n type = 'text',\n variant = 'outlined',\n size = 'small',\n borderRadius = FIELD_BORDER_RADIUS,\n labelPosition = 'outside',\n preset,\n min,\n max,\n maxLength,\n readOnly,\n inputProps,\n slotProps,\n startAdornment,\n endAdornment,\n sx,\n onBlur,\n ...rest\n } = props as ControlledInputProps & {\n control?: Control<any>;\n validation?: RegisterOptions;\n };\n\n const theme = useTheme();\n const presetSx = resolvePreset('Input', preset, theme);\n\n const finalSlotProps = buildSlotProps(\n type,\n min,\n max,\n maxLength,\n slotProps,\n inputProps,\n readOnly,\n startAdornment,\n endAdornment,\n );\n // El estilo built-in va SIEMPRE primero: el preset se mergea encima, no lo\n // reemplaza (si no, un preset `default` registrado en el theme del consumer\n // borraría altura/labelPosition sin que nadie lo pidiera).\n const mergedSx = [\n buildInputSx(borderRadius, labelPosition),\n ...(presetSx ? [presetSx] : []),\n ...(Array.isArray(sx) ? sx : sx ? [sx] : []),\n ];\n\n if ('control' in props && props.control) {\n const { name, control, validation, onValueChange } = props as RHFInputProps;\n return (\n <Controller\n name={name}\n control={control}\n rules={validation}\n render={({ field, fieldState: { error } }) => (\n <TextField\n fullWidth\n {...rest}\n name={field.name}\n value={field.value ?? ''}\n onChange={(e) => {\n const parsed = parseValue(e.target.value, type);\n field.onChange(parsed);\n onValueChange?.(parsed);\n }}\n onBlur={(e) => {\n field.onBlur();\n onBlur?.(e);\n }}\n inputRef={field.ref}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n error={!!error || rest.error}\n helperText={error?.message ?? rest.helperText}\n />\n )}\n />\n );\n }\n\n const { value, onChange } = props as ControlledInputProps;\n return (\n <TextField\n fullWidth\n {...rest}\n value={value ?? ''}\n onChange={(e) => onChange(parseValue(e.target.value, type))}\n onBlur={onBlur}\n type={type}\n variant={variant}\n size={size}\n slotProps={finalSlotProps}\n sx={mergedSx}\n />\n );\n};\n\nexport default Input;\n"],"names":["buildFormFieldSx","FIELD_INPUT_PADDING_Y","FIELD_BORDER_RADIUS","useTheme","resolvePreset","jsx","Controller","TextField","_a"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AASO,MAAM,aAAa,CAAC,KAAa,SAAqC;AAC3E,MAAI,SAAS,SAAU,QAAO;AAC9B,MAAI,QAAQ,MAAM,QAAQ,IAAK,QAAO;AACtC,QAAM,IAAI,WAAW,GAAG;AACxB,SAAO,MAAM,CAAC,IAAI,MAAM;AAC1B;AAMO,MAAM,iBAAiB,CAC5B,MACA,KACA,KACA,WACA,iBACA,kBACA,UACA,gBACA,iBACgC;AAChC,QAAM,cACJ,SAAS,WACL,iBAAE,KAAK,oBAAO,OAAO,qBAAuB,QAAQ,UAAa,EAAE,IAAA,KACnE,CAAA;AAIN,QAAM,kBAAmB,mDAAyB;AAClD,QAAM,YAAY,iDACZ,mBAAmB,UAAa,EAAE,eAAA,IAClC,iBAAiB,UAAa,EAAE,aAAA,IACjC;AAEL,QAAM,eAAe,OAAO,KAAK,SAAS,EAAE,SAAS;AAErD,SAAO,gDACF,kBACC,gBAAgB,EAAE,OAAO,UAAA,IAFxB;AAAA,IAGL,WAAW,+EACN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WAAW,EAAE,OAAO,OAAO,IAAI,CAAC;AAAA,MAC1D;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,WAAW;AAAA,MACX,IAAI;AAAA,IAAA;AAAA,EAAA;AAGV;;"}
|
|
@@ -235,7 +235,8 @@ function Select(props) {
|
|
|
235
235
|
return items;
|
|
236
236
|
};
|
|
237
237
|
const mergedSx = [
|
|
238
|
-
|
|
238
|
+
buildSelectSx(borderRadius, labelPosition),
|
|
239
|
+
...presetSx ? [presetSx] : [],
|
|
239
240
|
...Array.isArray(sx) ? sx : sx ? [sx] : []
|
|
240
241
|
];
|
|
241
242
|
const renderSelect = (selectValue, selectOnChange, onBlur, inputRef, rhfError, rhfHelperText, onValuesChange) => {
|
|
@@ -379,4 +380,4 @@ export {
|
|
|
379
380
|
Option as O,
|
|
380
381
|
Select as S
|
|
381
382
|
};
|
|
382
|
-
//# sourceMappingURL=Select-
|
|
383
|
+
//# sourceMappingURL=Select-CZ0BiKVN.js.map
|