: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(lemon-ui): wire LemonField htmlFor so clicking labels focuses inputs (#60548)
posthog[bot]7753f4614def
diff --git a/frontend/src/lib/lemon-ui/LemonField/LemonField.test.tsx b/frontend/src/lib/lemon-ui/LemonField/LemonField.test.tsxnew file mode 100644index 000000000000..bf9ad1578734--- /dev/null+++ b/frontend/src/lib/lemon-ui/LemonField/LemonField.test.tsx@@ -0,0 +1,82 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'+import { kea, path } from 'kea'+import { Form, forms } from 'kea-forms'++import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'++import { initKeaTests } from '~/test/init'++import { LemonField } from './LemonField'+import type { lemonFieldTestLogicType } from './LemonField.testType'++const lemonFieldTestLogic = kea<lemonFieldTestLogicType>([+ path(['lib', 'lemon-ui', 'LemonField', 'test']),+ forms(() => ({+ myForm: {+ defaults: { referral_source: '', email: '' } as { referral_source: string; email: string },+ errors: () => ({}),+ submit: () => {},+ },+ })),+])++describe('LemonField', () => {+ beforeEach(() => {+ initKeaTests()+ lemonFieldTestLogic.mount()+ })++ afterEach(() => {+ cleanup()+ })++ it('Pure field wires the explicit htmlFor onto the label', () => {+ render(+ <LemonField.Pure label="Email" htmlFor="email-input">+ <input id="email-input" />+ </LemonField.Pure>+ )++ // getByLabelText only resolves when the label is correctly associated with the input,+ // so it's both the assertion and the proof of correct wiring.+ expect(screen.getByLabelText('Email')).toBe(document.getElementById('email-input'))+ })++ it.each([+ {+ desc: 'function-as-child render prop (the signup dead-click pattern)',+ label: 'Where did you hear about us?',+ field: (+ <LemonField name="referral_source" label="Where did you hear about us?">+ {({ value, onChange }) => (+ <LemonInput value={value ?? ''} onChange={(val: string) => onChange(val)} />+ )}+ </LemonField>+ ),+ },+ {+ desc: 'React-element child (no render prop)',+ label: 'Email address',+ field: (+ <LemonField name="email" label="Email address">+ <LemonInput type="email" />+ </LemonField>+ ),+ },+ ])('clicking the label focuses the wrapped input — $desc', ({ label, field }) => {+ render(+ <Form logic={lemonFieldTestLogic} formKey="myForm">+ {field}+ </Form>+ )++ // getByLabelText only finds the input when label[for] matches input[id].+ // If LemonField regressed to emitting htmlFor={undefined}, this throws.+ const input = screen.getByLabelText(label) as HTMLInputElement+ expect(input).toBeInstanceOf(HTMLInputElement)+ expect(input.id).toBeTruthy()+ expect(screen.getByText(label).closest('label')?.getAttribute('for')).toBe(input.id)+ })+})diff --git a/frontend/src/lib/lemon-ui/LemonField/LemonField.tsx b/frontend/src/lib/lemon-ui/LemonField/LemonField.tsxindex 55411bd105ed..fe9bc8d1f621 100644--- a/frontend/src/lib/lemon-ui/LemonField/LemonField.tsx+++ b/frontend/src/lib/lemon-ui/LemonField/LemonField.tsx@@ -1,5 +1,6 @@import clsx from 'clsx'import { Field as KeaField, FieldProps as KeaFieldProps } from 'kea-forms/lib/components'+import { cloneElement, isValidElement, useId } from 'react'import { IconErrorOutline } from 'lib/lemon-ui/icons'import { LemonLabel } from 'lib/lemon-ui/LemonLabel/LemonLabel'@@ -103,9 +104,17 @@ export const LemonField = ({renderError,labelClassName,premiumFeature,+ htmlFor,...keaFieldProps}: LemonFieldProps): JSX.Element => {+ // Stable fallback id so clicking the label focuses the wrapped input. Used when neither the+ // caller nor kea-forms (function-as-child case) put an id on the rendered input.+ const generatedId = useId()const template: KeaFieldProps['template'] = ({ label, kids, error }) => {+ const kidsElement = isValidElement(kids) ? (kids as React.ReactElement<{ id?: string }>) : null+ const existingId = kidsElement?.props.id+ const inputId = htmlFor ?? existingId ?? generatedId+ const renderedKids = kidsElement && existingId !== inputId ? cloneElement(kidsElement, { id: inputId }) : kidsreturn (<LemonPureFieldlabel={label}@@ -118,8 +127,9 @@ export const LemonField = ({renderError={renderError}labelClassName={labelClassName}premiumFeature={premiumFeature}+ htmlFor={inputId}>- {kids as React.ReactNode}+ {renderedKids as React.ReactNode}</LemonPureField>)}