: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(property-filters): keep whitespace on a value picked from suggestions (#97122)
posthog[bot]6ad75d28ee7c
diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsxindex 6b7ba48e67b1..2f21ffa5a2fa 100644--- a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.test.tsx@@ -7,7 +7,7 @@ import { Provider } from 'kea'import { useMocks } from '~/mocks/jest'import { propertyDefinitionsModel } from '~/models/propertyDefinitionsModel'import { initKeaTests } from '~/test/init'-import { GroupTypeIndex, PropertyFilterType, PropertyOperator, PropertyType } from '~/types'+import { GroupTypeIndex, PropertyDefinitionType, PropertyFilterType, PropertyOperator, PropertyType } from '~/types'import { PropertyValue } from './PropertyValue'@@ -167,7 +167,24 @@ describe('PropertyValue', () => {pastedValue: 'foo ',expectedArg: 'foo ',},- ])('$label', async ({ propertyKey, operator, pastedValue, expectedArg }) => {+ {+ label: 'preserves surrounding whitespace on a value picked from the suggestion list',+ propertyKey: 'name',+ operator: PropertyOperator.Exact,+ suggestedValue: 'Acme Corp ',+ expectedArg: ['Acme Corp '],+ },+ ])('$label', async ({ propertyKey, operator, pastedValue, suggestedValue, expectedArg }) => {+ if (suggestedValue) {+ const values = { results: [{ name: suggestedValue }], refreshing: false }+ useMocks({+ get: {+ '/api/event/values': values,+ '/api/environments/:team/events/values': values,+ },+ })+ }+const onSet = jest.fn()render(<Provider>@@ -184,14 +201,155 @@ describe('PropertyValue', () => {const user = userEvent.setup()const input = screen.getByRole('textbox')await user.click(input)- await user.paste(pastedValue)- await user.keyboard('{Enter}')+ if (suggestedValue) {+ // The default matcher trims, so this finds the option by its visible label+ const option = await screen.findByText(suggestedValue.trim(), undefined, { timeout: 3000 })+ await user.click(option)+ } else {+ await user.paste(pastedValue)+ await user.keyboard('{Enter}')+ }await waitFor(() => {expect(onSet).toHaveBeenCalledWith(expectedArg)})})+ it('preserves whitespace on a value picked from search results the dropdown still shows', async () => {+ // After the first pick the dropdown keeps rendering the search results, while the component+ // reloads the unsearched values behind it. The second pick then arrives from a list the+ // component no longer holds.+ const searchResults = { results: [{ name: 'Acme Corp ' }, { name: 'Acme Inc ' }], refreshing: false }+ const unsearchedResults = { results: [{ name: 'Chrome' }], refreshing: false }+ const respondToSearch = ({ request }: { request: Request }): typeof searchResults =>+ new URL(request.url).searchParams.get('value') ? searchResults : unsearchedResults+ useMocks({+ get: {+ '/api/event/values': respondToSearch,+ '/api/environments/:team/events/values': respondToSearch,+ },+ })++ const onSet = jest.fn()+ render(+ <Provider>+ <PropertyValue+ propertyKey="name"+ type={PropertyFilterType.Event}+ operator={PropertyOperator.Exact}+ onSet={onSet}+ value={[]}+ />+ </Provider>+ )++ const user = userEvent.setup()+ await user.type(screen.getByRole('textbox'), 'Acme')++ // The default matcher trims, so this finds the option by its visible label+ await user.click(await screen.findByText('Acme Corp', undefined, { timeout: 3000 }))++ // The pick clears the search, so the unsearched values replace the ones just searched+ await waitFor(+ () => {+ expect(propertyDefinitionsModel.values.options['name']?.values).toEqual([{ name: 'Chrome' }])+ },+ { timeout: 3000 }+ )++ await user.click(screen.getByText('Acme Inc'))++ await waitFor(() => {+ expect(onSet).toHaveBeenLastCalledWith(['Acme Inc '])+ })+ })++ it('trims a typed value that only the previous property offered', async () => {+ // Some callers change `propertyKey` without remounting the editor. The values offered for+ // the previous property must not count as suggestions of the new one, or a value the user+ // types for the new property keeps whitespace that only a suggestion may keep.+ const valuesForKey: Record<string, { results: { name: string }[]; refreshing: boolean }> = {+ company_name: { results: [{ name: 'Acme Corp ' }], refreshing: false },+ city: { results: [{ name: 'Springfield' }], refreshing: false },+ }+ const respondToKey = ({ request }: { request: Request }): (typeof valuesForKey)[string] =>+ valuesForKey[new URL(request.url).searchParams.get('key') ?? ''] ?? { results: [], refreshing: false }+ useMocks({+ get: {+ '/api/event/values': respondToKey,+ '/api/environments/:team/events/values': respondToKey,+ },+ })++ const onSet = jest.fn()+ const editor = (propertyKey: string): JSX.Element => (+ <Provider>+ <PropertyValue+ propertyKey={propertyKey}+ type={PropertyFilterType.Event}+ operator={PropertyOperator.Exact}+ onSet={onSet}+ value={[]}+ />+ </Provider>+ )++ const { rerender } = render(editor('company_name'))+ const user = userEvent.setup()+ await user.click(screen.getByRole('textbox'))+ // The default matcher trims, so this finds the option by its visible label+ await screen.findByText('Acme Corp', undefined, { timeout: 3000 })++ rerender(editor('city'))+ await screen.findByText('Springfield', undefined, { timeout: 3000 })++ await user.click(screen.getByRole('textbox'))+ await user.paste('Acme Corp ')+ await user.keyboard('{Enter}')++ await waitFor(() => {+ expect(onSet).toHaveBeenLastCalledWith(['Acme Corp'])+ })+ })++ it('keeps the suggested values when it mounts with values already loaded and a refresh changes them', async () => {+ const editor = (+ <Provider>+ <PropertyValue+ propertyKey="$browser"+ type={PropertyFilterType.Event}+ operator={PropertyOperator.Exact}+ onSet={jest.fn()}+ value={[]}+ />+ </Provider>+ )+ const { unmount } = render(editor)+ await waitFor(() => expect(propertyDefinitionsModel.values.options['$browser']?.status).toBe('loaded'))+ unmount()++ const refreshedValues = { results: [{ name: 'Edge' }], refreshing: false }+ useMocks({+ get: {+ '/api/event/values': refreshedValues,+ '/api/environments/:team/events/values': refreshedValues,+ },+ })+ render(editor)+ await userEvent.setup().click(screen.getByRole('textbox'))+ await screen.findByText('Chrome')++ propertyDefinitionsModel.actions.loadPropertyValues({+ endpoint: undefined,+ type: PropertyDefinitionType.Event,+ newInput: undefined,+ propertyKey: '$browser',+ })+ await screen.findByText('Edge', undefined, { timeout: 3000 })++ expect(screen.getByText('Chrome')).toBeInTheDocument()+ })+it('allows text when a polymorphic property overrides a globally inferred numeric type', async () => {propertyDefinitionsModel.actions.updatePropertyDefinitions({'event/current_value': {diff --git a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsxindex 0a928bf79427..230d5eb76b64 100644--- a/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx+++ b/frontend/src/lib/components/PropertyFilters/components/PropertyValue.tsx@@ -140,10 +140,17 @@ export function PropertyValue({// options jumping around as the user types, we keep the initially loaded options// in state and show those first, then any new options based on user input afterconst [initialSuggestedValues, setInitialSuggestedValues] = useState<{+ // The property these values were loaded for. The reset effect below runs after the render+ // that changes `propertyKey`, so a reader must compare the key to know they are stale.+ propertyKey: stringset: Set<string>orderedKeys: string[]- }>({ set: new Set(), orderedKeys: [] })+ }>({ propertyKey, set: new Set(), orderedKeys: [] })const currentSearchInput = useRef<string>('')+ // Every value the suggestion list has offered for this property. A search replaces the+ // loaded values, but the dropdown can still show the older list, so a value the user+ // clicks is not always among the ones loaded now.+ const offeredValues = useRef<Set<string>>(new Set())const hasStaticValues = !!staticValuesconst load = useCallback(@@ -217,22 +224,27 @@ export function PropertyValue({setInitialSuggestedValues((prev) => {// Merge new keys into existing ones so that values already shown are never removed// from under the user's cursor when a background refresh arrives with a different list.- const merged = [...prev.orderedKeys]- const existingSet = new Set(prev.orderedKeys)+ // Values held for a different property are dropped instead of merged.+ const isSameProperty = prev.propertyKey === propertyKey+ const merged = isSameProperty ? [...prev.orderedKeys] : []+ const existingSet = new Set(merged)for (const key of newKeys) {if (!existingSet.has(key)) {merged.push(key)existingSet.add(key)}}- return { set: existingSet, orderedKeys: merged }+ return { propertyKey, set: existingSet, orderedKeys: merged }})}- }, [propertyOptions?.status, propertyOptions?.values, propertyOptions?.searchInput])+ }, [propertyOptions?.status, propertyOptions?.values, propertyOptions?.searchInput, propertyKey])- // reset initial suggested values when propertyKey changes+ // reset the suggested and offered values when propertyKey changesuseEffect(() => {- setInitialSuggestedValues({ set: new Set(), orderedKeys: [] })+ setInitialSuggestedValues((prev) =>+ prev.propertyKey === propertyKey ? prev : { propertyKey, set: new Set(), orderedKeys: [] }+ )+ offeredValues.current = new Set()}, [propertyKey])// show suggested values first, then any other available options that aren't in the suggested list@@ -241,7 +253,9 @@ export function PropertyValue({return staticValues}const options = propertyOptions?.values || []- if (initialSuggestedValues.set.size === 0) {+ // Stale values must not become options, because the offered set below would then keep+ // them and count them as suggestions of the new property.+ if (initialSuggestedValues.propertyKey !== propertyKey || initialSuggestedValues.set.size === 0) {return options}@@ -271,7 +285,13 @@ export function PropertyValue({}return [...suggestedOptions, ...otherOptions]- }, [propertyOptions?.values, initialSuggestedValues, staticValues])+ }, [propertyOptions?.values, initialSuggestedValues, staticValues, propertyKey])++ useEffect(() => {+ for (const option of displayOptions) {+ offeredValues.current.add(toString(option.name))+ }+ }, [displayOptions, propertyKey])const onSearchTextChange = (newInput: string): void => {const trimmedInput = newInput.trim()@@ -483,12 +503,18 @@ export function PropertyValue({}onChange={(nextVal) => {// Trim whitespace so a stray leading/trailing space (common when pasting an ID)- // doesn't silently break the filter — the snack display hides the space.+ // doesn't silently break the filter — the snack display hides the space. Only+ // what the user just typed or pasted is trimmed: a suggested value, and one+ // already committed, can end in a space, and flag evaluation matches exactly.// Skip regex operators, where leading/trailing whitespace can be a meaningful// part of the pattern (e.g. `^ foo`, `bar $`).const trimmedVal = isOperatorRegex(operator)? nextVal- : nextVal.map((v) => (typeof v === 'string' ? v.trim() : v))+ : nextVal.map((v) =>+ typeof v === 'string' && !offeredValues.current.has(v) && !formattedValues.includes(v)+ ? v.trim()+ : v+ )const newValues = trimmedVal.filter((v) => !formattedValues.includes(String(v)))if (newValues.length > 0) {const availableValues = new Set(displayOptions.map((o) => toString(o.name)))diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsxindex b366b89cc15e..df9e6036add6 100644--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsx+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.test.tsx@@ -430,6 +430,43 @@ describe('LemonInputSelect', () => {expect(lastCall[0]).toContain('[email protected]')})+ it.each([+ {+ name: 'commits it unchanged when the text was not touched',+ typed: '',+ expected: ['Acme Corp '],+ },+ {+ name: 'trims what the person typed over it',+ typed: ' Other Corp ',+ expected: ['Other Corp'],+ },+ ])('multiple-select mode: editing a value snack $name', async ({ typed, expected }) => {+ const onChange = jest.fn()++ const { container } = render(+ <LemonInputSelect<string>+ mode="multiple"+ options={[{ key: 'Acme Corp ', label: 'Acme Corp ' }]}+ value={['Acme Corp ']}+ onChange={onChange}+ allowCustomValues+ />+ )++ // Clicking the snack's text opens it for editing, seeding the input with its value+ await userEvent.click(container.querySelector('[title="Acme Corp "]')!)+ const input = container.querySelector('input[type="text"]') as HTMLInputElement+ expect(input.value).toBe('Acme Corp ')+ if (typed) {+ await userEvent.clear(input)+ await userEvent.type(input, typed)+ }+ await userEvent.click(document.body)++ expect(onChange).toHaveBeenLastCalledWith(expected)+ })+it.each([{name: 'adds nothing when the limit is reached',diff --git a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsxindex da8c11e16729..2e48fc9b0601 100644--- a/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx+++ b/frontend/src/lib/lemon-ui/LemonInputSelect/LemonInputSelect.tsx@@ -221,6 +221,8 @@ export function LemonInputSelect<T = string>({const [showPopover, setShowPopover] = useState(false)const [inputValue, _setInputValue] = useState('')const [itemBeingEditedIndex, setItemBeingEditedIndex] = useState<number | null>(null)+ // The key the current edit started from, so an edit that changes nothing commits it verbatim+ const itemBeingEditedKey = useRef<string | null>(null)const popoverFocusRef = useRef<boolean>(false)// Picking an option blurs the input synchronously, and the blur would otherwise commit the typed// search text as a custom value before (or instead of) the option the user picked.@@ -505,12 +507,14 @@ export function LemonInputSelect<T = string>({}setItemBeingEditedIndex(indexOfValue)}+ itemBeingEditedKey.current = item_setInputValue(item)onInputChange?.(item)inputRef.current?.focus()return}setItemBeingEditedIndex(null)+ itemBeingEditedKey.current = nullif (mode === 'single') {setShowPopover(false)popoverFocusRef.current = false@@ -550,7 +554,10 @@ export function LemonInputSelect<T = string>({return}if (hasCustomValue && !blurringForSelectionRef.current) {- _onActionItem(inputValue.trim(), null)+ // An edit the person did not change must commit the value as it was. Trimming here+ // would drop whitespace they never typed, and a value can end in a space.+ const editedKey = itemBeingEditedKey.current+ _onActionItem(editedKey !== null && inputValue === editedKey ? editedKey : inputValue.trim(), null)} else {setInputValue('')}