{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "use-number-input",
  "type": "registry:hook",
  "title": "useNumberInput",
  "description": "A hook for managing state and behavior in number input components.",
  "dependencies": [],
  "registryDependencies": [],
  "files": [
    {
      "path": "hooks/use-number-input/index.ts",
      "target": "src/mui-treasury/hooks/use-number-input/index.ts",
      "content": "'use client';\nexport * from './useNumberInput';\n",
      "type": "registry:item"
    },
    {
      "path": "hooks/use-number-input/useNumberInput.ts",
      "target": "src/mui-treasury/hooks/use-number-input/useNumberInput.ts",
      "content": "import React, { useEffect, useRef, useState } from 'react';\n\nimport { useSpinner } from './useSpinner';\n\ntype EventKeys =\n  | 'ArrowDown'\n  | 'ArrowUp'\n  | 'ArrowLeft'\n  | 'ArrowRight'\n  | 'Enter'\n  | 'Space'\n  | 'Tab'\n  | 'Backspace'\n  | 'Control'\n  | 'Meta'\n  | 'Home'\n  | 'End'\n  | 'PageDown'\n  | 'PageUp'\n  | 'Delete'\n  | 'Escape'\n  | ' '\n  | 'Shift';\n\ntype EventKeyMap = Partial<Record<EventKeys, React.KeyboardEventHandler>>;\n\n/**\n * Get the normalized event key across all browsers\n * @param event keyboard event\n */\nfunction normalizeEventKey(event: Pick<KeyboardEvent, 'key' | 'keyCode'>) {\n  const { key, keyCode } = event;\n\n  const isArrowKey =\n    keyCode >= 37 && keyCode <= 40 && key.indexOf('Arrow') !== 0;\n\n  const eventKey = isArrowKey ? `Arrow${key}` : key;\n\n  return eventKey as EventKeys;\n}\n\nexport const minSafeInteger = Number.MIN_SAFE_INTEGER || -9007199254740991;\nexport const maxSafeInteger = Number.MAX_SAFE_INTEGER || 9007199254740991;\n\nexport interface BoundaryParams {\n  defaultValue?: number;\n  value?: number;\n  min?: number;\n  max?: number;\n}\n\nexport interface SpinParams {\n  precision?: number;\n  step?: number;\n}\n\nexport const toNumber = (value: string | undefined) => {\n  if (value === '') return undefined;\n  const result = Number(value);\n  return Number.isNaN(result) ? undefined : result;\n};\n\nexport const numberToString = (value: number | undefined, precision = 0) => {\n  const result = value?.toFixed(precision) ?? '';\n  if (result === 'NaN') return '';\n  return result;\n};\n\nexport const getStepFactor = (\n  event: Partial<{ metaKey: boolean; ctrlKey: boolean; shiftKey: boolean }>,\n  step: number,\n  precision: number,\n) => {\n  let ratio = 1;\n  if (event.metaKey || event.ctrlKey) {\n    ratio = 0.1;\n  }\n  if (event.shiftKey) {\n    ratio = 10;\n  }\n  let stepFactor = ratio * step;\n  if (stepFactor < 1 / Math.pow(10, precision)) {\n    stepFactor = step;\n  }\n  return stepFactor;\n};\n\nconst noop = <T>(value: T) => value;\n\nexport const useNumberBoundary = (options: UseNumberInputOptions = {}) => {\n  const {\n    min = minSafeInteger,\n    max = maxSafeInteger,\n    defaultValue,\n    value,\n    precision = 0,\n    step = 1,\n    keepWithinRange = true,\n    formatter = noop,\n    parser = noop,\n  } = options;\n  const [interfaceValue, setInterfaceValue] = useState<string>(\n    formatter(numberToString(defaultValue, precision)),\n  );\n  const numberValue = toNumber(parser(interfaceValue));\n\n  useEffect(() => {\n    if (defaultValue === undefined && value !== numberValue) {\n      setInterfaceValue(formatter(numberToString(value, precision)));\n    }\n  }, [value]);\n\n  function change(multiplier = 1, params: SpinParams = {}) {\n    setInterfaceValue((current) => {\n      const result =\n        (toNumber(parser(current)) ?? 0) + multiplier * (params.step ?? step);\n      const digits = params.precision ?? precision;\n      if (keepWithinRange) {\n        if (result > max) return max.toFixed(digits);\n        if (result < min) return min.toFixed(digits);\n      }\n      return formatter(result.toFixed(digits));\n    });\n  }\n\n  function increment(params: SpinParams = {}) {\n    change(1, params);\n  }\n\n  function decrement(params: SpinParams = {}) {\n    change(-1, params);\n  }\n\n  return {\n    numberValue,\n    interfaceValue,\n    setInterfaceValue: (value: string) => {\n      setInterfaceValue(formatter(value));\n    },\n    increment,\n    decrement,\n  };\n};\n\nexport type NumberInputEventType = 'change' | 'blur';\nexport type NumberInputError = 'exceed-max' | 'below-min';\nexport type UseNumberInputOptions = {\n  /**\n   * If true, the input's value will change based on mouse wheel\n   */\n  allowMouseWheel?: boolean;\n  /**\n   * When user types number directly into the input.\n   * This controls the value update when you blur out of the input.\n   * - If true and the value is greater than max, the value will be reset to max\n   * - Else, the value remains the same.\n   * @default true\n   */\n  clampValueOnBlur?: boolean;\n  /**\n   * This controls the value update behavior in general.\n   * - If true and you use the stepper or up/down arrow keys, the value will not exceed the max or go lower than min\n   * - If false, the value will be allowed to go out of range.\n   * @default true\n   */\n  keepWithinRange?: boolean;\n  /**\n   * If true, the input will be focused as you increment or decrement the value with the stepper\n   * @default true\n   */\n  focusInputOnChange?: boolean;\n  formatter?: (value: string) => string;\n  parser?: (value: string) => string;\n  /**\n   * a callback function when input value changed\n   */\n  onChange?: (\n    value: number | undefined,\n    metadata: {\n      error: NumberInputError | null;\n      eventType?: NumberInputEventType;\n      valueText?: string;\n    },\n  ) => void;\n} & BoundaryParams &\n  SpinParams;\n\ninterface InputHandlers {\n  onBlur: (event: React.FocusEvent<HTMLInputElement>) => void;\n  onKeyDown: (event: React.KeyboardEvent<HTMLInputElement>) => void;\n}\ninterface ButtonHandlers {\n  onTouchStart: (event: React.TouchEvent<HTMLButtonElement>) => void;\n  onTouchEnd: (event: React.TouchEvent<HTMLButtonElement>) => void;\n  onMouseDown: (event: React.MouseEvent<HTMLButtonElement>) => void;\n  onMouseUp: (event: React.MouseEvent<HTMLButtonElement>) => void;\n  onMouseLeave: (event: React.MouseEvent<HTMLButtonElement>) => void;\n}\n\nfunction callAllHandlers<T>(\n  ...handlers: Array<undefined | ((event: T) => void)>\n) {\n  return (event: T) => {\n    handlers.forEach((handler) => {\n      if (typeof handler === 'function') {\n        handler(event);\n      }\n    });\n  };\n}\n\nconst useIsFirstMount = () => {\n  const isFirstMount = useRef(true);\n  useEffect(() => {\n    isFirstMount.current = false;\n  }, []);\n  return isFirstMount.current;\n};\n\nfunction getError(\n  value: number | undefined,\n  min: number,\n  max: number,\n): NumberInputError | null {\n  if (typeof value === 'number') {\n    if (value < min) return 'below-min';\n    if (value > max) return 'exceed-max';\n  }\n  return null;\n}\n\nexport const useNumberInput = (options: UseNumberInputOptions = {}) => {\n  const inputRef = useRef<HTMLInputElement | null>(null);\n  const {\n    min = minSafeInteger,\n    max = maxSafeInteger,\n    step = 1,\n    precision = 0,\n    focusInputOnChange = true,\n    keepWithinRange = true,\n    clampValueOnBlur = true,\n    allowMouseWheel = false,\n    parser = noop,\n    formatter = noop,\n    onChange,\n  } = options;\n  const {\n    interfaceValue,\n    setInterfaceValue,\n    numberValue,\n    increment,\n    decrement,\n  } = useNumberBoundary(options);\n\n  useEffect(() => {\n    if (process.env.NODE_ENV !== 'production') {\n      if (focusInputOnChange && !inputRef.current) {\n        console.warn(`Cannot find inputRef, make sure to pass it to <input /> like this 👇\n\nfunction NumberInput() {\n  const { inputRef } = useNumberInput(options)\n  return (\n    <input ref={inputRef} />\n  )\n}\n        `);\n      }\n    }\n    function handler(event: WheelEvent) {\n      const isInputFocused = document.activeElement === inputRef.current;\n      if (!allowMouseWheel || !isInputFocused) return;\n\n      event.preventDefault();\n\n      const stepFactor = getStepFactor(event, step, precision);\n      const direction = Math.sign(event.deltaY);\n\n      if (direction === -1) {\n        increment({ step: stepFactor });\n      } else if (direction === 1) {\n        decrement({ step: stepFactor });\n      }\n    }\n    // Use passive: false to allow preventDefault to work\n    const element = inputRef.current;\n    if (element && allowMouseWheel) {\n      element.addEventListener('wheel', handler as EventListener, {\n        passive: false,\n      });\n      return () => {\n        element.removeEventListener('wheel', handler as EventListener);\n      };\n    }\n  }, [\n    allowMouseWheel,\n    decrement,\n    focusInputOnChange,\n    increment,\n    precision,\n    step,\n  ]);\n\n  const isFirstMount = useIsFirstMount();\n  useEffect(() => {\n    if (!isFirstMount) {\n      onChange?.(numberValue, {\n        valueText: interfaceValue,\n        error: getError(numberValue, min, max),\n        eventType: 'change',\n      });\n    }\n  }, [interfaceValue, isFirstMount, max, min, numberValue, onChange]);\n\n  const tempInterfaceValue = useRef(interfaceValue);\n  const spinner = useSpinner(increment, decrement);\n\n  const spinUp = (event: React.MouseEvent | React.TouchEvent) => {\n    event.preventDefault();\n    spinner.up({ step: getStepFactor(event, step, precision) });\n    if (focusInputOnChange) inputRef.current?.focus();\n  };\n\n  const spinDown = (event: React.MouseEvent | React.TouchEvent) => {\n    event.preventDefault();\n    spinner.down({ step: getStepFactor(event, step, precision) });\n    if (focusInputOnChange) inputRef.current?.focus();\n  };\n\n  const handleKeyDown = (event: React.KeyboardEvent) => {\n    const stepFactor = getStepFactor(event, step, precision);\n    const keyMap: EventKeyMap = {\n      ArrowUp: () => increment({ step: stepFactor }),\n      ArrowDown: () => decrement({ step: stepFactor }),\n    };\n    const eventKey = normalizeEventKey(event);\n    const action = keyMap[eventKey];\n    if (action) {\n      event.preventDefault();\n      action(event);\n    }\n  };\n\n  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n    tempInterfaceValue.current = interfaceValue;\n    const result = parser(event.target.value);\n    if (result.match(/^(-|\\+)?(0|[1-9]\\d*)?(\\.)?(\\d+)?$/)) {\n      setInterfaceValue(result);\n    }\n  };\n\n  const handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {\n    const parsedValue = parser(event.target.value);\n    if (parsedValue !== '') {\n      const nextNum = Number(parsedValue);\n      let result = '';\n      if (Number.isNaN(nextNum)) {\n        result = tempInterfaceValue.current;\n      } else {\n        result = nextNum.toFixed(precision);\n        if (clampValueOnBlur) {\n          if (nextNum > max) result = max.toFixed(precision);\n          if (nextNum < min) result = min.toFixed(precision);\n        }\n      }\n\n      setInterfaceValue(result);\n      onChange?.(Number(result), {\n        valueText: formatter(result),\n        error: getError(Number(result), min, max),\n        eventType: 'blur',\n      });\n    } else {\n      onChange?.(undefined, {\n        valueText: '',\n        error: null,\n        eventType: 'blur',\n      });\n    }\n  };\n\n  const incrementDisabled =\n    keepWithinRange && typeof numberValue === 'number' && numberValue >= max;\n  const decrementDisabled =\n    keepWithinRange && typeof numberValue === 'number' && numberValue <= min;\n  return {\n    inputRef,\n    getInputProps: (handlers?: Partial<InputHandlers>) => ({\n      pattern: '[0-9]*(.[0-9]+)?',\n      role: 'spinbutton',\n      'aria-valuemin': min,\n      'aria-valuemax': max,\n      autoComplete: 'off',\n      autoCorrect: 'off',\n      'aria-valuetext': interfaceValue,\n      'aria-valuenow': numberValue,\n      value: interfaceValue,\n      onChange: handleChange,\n      onBlur: callAllHandlers(handleBlur, handlers?.onBlur),\n      onKeyDown: callAllHandlers(handleKeyDown, handlers?.onKeyDown),\n    }),\n    getIncrementProps: (handlers?: Partial<ButtonHandlers>) => ({\n      tabIndex: -1,\n      ...(typeof window !== 'undefined' &&\n      !!document.documentElement.ontouchstart\n        ? {\n            onTouchStart: callAllHandlers(spinUp, handlers?.onTouchStart),\n          }\n        : {\n            onMouseDown: callAllHandlers(spinUp, handlers?.onMouseDown),\n          }),\n      onMouseUp: callAllHandlers(spinner.stop, handlers?.onMouseUp),\n      onMouseLeave: callAllHandlers(spinner.stop, handlers?.onMouseLeave),\n      onTouchEnd: callAllHandlers(spinner.stop, handlers?.onTouchEnd),\n      disabled: incrementDisabled,\n      'aria-disabled': incrementDisabled ? true : undefined,\n    }),\n    getDecrementProps: (handlers?: Partial<ButtonHandlers>) => ({\n      tabIndex: -1,\n      ...(typeof window !== 'undefined' &&\n      !!document.documentElement.ontouchstart\n        ? {\n            onTouchStart: callAllHandlers(spinDown, handlers?.onTouchStart),\n          }\n        : {\n            onMouseDown: callAllHandlers(spinDown, handlers?.onMouseDown),\n          }),\n      onMouseUp: callAllHandlers(spinner.stop, handlers?.onMouseUp),\n      onMouseLeave: callAllHandlers(spinner.stop, handlers?.onMouseLeave),\n      onTouchEnd: callAllHandlers(spinner.stop, handlers?.onTouchEnd),\n      disabled: decrementDisabled,\n      'aria-disabled': decrementDisabled ? true : undefined,\n    }),\n  };\n};\n",
      "type": "registry:item"
    },
    {
      "path": "hooks/use-number-input/useSpinner.ts",
      "target": "src/mui-treasury/hooks/use-number-input/useSpinner.ts",
      "content": "/**\n * ======== CREDIT: Chakra UI ==========\n * https://github.com/chakra-ui/chakra-ui/blob/main/packages/number-input/src/use-spinner.ts\n */\nimport React, { useCallback, useRef, useState } from 'react';\n\nfunction canUseDOM(): boolean {\n  return !!(\n    typeof window !== 'undefined' &&\n    window.document &&\n    window.document.createElement\n  );\n}\n\nconst isBrowser = canUseDOM();\n\n/**\n * useSafeLayoutEffect enables us to safely call `useLayoutEffect` on the browser\n * (for SSR reasons)\n *\n * React currently throws a warning when using useLayoutEffect on the server.\n * To get around it, we can conditionally useEffect on the server (no-op) and\n * useLayoutEffect in the browser.\n *\n * @see https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85\n */\nconst useSafeLayoutEffect = isBrowser ? React.useLayoutEffect : React.useEffect;\n\nfunction useCallbackRef<T extends (...args: unknown[]) => unknown>(\n  fn: T | undefined,\n  deps: React.DependencyList = [],\n): T {\n  const ref = React.useRef(fn);\n\n  useSafeLayoutEffect(() => {\n    ref.current = fn;\n  });\n\n  // eslint-disable-next-line react-hooks/exhaustive-deps\n  return React.useCallback(((...args) => ref.current?.(...args)) as T, deps);\n}\n\nfunction useInterval(callback: () => void, delay: number | null) {\n  const fn = useCallbackRef(callback);\n\n  React.useEffect(() => {\n    let intervalId: number | null = null;\n    const tick = () => fn();\n    if (delay !== null) {\n      intervalId = window.setInterval(tick, delay);\n    }\n    return () => {\n      if (intervalId) {\n        window.clearInterval(intervalId);\n      }\n    };\n  }, [delay, fn]);\n}\n\nfunction useUnmountEffect(fn: () => void, deps: unknown[] = []) {\n  return React.useEffect(\n    () => () => fn(),\n    // eslint-disable-next-line react-hooks/exhaustive-deps\n    deps,\n  );\n}\n\n/**\n * When click and hold on a button - the speed of auto changing the value.\n */\nconst CONTINUOUS_CHANGE_INTERVAL = 50;\n\n/**\n * When click and hold on a button - the delay before auto changing the value.\n */\nconst CONTINUOUS_CHANGE_DELAY = 300;\n\ntype Action = 'increment' | 'decrement';\n\n/**\n * React hook used in the number input to spin its\n * value on long press of the spin buttons\n *\n * @param increment the function to increment\n * @param decrement the function to decrement\n */\nexport function useSpinner<T>(\n  increment: (params?: T) => void,\n  decrement: (params?: T) => void,\n) {\n  /**\n   * To keep incrementing/decrementing on press, we call that `spinning`\n   */\n  const [isSpinning, setIsSpinning] = useState(false);\n\n  // This state keeps track of the action (\"increment\" or \"decrement\")\n  const [action, setAction] = useState<Action | null>(null);\n\n  // To increment the value the first time you mousedown, we call that `runOnce`\n  const [runOnce, setRunOnce] = useState(true);\n\n  const paramsRef = useRef<T | undefined>(undefined);\n\n  // Store the timeout instance id in a ref, so we can clear the timeout later\n  const timeoutRef = useRef<NodeJS.Timeout | undefined>(undefined);\n\n  // Clears the timeout from memory\n  const removeTimeout = () => clearTimeout(timeoutRef.current);\n\n  /**\n   * useInterval hook provides a performant way to\n   * update the state value at specific interval\n   */\n  useInterval(\n    () => {\n      if (action === 'increment') {\n        increment(paramsRef.current);\n      }\n      if (action === 'decrement') {\n        decrement(paramsRef.current);\n      }\n    },\n    isSpinning ? CONTINUOUS_CHANGE_INTERVAL : null,\n  );\n\n  // Function to activate the spinning and increment the value\n  const up = useCallback(\n    (params?: T) => {\n      paramsRef.current = params;\n      // increment the first fime\n      if (runOnce) {\n        increment(params);\n      }\n\n      // after a delay, keep incrementing at interval (\"spinning up\")\n      timeoutRef.current = setTimeout(() => {\n        setRunOnce(false);\n        setIsSpinning(true);\n        setAction('increment');\n      }, CONTINUOUS_CHANGE_DELAY);\n    },\n    [increment, runOnce],\n  );\n\n  // Function to activate the spinning and increment the value\n  const down = useCallback(\n    (params?: T) => {\n      paramsRef.current = params;\n      // decrement the first fime\n      if (runOnce) {\n        decrement(paramsRef.current);\n      }\n\n      // after a delay, keep decrementing at interval (\"spinning down\")\n      timeoutRef.current = setTimeout(() => {\n        setRunOnce(false);\n        setIsSpinning(true);\n        setAction('decrement');\n      }, CONTINUOUS_CHANGE_DELAY);\n    },\n    [decrement, runOnce],\n  );\n\n  // Function to stop spinng (useful for mouseup, keyup handlers)\n  const stop = useCallback(() => {\n    paramsRef.current = undefined;\n    setRunOnce(true);\n    setIsSpinning(false);\n    removeTimeout();\n  }, []);\n\n  /**\n   * If the component unmounts while spinning,\n   * let's clear the timeout as well\n   */\n  useUnmountEffect(removeTimeout);\n\n  return { up, down, stop };\n}\n",
      "type": "registry:item"
    }
  ],
  "meta": {
    "category": "react-hook"
  }
}