Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(lemon-ui): keep a cleared number input empty while typing (#80115)

Chris Shine2bd50f9f04f4
diff --git a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx
index fde734fffe83..a40548c6afdb 100644
--- a/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx
+++ b/frontend/src/lib/components/DateFilter/RollingDateRangeFilter.tsx
@@ -79,7 +79,6 @@ export function RollingDateRangeFilter({
type="number"
value={counter ?? 0}
min={0}
- placeholder="0"
onChange={(value) => setCounter(value)}
/>
<span
diff --git a/frontend/src/lib/lemon-ui/LemonInput/LemonInput.test.tsx b/frontend/src/lib/lemon-ui/LemonInput/LemonInput.test.tsx
index afdceaf90911..e2aefcf4bcc0 100644
--- a/frontend/src/lib/lemon-ui/LemonInput/LemonInput.test.tsx
+++ b/frontend/src/lib/lemon-ui/LemonInput/LemonInput.test.tsx
@@ -1,7 +1,38 @@
import { fireEvent, render } from '@testing-library/react'
+import { useState } from 'react'
import { LemonInput } from './LemonInput'
+/** Mimics how consumers wire a number field: store what `onChange` gives us, optionally collapsing the
+ * NaN of a cleared field back into a default, and optionally clamping. */
+function NumberFieldHarness({
+ fallback,
+ clampMax,
+ onValueChange,
+}: {
+ fallback?: number
+ clampMax?: number
+ onValueChange?: (value: number | undefined) => void
+}): JSX.Element {
+ const [value, setValue] = useState<number | undefined>(30)
+ return (
+ <LemonInput
+ type="number"
+ value={fallback !== undefined ? value || fallback : value}
+ onChange={(newValue) => {
+ const next = clampMax !== undefined && (newValue as number) > clampMax ? clampMax : newValue
+ setValue(next)
+ onValueChange?.(next)
+ }}
+ />
+ )
+}
+
+/** Types `text` the way a keystroke does — appending to whatever the field already shows. */
+function typeInto(input: HTMLInputElement, text: string): void {
+ fireEvent.change(input, { target: { value: `${input.value}${text}` } })
+}
+
describe('LemonInput', () => {
it('does not refocus the native input when it handles the click itself', () => {
const { container } = render(<LemonInput type="time" />)
@@ -19,4 +50,146 @@ describe('LemonInput', () => {
fireEvent.click(wrapper!)
expect(focus).toHaveBeenCalledTimes(1)
})
+
+ it.each([
+ ['falls back to 0', 0],
+ ['falls back to 100', 100],
+ ['has no fallback', undefined],
+ ])('keeps a cleared number field empty while typing, when the consumer %s', (_, fallback) => {
+ const onValueChange = jest.fn()
+ const { container } = render(<NumberFieldHarness fallback={fallback} onValueChange={onValueChange} />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+ expect(input.value).toBe('')
+
+ // The next keystroke appends. Without the fix the field already holds the fallback, so this
+ // lands as '05' or '1005' — and React leaves it there, because '05' and 5 compare equal.
+ typeInto(input, '5')
+ expect(input.value).toBe('5')
+ expect(onValueChange).toHaveBeenLastCalledWith(5)
+ })
+
+ it('restores the consumer fallback once the cleared field loses focus', () => {
+ const { container } = render(<NumberFieldHarness fallback={100} />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+ expect(input.value).toBe('')
+
+ fireEvent.blur(input)
+ expect(input.value).toBe('100')
+ })
+
+ it('still shows a value the consumer clamped while the field is focused', () => {
+ // Pins the empty-only scope: covering the whole focused session instead would swallow clamping
+ // and any programmatic update, such as a slider sharing the field's state.
+ const { container } = render(<NumberFieldHarness clampMax={365} />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '9999' } })
+ expect(input.value).toBe('365')
+ })
+
+ it.each([
+ ['a bare zero', '0'],
+ ['a decimal', '0.5'],
+ ])('accepts %s entered into a cleared field', (_, entered) => {
+ const onValueChange = jest.fn()
+ const { container } = render(<NumberFieldHarness fallback={0} onValueChange={onValueChange} />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+ fireEvent.change(input, { target: { value: entered } })
+
+ expect(input.value).toBe(entered)
+ expect(onValueChange).toHaveBeenLastCalledWith(Number(entered))
+ })
+
+ it('leaves a half-typed number the browser cannot parse yet alone', () => {
+ // A number input reports `value` as '' for an incomplete number like '-' or '0.', so the
+ // consumer sees NaN and echoes its fallback. The field must keep showing what was typed.
+ const { container } = render(<NumberFieldHarness fallback={0} />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+ fireEvent.change(input, { target: { value: '-' } })
+
+ // jsdom applies value sanitization but keeps no record of the raw text, so '' is all we can
+ // assert here — what matters is that React declined to write the fallback over it. A real
+ // browser keeps the '-' visible on top of the same empty `value`.
+ expect(input.value).toBe('')
+ })
+
+ it('leaves an uncontrolled number field uncontrolled while it is emptied', () => {
+ // Consumers that pass only `defaultValue` have no echoed fallback to defend against, and
+ // swapping their undefined value for '' would flip the input controlled and back again.
+ const messages: string[] = []
+ const consoleError = jest.spyOn(console, 'error').mockImplementation((...args) => {
+ messages.push(args.map(String).join(' '))
+ })
+ try {
+ const { container } = render(<LemonInput type="number" defaultValue={50} />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+ typeInto(input, '5')
+
+ expect(messages.filter((message) => /uncontrolled input|controlled input/.test(message))).toEqual([])
+ } finally {
+ consoleError.mockRestore()
+ }
+ })
+
+ it('drops the has-content style while a number field is drafting empty', () => {
+ const { container } = render(<NumberFieldHarness fallback={100} />)
+ const wrapper = container.querySelector<HTMLElement>('.LemonInput')!
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ expect(wrapper.classList).toContain('LemonInput--has-content')
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+ // The consumer still holds 100 here — the class has to follow what is on screen, not the prop.
+ expect(wrapper.classList).not.toContain('LemonInput--has-content')
+
+ fireEvent.blur(input)
+ expect(wrapper.classList).toContain('LemonInput--has-content')
+ })
+
+ it('ends the draft when Enter commits without blurring', () => {
+ // A number input takes part in a form's implicit submission, and Enter fires no blur, so
+ // without this the field keeps reading empty while the consumer's fallback is what just
+ // got submitted. Deliberately not gated on an onPressEnter handler — implicit submission
+ // happens whether or not the consumer wired one.
+ const { container } = render(<NumberFieldHarness fallback={100} />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+ expect(input.value).toBe('')
+
+ fireEvent.keyDown(input, { key: 'Enter' })
+ expect(input.value).toBe('100')
+ })
+
+ it('leaves a cleared text input to its consumer', () => {
+ function TextFieldHarness(): JSX.Element {
+ const [value, setValue] = useState<string>('abc')
+ return <LemonInput type="text" value={value || 'abc'} onChange={setValue} />
+ }
+ const { container } = render(<TextFieldHarness />)
+ const input = container.querySelector<HTMLInputElement>('input')!
+
+ fireEvent.focus(input)
+ fireEvent.change(input, { target: { value: '' } })
+
+ expect(input.value).toBe('abc')
+ })
})
diff --git a/frontend/src/lib/lemon-ui/LemonInput/LemonInput.tsx b/frontend/src/lib/lemon-ui/LemonInput/LemonInput.tsx
index a2eaeaa43bd6..86c9294aa991 100644
--- a/frontend/src/lib/lemon-ui/LemonInput/LemonInput.tsx
+++ b/frontend/src/lib/lemon-ui/LemonInput/LemonInput.tsx
@@ -124,6 +124,9 @@ export const LemonInput = React.forwardRef<HTMLDivElement, LemonInputProps>(func
const [focused, setFocused] = useState<boolean>(Boolean(props.autoFocus))
const [passwordVisible, setPasswordVisible] = useState<boolean>(false)
+ // A cleared number field reports NaN, which consumers routinely collapse back into a default and
+ // echo into the input. While the user is still editing, their empty text wins over that default.
+ const [numberDraftEmpty, setNumberDraftEmpty] = useState<boolean>(false)
if (autoWidth && fullWidth) {
throw new Error('Cannot use `autoWidth` and `fullWidth` props together')
@@ -178,6 +181,7 @@ export const LemonInput = React.forwardRef<HTMLDivElement, LemonInputProps>(func
}
if (onChange) {
if (type === 'number') {
+ setNumberDraftEmpty(false)
// @ts-expect-error - onChange is typed as never, force it to match the right one
onChange(0)
} else {
@@ -201,6 +205,17 @@ export const LemonInput = React.forwardRef<HTMLDivElement, LemonInputProps>(func
}
const InputComponent = autoWidth ? RawInputAutosize : 'input'
+ // A cleared controlled number input holds NaN; show '' so it stays controlled instead of feeding
+ // NaN to the DOM. While the field is focused and the user has emptied it, their empty text also
+ // wins over the fallback a consumer echoes back. Both branches require a controlled input —
+ // `undefined` means the consumer passed only `defaultValue`, and swapping that for '' mid-edit
+ // would flip the input uncontrolled -> controlled and back on the next keystroke.
+ const displayValue =
+ type === 'number' &&
+ value !== undefined &&
+ ((focused && numberDraftEmpty) || (typeof value === 'number' && Number.isNaN(value)))
+ ? ''
+ : value
return (
<Tooltip
title={disabledReason ?? undefined}
@@ -215,7 +230,7 @@ export const LemonInput = React.forwardRef<HTMLDivElement, LemonInputProps>(func
type && `LemonInput--type-${type}`,
size && `LemonInput--${size}`,
fullWidth && 'LemonInput--full-width',
- value && 'LemonInput--has-content',
+ displayValue && 'LemonInput--has-content',
!disabled && !disabledReason && focused && 'LemonInput--focused',
transparentBackground && 'LemonInput--transparent-background',
badgeText && 'relative',
@@ -237,15 +252,22 @@ export const LemonInput = React.forwardRef<HTMLDivElement, LemonInputProps>(func
className="LemonInput__input"
ref={mergedInputRef}
type={(type === 'password' && passwordVisible ? 'text' : type) || 'text'}
- // A cleared controlled number input holds NaN; pass '' so the input stays
- // controlled instead of feeding NaN to the DOM (undefined stays uncontrolled)
- value={type === 'number' && typeof value === 'number' && Number.isNaN(value) ? '' : value}
+ value={displayValue}
disabled={disabled || !!disabledReason}
onChange={(event) => {
if (stopPropagation) {
event.stopPropagation()
}
+ if (type === 'number') {
+ // Value sanitization empties `value` for anything that isn't a valid float,
+ // so intermediate states like '-' and '0.' count as draft-empty too. That is
+ // what we want: the browser keeps showing the half-typed text, and marking it
+ // empty stops React's `value === 0 && node.value === ''` case from replacing
+ // it with a fallback of 0 before the user can finish the number.
+ setNumberDraftEmpty(event.currentTarget.value === '')
+ }
+
if (onChange) {
if (type === 'number') {
// @ts-expect-error - onChange is typed as never, force it to match the right one
@@ -268,14 +290,20 @@ export const LemonInput = React.forwardRef<HTMLDivElement, LemonInputProps>(func
event.stopPropagation()
}
setFocused(false)
+ setNumberDraftEmpty(false)
onBlur?.(event)
}}
onKeyDown={(event) => {
if (stopPropagation) {
event.stopPropagation()
}
- if (onPressEnter && event.key === 'Enter' && !event.nativeEvent.isComposing) {
- onPressEnter(event)
+ if (event.key === 'Enter' && !event.nativeEvent.isComposing) {
+ // Enter commits without blurring — through onPressEnter, and through a
+ // surrounding form's implicit submission even when there is no handler
+ // here. End the draft either way, so the field stops showing empty while
+ // the consumer's value is what actually got submitted.
+ setNumberDraftEmpty(false)
+ onPressEnter?.(event)
}
}}
{...props}