: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
feat(tags): share searchable paginated tag picker (#105788)
Paul D'Ambra4364547b943f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex e90b9c7a7350..f0c3e888faa6 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -9425,9 +9425,9 @@ snapshots:scenes-app-inbox-scoutsroster--large-fleet--light:hash: v1.k794b7964.ed67ad70f3fa88f0a8ec479cb91870ad1d9baab13bb4be71428c960c391bf0db.o6Eahjl27mO8luIjeK97HT62W6KldZEJDcPJDMaCx4cscenes-app-inbox-scoutsroster--narrow--dark:- hash: v1.k794b7964.563269374213e79108bbb022152b0489ff74bebfc5346e9f963f998953304f1f.9FmxupASPfGYeA0dT5MMVMmpnpuenKbo9I0_j3EmGT8+ hash: v1.k794b7964.4f46e7d63afc2c1e1d30d6748e9dd97982bc40daa1057b76679b1ae973b2b34c.FXKomGBUCtnwOShb1cCohyS4J_coJlZPRd2pRY9Zqu4scenes-app-inbox-scoutsroster--narrow--light:- hash: v1.k794b7964.9146b5b058fe264dcf9e062d2a0d9b1dbe30b0a0cfec4e53cfe389a5920f9826.1-i3E_dsDeO6Q8b_UoIj7gJ_th7qgHeQ98oHLMuoA3Q+ hash: v1.k794b7964.e56543a591d0a834354a7a2c235661248d3d76152aed5c4dae11fae9e4f105cf.OMYWVSInB5z11FCVzRUhRvtdq1_U4hi4ALD4a4G32zIscenes-app-inbox-scoutsroster--roster--dark:hash: v1.k794b7964.1fa499f9b82d53b5303ac9c1aad41ae71c3181773bfebff8484f9aac6a5d7ad5.c9CzmU_NYRff7RF85AjHkQMh2xHZSlQNuLU0fF3-Utoscenes-app-inbox-scoutsroster--roster--light:@@ -11856,6 +11856,26 @@ snapshots:hash: v1.k794b7964.b76b173ee1dc78112e700af267b53d59959164f8ebbc814df2b5f4a3811bcd49.2hfIhAW_k3BdFlo9jtUoJhOyZhS1uQmgafcdvh_CGmgscenes-inbox-scout-tags--editor-and-filter--light:hash: v1.k794b7964.4aed44e2990813028b0e9390cbae48142a07a1d7f977b8bfc69d8ca6025c1a80._qkBooayua1hQrnHoZoNzQ8Oj6iSL_nnwUrNwJ1qoh0+ scenes-inbox-scout-tags--many-tags--dark:+ hash: v1.k794b7964.491644324fcbe190b251205a2f7d5b0e59516b8345a63c4d604071095d53ef20.lEWGSyQZ8Qn0d98vMxEg5IZgxzTWFkx880UnUUY4wus+ scenes-inbox-scout-tags--many-tags--light:+ hash: v1.k794b7964.56f3c345dcf5e9ae422037d2253e643f5cfd5229333b00680f3633d79aae0cbc.P89O0cFBwYh_CX9l1OE15M8krA-7FvUDgMmTf29BaX4+ scenes-inbox-scout-tags--open-filter--narrow--dark:+ hash: v1.k794b7964.0eb5a6088f7c9d046170ea599ecefa5fd7473087106789e887fe239fb9a40b55.Zh3FkMhPK3MdhtUxUaihYerzfl074-MHRbjsNI4Ri6o+ scenes-inbox-scout-tags--open-filter--narrow--light:+ hash: v1.k794b7964.424cbb1e38a51f74a90b2d7b5334137f2eb15ca8e304223b00dc4ca872178c19.F6x2cGvtUcffJNZIIjXhFC5Im37OcvoLn3IGleKJ67s+ scenes-inbox-scout-tags--open-filter--wide--dark:+ hash: v1.k794b7964.62fda3088461be73d53c13d078cd263985b7485807392862e62d757703ee8c62.wUsXjTwxVLM-_gy47sD_m-3R8diOUTfCKhGOM9PL-sc+ scenes-inbox-scout-tags--open-filter--wide--light:+ hash: v1.k794b7964.1c420298b76d0e6c2281337a01ce756aac345ec37dc3292b92ec3713be3419d6.yjJ6m9CFyfHYn_0xi0mfYDTQukh1LmyqI56IRsKm0DU+ scenes-inbox-scout-tags--searched-filter--narrow--dark:+ hash: v1.k794b7964.8ae087cd46f020a43e565b977c841e684ae2cb681a7f6f4adc5c2ccdf430843c.rPOv-s4cOD-m-x5jNkt_fHwOfh5xPSv2NdBAqig2VSw+ scenes-inbox-scout-tags--searched-filter--narrow--light:+ hash: v1.k794b7964.fbe7f8bce6b2aa7a0b332622238d969cb869d613d2dba476379741a30d1fafeb.jvE_O-kIFD18kia3-tDBnktHpweb1k3yoQ9xmF4WrfQ+ scenes-inbox-scout-tags--searched-filter--wide--dark:+ hash: v1.k794b7964.7a6a02807240dbbe34017687603246e0d2a8cf3c5030a72489e9c91dbebbd7bf.wRFlnN8ieOdhMFH_nOuQP7jaRIAsHHzggG0_S_U6UBU+ scenes-inbox-scout-tags--searched-filter--wide--light:+ hash: v1.k794b7964.d2fc29b8d0d41c120300eb49eff2ef947cc30813d3491d915dfe4219a8c4326d.-JiZJOnlilAHmEGyfuIA5Uoerbf1c_XC6zVvzKjtduYscenes-other-account-connected--github-integration-connected--dark:hash: v1.k794b7964.fcae9b65af8160ba40bf82664dd9b5a6b9f5a1ddbdedee05bf15ec453eb7aa64.3616s9KNJancKVe-j4dQsJdo3W1CVcwWxRMA24QgU6Qscenes-other-account-connected--github-integration-connected--light:diff --git a/frontend/src/lib/components/TagSelect.test.tsx b/frontend/src/lib/components/TagSelect.test.tsxnew file mode 100644index 000000000000..7c5870b17bf2--- /dev/null+++ b/frontend/src/lib/components/TagSelect.test.tsx@@ -0,0 +1,97 @@+import '@testing-library/jest-dom'++import { act, cleanup, render, screen, waitFor } from '@testing-library/react'+import userEvent from '@testing-library/user-event'+import { Provider } from 'kea'++import { initKeaTests } from '~/test/init'++import { TagSelect } from './TagSelect'++describe('TagSelect', () => {+ beforeEach(() => initKeaTests())+ afterEach(() => cleanup())++ it('searches only the supplied tags and keeps multi-selection when the search changes', async () => {+ const onChange = jest.fn()+ const options = [+ { tag: 'revenue', count: 1 },+ ...Array.from({ length: 75 }, (_, index) => ({ tag: `topic-${index + 1}`, count: 75 - index })),+ ]+ render(+ <Provider>+ <TagSelect defaultLabel="Any tag" options={options} value={['revenue']} onChange={onChange} />+ </Provider>+ )++ await userEvent.click(screen.getByText('revenue'))+ await waitFor(() => expect(screen.getByLabelText('topic-1 (75)')).toBeInTheDocument())+ expect(screen.getByText('Clear selection')).toBeInTheDocument()+ expect(screen.queryByLabelText('topic-75 (1)')).not.toBeInTheDocument()+ await userEvent.type(screen.getByPlaceholderText('Search tags'), 'topic-75')+ await waitFor(() => expect(screen.getByLabelText('topic-75 (1)')).toBeInTheDocument())+ expect(screen.queryByLabelText('revenue (1)')).not.toBeInTheDocument()+ expect(screen.queryByText('Clear selection')).not.toBeInTheDocument()+ await userEvent.click(screen.getByLabelText('topic-75 (1)'))+ expect(onChange).toHaveBeenCalledWith(['revenue', 'topic-75'])+ })++ it('shows a retry when a tag page fails to load', async () => {+ const loadTags = jest+ .fn()+ .mockRejectedValueOnce(new Error('Request failed'))+ .mockResolvedValue({ results: [{ tag: 'available' }], hasMore: false })+ render(+ <Provider>+ <TagSelect value={[]} onChange={jest.fn()} loadTags={loadTags} />+ </Provider>+ )++ await userEvent.click(screen.getByText('Any tags'))+ await userEvent.click(+ await screen.findByText("Couldn't load tags. Try again.", { selector: '.LemonButton__content' })+ )+ await waitFor(() => expect(screen.getByLabelText('available')).toBeInTheDocument())+ expect(screen.queryByText('Clear selection')).not.toBeInTheDocument()+ expect(loadTags).toHaveBeenCalledTimes(2)+ })++ it('ignores a page that finishes after the picker closes', async () => {+ let resolveFirstPage: (page: { results: { tag: string }[]; hasMore: boolean }) => void = () => {}+ let resolveNextPage: (page: { results: { tag: string }[]; hasMore: boolean }) => void = () => {}+ const loadTags = jest+ .fn()+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveFirstPage = resolve+ })+ )+ .mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ resolveNextPage = resolve+ })+ )+ render(+ <Provider>+ <TagSelect value={['selected']} onChange={jest.fn()} loadTags={loadTags} />+ </Provider>+ )++ await userEvent.click(screen.getAllByText('selected')[0].closest('button')!)+ await waitFor(() => expect(loadTags).toHaveBeenCalledTimes(1))+ await userEvent.click(screen.getByText('Clear selection'))+ expect(screen.getAllByText('selected')[0].closest('button')!).toHaveFocus()+ await act(async () => {+ resolveFirstPage({ results: [{ tag: 'stale' }], hasMore: false })+ })+ await userEvent.click(screen.getAllByText('selected')[0].closest('button')!)+ await waitFor(() => expect(loadTags).toHaveBeenCalledTimes(2))+ expect(screen.queryByLabelText('stale')).not.toBeInTheDocument()+ await act(async () => {+ resolveNextPage({ results: [{ tag: 'current' }], hasMore: false })+ })+ expect(screen.getByLabelText('current')).toBeInTheDocument()+ })+})diff --git a/frontend/src/lib/components/TagSelect.tsx b/frontend/src/lib/components/TagSelect.tsxindex dc326e0f08c1..1e08ebbdfd8b 100644--- a/frontend/src/lib/components/TagSelect.tsx+++ b/frontend/src/lib/components/TagSelect.tsx@@ -1,17 +1,55 @@import { useActions, useValues } from 'kea'-import { useId } from 'react'+import { cloneElement, MouseEvent, useCallback, useEffect, useId, useRef } from 'react'-import { LemonButton, LemonButtonProps, LemonDropdown, LemonDropdownProps, LemonInput } from '@posthog/lemon-ui'+import { LemonButton, LemonButtonProps, LemonDropdown, LemonDropdownProps } from '@posthog/lemon-ui'-import { tagSelectLogic } from './tagSelectLogic'+import api, { PaginatedResponse } from 'lib/api'+import { useScrollObserver } from 'lib/hooks/useScrollObserver'+import { teamLogic } from 'scenes/teamLogic'++import { LoadTags, TagOption, tagSelectLogic } from './tagSelectLogic'+import { TagSelectMenu } from './TagSelectMenu'++const TAGS_PER_PAGE = 50export type TagSelectProps = {defaultLabel?: stringvalue: string[]onChange: (value: string[]) => voidchildren?: (selectedTags: string[]) => LemonDropdownProps['children']- /** Distinguishes the logic instance so multiple selects on one page keep independent open/search state. */logicKey?: string+ listDataAttr?: string+ options?: TagOption[]+ loadTags?: LoadTags+ borderless?: boolean+}++function useTagSource(options: TagOption[] | undefined, customLoadTags: LoadTags | undefined): LoadTags {+ const { currentTeamId } = useValues(teamLogic)+ return useCallback<LoadTags>(+ async (query, offset) => {+ if (options) {+ const matches = options.filter((option) => option.tag.toLowerCase().includes(query.toLowerCase()))+ return {+ results: matches.slice(offset, offset + TAGS_PER_PAGE),+ hasMore: offset + TAGS_PER_PAGE < matches.length,+ }+ }+ if (customLoadTags) {+ return customLoadTags(query, offset)+ }+ if (currentTeamId == null) {+ return { results: [], hasMore: false }+ }+ const params = new URLSearchParams({ search: query, limit: String(TAGS_PER_PAGE), offset: String(offset) })+ const page: PaginatedResponse<string> = await api.get(`api/projects/${currentTeamId}/tags?${params}`)+ return {+ results: page.results.map((tag) => ({ tag })),+ hasMore: page.next != null,+ }+ },+ [options, customLoadTags, currentTeamId]+ )}export function TagSelect({@@ -20,110 +58,104 @@ export function TagSelect({onChange,children,logicKey,+ listDataAttr,+ options,+ loadTags: customLoadTags,+ borderless = false,...buttonProps-}: TagSelectProps & Pick<LemonButtonProps, 'type' | 'size'>): JSX.Element {+}: TagSelectProps & Pick<LemonButtonProps, 'type' | 'size' | 'aria-label'>): JSX.Element {const fallbackKey = useId()+ const triggerRef = useRef<HTMLElement | null>(null)const logic = tagSelectLogic({ logicKey: logicKey ?? fallbackKey })- const { filteredTags, search, showPopover } = useValues(logic)- const { setSearch, setShowPopover } = useActions(logic)+ const {+ awaitingFirstPage,+ hasMoreTags,+ requestEpoch,+ search,+ showPopover,+ tagPageError,+ tagPageLoading,+ tagResults,+ } = useValues(logic)+ const { loadTagPage, setSearch, setShowPopover } = useActions(logic)+ const source = useTagSource(options, customLoadTags)- const _onChange = (newTags: string[]): void => {- onChange(newTags)- }+ useEffect(() => {+ if (showPopover) {+ loadTagPage({ search, offset: 0, loadTags: source, requestEpoch })+ }+ }, [showPopover, search, source, loadTagPage, requestEpoch])- const handleTagToggle = (tag: string): void => {- const selected = new Set(value || [])- if (selected.has(tag)) {- selected.delete(tag)- } else {- selected.add(tag)+ const loadMore = (): void => {+ if (hasMoreTags && !awaitingFirstPage && !tagPageLoading && !tagPageError) {+ loadTagPage({ search, offset: tagResults.length, loadTags: source, requestEpoch })}- _onChange(Array.from(selected))}+ const scrollRef = useScrollObserver({ onScrollBottom: loadMore })+ const displayedTags: TagOption[] = search+ ? tagResults+ : [+ ...value+ .filter((tag) => !tagResults.some((option) => option.tag === tag))+ .map((tag) => options?.find((option) => option.tag === tag) ?? { tag }),+ ...tagResults,+ ]- const handleClear = (): void => {- _onChange([])- setShowPopover(false)+ const handleToggle = (tag: string): void => {+ onChange(value.includes(tag) ? value.filter((selected) => selected !== tag) : [...value, tag])}- const selectedCount = value?.length || 0- const buttonClass = selectedCount > 0 ? 'min-w-26' : 'w-26'-+ const selectedCount = value.length+ const trigger = children ? (+ children(value)+ ) : (+ <LemonButton+ size="small"+ type="secondary"+ active={selectedCount > 0}+ status={borderless && selectedCount === 0 ? 'alt' : 'default'}+ className="min-w-26 max-w-48 truncate"+ {...buttonProps}+ >+ {selectedCount === 0 ? defaultLabel : selectedCount === 1 ? value[0] : `${selectedCount} tags`}+ </LemonButton>+ )return (<LemonDropdowncloseOnClickInside={false}visible={showPopover}matchWidth={false}+ padded={false}actionableonVisibilityChange={setShowPopover}overlay={- <div className="max-w-100 deprecated-space-y-2">- <LemonInput- type="search"- placeholder="Search tags"- autoFocus- value={search}- onChange={setSearch}- fullWidth- className="max-w-full"- />- <ul className="deprecated-space-y-px">- {filteredTags.map((tag: string) => (- <li key={tag}>- <LemonButton- fullWidth- role="menuitem"- size="small"- onClick={() => handleTagToggle(tag)}- >- <span className="flex items-center justify-between gap-2 flex-1">- <span className="flex items-center gap-2 max-w-full">- <input- type="checkbox"- className="cursor-pointer"- checked={value?.includes(tag) || false}- readOnly- />- <span>{tag}</span>- </span>- </span>- </LemonButton>- </li>- ))}-- {filteredTags.length === 0 ? (- <div className="p-2 text-secondary italic truncate border-t">- {search ? <span>No matching tags</span> : <span>No tags</span>}- </div>- ) : null}-- {selectedCount > 0 && (- <>- <div className="my-1 border-t" />- <li>- <LemonButton- fullWidth- role="menuitem"- size="small"- onClick={handleClear}- type="secondary"- >- Clear selection- </LemonButton>- </li>- </>- )}- </ul>- </div>+ <TagSelectMenu+ search={search}+ setSearch={setSearch}+ displayedTags={displayedTags}+ value={value}+ awaitingFirstPage={awaitingFirstPage}+ tagPageLoading={tagPageLoading}+ tagPageError={tagPageError}+ listDataAttr={listDataAttr}+ scrollRef={scrollRef}+ onToggle={handleToggle}+ onRetry={() => loadTagPage({ search, offset: tagResults.length, loadTags: source, requestEpoch })}+ onClear={() => {+ onChange([])+ setShowPopover(false)+ triggerRef.current?.focus()+ }}+ />}>- {children ? (- children(value)- ) : (- <LemonButton size="small" type="secondary" className={buttonClass} {...buttonProps}>- {selectedCount > 0 ? `${selectedCount} selected` : defaultLabel}- </LemonButton>- )}+ {trigger &&+ cloneElement(trigger, {+ onClick: (event: MouseEvent<HTMLElement>): void => {+ triggerRef.current = event.currentTarget+ trigger.props.onClick?.(event)+ },+ })}</LemonDropdown>)}diff --git a/frontend/src/lib/components/TagSelectMenu.tsx b/frontend/src/lib/components/TagSelectMenu.tsxnew file mode 100644index 000000000000..f3be650b9c62--- /dev/null+++ b/frontend/src/lib/components/TagSelectMenu.tsx@@ -0,0 +1,98 @@+import { LemonButton, LemonInput } from '@posthog/lemon-ui'++import { TagOption } from './tagSelectLogic'+import { TagSelectOptions } from './TagSelectOptions'++function tagStatus(error: boolean, loading: boolean, displayedTags: TagOption[], search: string): string {+ if (error) {+ return "Couldn't load tags. Try again."+ }+ if (loading) {+ return 'Loading tags'+ }+ if (displayedTags.length === 0) {+ return search ? 'No matching tags' : 'No tags'+ }+ return search ? `${displayedTags.length} tags shown` : ''+}++export function TagSelectMenu({+ search,+ setSearch,+ displayedTags,+ value,+ awaitingFirstPage,+ tagPageLoading,+ tagPageError,+ listDataAttr,+ scrollRef,+ onToggle,+ onRetry,+ onClear,+}: {+ search: string+ setSearch: (search: string) => void+ displayedTags: TagOption[]+ value: string[]+ awaitingFirstPage: boolean+ tagPageLoading: boolean+ tagPageError: string | null+ listDataAttr?: string+ scrollRef: (element: HTMLDivElement | null) => void+ onToggle: (tag: string) => void+ onRetry: () => void+ onClear: () => void+}): JSX.Element {+ const loading = tagPageLoading || awaitingFirstPage+ const hasVisibleSelection = displayedTags.some(({ tag }) => value.includes(tag))++ return (+ <div className="w-64 max-w-[min(25rem,80vw)]">+ <div className="border-b border-primary focus-within:ring-2 focus-within:ring-inset focus-within:ring-primary">+ <LemonInput+ type="search"+ placeholder="Search tags"+ autoFocus+ value={search}+ onChange={setSearch}+ fullWidth+ className="!rounded-none !border-0 !bg-transparent !shadow-none"+ />+ </div>+ <span role="status" className="sr-only">+ {tagStatus(Boolean(tagPageError), loading, displayedTags, search)}+ </span>+ <div ref={scrollRef} className="max-h-80 overflow-y-auto" data-attr={listDataAttr}>+ <TagSelectOptions+ displayedTags={displayedTags}+ value={value}+ loading={loading}+ tagPageError={Boolean(tagPageError)}+ search={search}+ onToggle={onToggle}+ />+ </div>+ {(tagPageError || hasVisibleSelection) && (+ <div className="border-t border-primary">+ {tagPageError && (+ <LemonButton+ fullWidth+ size="small"+ type="tertiary"+ className="!rounded-none"+ loading={tagPageLoading}+ onClick={onRetry}+ >+ Couldn't load tags. Try again.+ </LemonButton>+ )}+ {hasVisibleSelection && (+ <LemonButton fullWidth size="small" type="tertiary" className="!rounded-none" onClick={onClear}>+ Clear selection+ </LemonButton>+ )}+ </div>+ )}+ </div>+ )+}diff --git a/frontend/src/lib/components/TagSelectOptions.tsx b/frontend/src/lib/components/TagSelectOptions.tsxnew file mode 100644index 000000000000..ea457d3e281c--- /dev/null+++ b/frontend/src/lib/components/TagSelectOptions.tsx@@ -0,0 +1,55 @@+import { LemonButton, LemonCheckbox } from '@posthog/lemon-ui'++import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'++import { TagOption } from './tagSelectLogic'++export function TagSelectOptions({+ displayedTags,+ value,+ loading,+ tagPageError,+ search,+ onToggle,+}: {+ displayedTags: TagOption[]+ value: string[]+ loading: boolean+ tagPageError: boolean+ search: string+ onToggle: (tag: string) => void+}): JSX.Element {+ return (+ <ul className="deprecated-space-y-px p-1">+ {displayedTags.map(({ tag, count }) => (+ <li key={tag}>+ <LemonButton+ fullWidth+ role="checkbox"+ aria-checked={value.includes(tag)}+ aria-label={count === undefined ? tag : `${tag} (${count})`}+ tooltip={tag}+ size="small"+ onClick={() => onToggle(tag)}+ >+ <span className="flex min-w-0 flex-1 items-center gap-2 text-left">+ <LemonCheckbox checked={value.includes(tag)} decorative className="pointer-events-none" />+ <span className="min-w-0 flex-1 truncate" title={tag}>+ {tag}+ </span>+ {count !== undefined && <span className="text-muted tabular-nums">{count}</span>}+ </span>+ </LemonButton>+ </li>+ ))}+ {loading && !tagPageError && (+ <li className="p-1" aria-label="Loading tags">+ <LemonSkeleton.Row className="h-8 mb-1" repeat={displayedTags.length === 0 ? 5 : 2} fade />+ </li>+ )}+ {!loading && !tagPageError && displayedTags.length === 0 && (+ <li className="p-2 text-secondary italic">{search ? 'No matching tags' : 'No tags'}</li>+ )}+ </ul>+ )+}diff --git a/frontend/src/lib/components/tagSelectLogic.test.ts b/frontend/src/lib/components/tagSelectLogic.test.tsnew file mode 100644index 000000000000..649e213d798c--- /dev/null+++ b/frontend/src/lib/components/tagSelectLogic.test.ts@@ -0,0 +1,53 @@+import { expectLogic } from 'kea-test-utils'++import { initKeaTests } from '~/test/init'++import { LoadTags, tagSelectLogic } from './tagSelectLogic'++const loadTags: LoadTags = async () => ({ results: [], hasMore: false })++describe('tagSelectLogic', () => {+ it('replaces searched results and appends later pages', async () => {+ initKeaTests()+ const logic = tagSelectLogic({ logicKey: 'pages' })+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.loadTagPageSuccess(+ { results: [{ tag: 'alpha' }, { tag: 'beta' }], hasMore: true },+ { search: '', offset: 0, loadTags, requestEpoch: 0 }+ )+ }).toMatchValues({ hasMoreTags: true, tagResults: [{ tag: 'alpha' }, { tag: 'beta' }] })++ await expectLogic(logic, () => {+ logic.actions.loadTagPageSuccess(+ { results: [{ tag: 'gamma' }], hasMore: false },+ { search: '', offset: 2, loadTags, requestEpoch: 0 }+ )+ }).toMatchValues({ hasMoreTags: false, tagResults: [{ tag: 'alpha' }, { tag: 'beta' }, { tag: 'gamma' }] })++ await expectLogic(logic, () => {+ logic.actions.setSearch('bet')+ logic.actions.loadTagPageSuccess(+ { results: [{ tag: 'beta' }], hasMore: false },+ { search: 'bet', offset: 0, loadTags, requestEpoch: 1 }+ )+ }).toMatchValues({ search: 'bet', tagResults: [{ tag: 'beta' }] })+ expect(logic.values.tagResults).toEqual([{ tag: 'beta' }])+ })++ it('keeps loaded tags after a failed page so users can retry', async () => {+ initKeaTests()+ const logic = tagSelectLogic({ logicKey: 'failure' })+ logic.mount()++ await expectLogic(logic, () => {+ logic.actions.loadTagPageSuccess(+ { results: [{ tag: 'alpha' }], hasMore: true },+ { search: '', offset: 0, loadTags, requestEpoch: 0 }+ )+ logic.actions.loadTagPageFailure('Unable to load tags')+ }).toMatchValues({ tagPageError: 'Unable to load tags', tagResults: [{ tag: 'alpha' }] })+ expect(logic.values.tagPageError).toBe('Unable to load tags')+ })+})diff --git a/frontend/src/lib/components/tagSelectLogic.ts b/frontend/src/lib/components/tagSelectLogic.tsindex 7bc575365213..0a7cc5f922f1 100644--- a/frontend/src/lib/components/tagSelectLogic.ts+++ b/frontend/src/lib/components/tagSelectLogic.ts@@ -1,6 +1,17 @@-import { MakeLogicType, actions, connect, kea, key, path, props, reducers, selectors } from 'kea'+import { MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'+import { loaders } from 'kea-loaders'-import { tagsModel } from '~/models/tagsModel'+export interface TagOption {+ tag: string+ count?: number+}++export interface TagPage {+ results: TagOption[]+ hasMore: boolean+}++export type LoadTags = (search: string, offset: number) => Promise<TagPage>export interface TagSelectLogicProps {logicKey: string@@ -8,14 +19,59 @@ export interface TagSelectLogicProps {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tagSelectLogicValues {- tags: string[] // tagsModel- filteredTags: string[]+ awaitingFirstPage: boolean+ hasMoreTags: boolean+ requestEpoch: numbersearch: stringshowPopover: boolean+ tagPage: TagPage | null+ tagPageError: string | null+ tagPageLoading: boolean+ tagResults: TagOption[]}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tagSelectLogicActions {+ loadTagPage: ({+ search,+ offset,+ loadTags,+ requestEpoch,+ }: {+ loadTags: LoadTags+ offset: number+ requestEpoch: number+ search: string+ }) => {+ search: string+ offset: number+ loadTags: LoadTags+ requestEpoch: number+ }+ loadTagPageFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadTagPageSuccess: (+ tagPage: TagPage,+ payload?: {+ search: string+ offset: number+ loadTags: LoadTags+ requestEpoch: number+ }+ ) => {+ tagPage: TagPage+ payload?: {+ search: string+ offset: number+ loadTags: LoadTags+ requestEpoch: number+ }+ }setSearch: (search: string) => {search: string}@@ -27,9 +83,6 @@ export interface tagSelectLogicActions {// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface tagSelectLogicMeta {key: string- __keaTypeGenInternalSelectorTypes: {- filteredTags: (tags: string[], search: string) => string[]- }}export type tagSelectLogicType = MakeLogicType<@@ -43,36 +96,90 @@ export const tagSelectLogic = kea<tagSelectLogicType>([props({} as TagSelectLogicProps),key((props) => props.logicKey),path((logicKey) => ['lib', 'components', 'tagSelectLogic', logicKey]),- connect(() => ({- values: [tagsModel, ['tags']],- })),actions(() => ({setSearch: (search: string) => ({ search }),setShowPopover: (visible: boolean) => ({ visible }),})),+ loaders(({ values }) => ({+ tagPage: [+ null as TagPage | null,+ {+ loadTagPage: async (+ {+ search,+ offset,+ loadTags,+ requestEpoch,+ }: { search: string; offset: number; loadTags: LoadTags; requestEpoch: number },+ breakpoint+ ): Promise<TagPage> => {+ if (offset === 0 && search) {+ await breakpoint(200)+ }+ try {+ const page = await loadTags(search, offset)+ breakpoint()+ return requestEpoch === values.requestEpoch ? page : { results: [], hasMore: false }+ } catch (error) {+ breakpoint()+ if (requestEpoch !== values.requestEpoch) {+ return { results: [], hasMore: false }+ }+ throw error+ }+ },+ },+ ],+ })),reducers(() => ({+ awaitingFirstPage: [+ false,+ {+ setSearch: () => true,+ setShowPopover: (_, { visible }) => visible,+ loadTagPageSuccess: (state, { payload }) => (payload?.offset === 0 ? false : state),+ loadTagPageFailure: () => false,+ },+ ],search: ['',{setSearch: (_, { search }) => search,- setShowPopover: (state, { visible }) => (visible ? state : ''), // Clear search when closing+ setShowPopover: (state, { visible }) => (visible ? state : ''),+ },+ ],+ requestEpoch: [+ 0,+ {+ setSearch: (state) => state + 1,+ setShowPopover: (state, { visible }) => (visible ? state : state + 1),},],- showPopover: [+ showPopover: [false, { setShowPopover: (_, { visible }) => visible }],+ tagResults: [+ [] as TagOption[],+ {+ setSearch: () => [],+ setShowPopover: (state, { visible }) => (visible ? state : []),+ loadTagPageSuccess: (state, { tagPage, payload }) =>+ payload?.offset === 0 ? tagPage.results : [...state, ...tagPage.results],+ },+ ],+ hasMoreTags: [false,{+ setSearch: () => false,setShowPopover: (_, { visible }) => visible,+ loadTagPageSuccess: (_, { tagPage }) => tagPage.hasMore,},],- })),- selectors(() => ({- filteredTags: [- (s) => [s.tags, s.search],- (tags: string[], search: string) => {- if (!search) {- return tags || []- }- return (tags || []).filter((tag) => tag.toLowerCase().includes(search.toLowerCase()))+ tagPageError: [+ null as string | null,+ {+ setSearch: () => null,+ setShowPopover: () => null,+ loadTagPageSuccess: () => null,+ loadTagPageFailure: (_, { error }) => error,},],})),diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFavoriteFilter.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFavoriteFilter.tsxnew file mode 100644index 000000000000..bd560ebd675f--- /dev/null+++ b/frontend/src/scenes/saved-insights/SavedInsightsFavoriteFilter.tsx@@ -0,0 +1,27 @@+import { IconHeart, IconHeartFilled } from '@posthog/icons'++import { LemonButton } from 'lib/lemon-ui/LemonButton'+import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'++export function SavedInsightsFavoriteFilter({+ favorited,+ setFilters,+ borderless,+}: {+ favorited: boolean | undefined | null+ setFilters: (filters: Partial<SavedInsightFilters>) => void+ borderless: boolean+}): JSX.Element {+ return (+ <LemonButton+ type="secondary"+ status={borderless && !favorited ? 'alt' : 'default'}+ active={favorited || false}+ onClick={() => setFilters({ favorited: !favorited })}+ size="small"+ icon={favorited ? <IconHeartFilled className="text-danger" /> : <IconHeart className="text-secondary" />}+ >+ Favorites+ </LemonButton>+ )+}diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsxindex 30fea013ddae..dc2be9924016 100644--- a/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx+++ b/frontend/src/scenes/saved-insights/SavedInsightsFilters.tsx@@ -1,16 +1,8 @@-import posthog from 'posthog-js'--import { IconHeart, IconHeartFilled } from '@posthog/icons'--import { MemberSelectMultiplePopover } from 'lib/components/MemberSelectMultiplePopover'-import { LemonButton } from 'lib/lemon-ui/LemonButton'import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'-import { LemonSelect } from 'lib/lemon-ui/LemonSelect'import { cn } from 'lib/utils/css-classes'-import { INSIGHT_TYPE_OPTIONS } from 'scenes/saved-insights/SavedInsights'import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'-import { SavedInsightsTagSelect } from './SavedInsightsTagSelect'+import { SavedInsightsQuickFilters } from './SavedInsightsQuickFilters'export type QuickFilterKind = 'insightType' | 'tags' | 'createdBy' | 'favorites'const ALL_QUICK_FILTERS: QuickFilterKind[] = ['insightType', 'tags', 'createdBy', 'favorites']@@ -27,9 +19,7 @@ export function SavedInsightsFilters({/** When true, inactive filters appear borderless. */borderless?: boolean}): JSX.Element {- const { search, favorited, tags, insightType, createdBy } = filters- const quickFilterSet = new Set(quickFilters)- const hasInsightTypeSelection = !!insightType && insightType !== 'All types'+ const { search } = filtersreturn (<div className={cn('flex justify-between gap-2 items-center flex-wrap')}>@@ -42,64 +32,12 @@ export function SavedInsightsFilters({data-attr="insight-dashboard-modal-search"/>{quickFilters.length > 0 && (- <div className="flex gap-2 items-center flex-wrap ml-auto">- {quickFilterSet.has('insightType') && (- <LemonSelect- dropdownMatchSelectWidth={false}- size="small"- active={hasInsightTypeSelection}- status={borderless && !hasInsightTypeSelection ? 'alt' : 'default'}- onChange={(value) => {- setFilters({ insightType: value as string })- posthog.capture('saved insights filtered', { filter_type: 'insight_type', value })- }}- options={INSIGHT_TYPE_OPTIONS}- value={insightType || 'All types'}- />- )}- {quickFilterSet.has('tags') && (- <SavedInsightsTagSelect- value={tags || []}- borderless={borderless}- onChange={(tags) => {- setFilters({ tags: tags.length > 0 ? tags : [] })- posthog.capture('saved insights filtered', { filter_type: 'tags', value: tags })- }}- />- )}- {quickFilterSet.has('createdBy') && (- <MemberSelectMultiplePopover- value={createdBy !== 'All users' ? (createdBy as number[]) : []}- onChange={(ids) => {- const createdByValue = ids.length > 0 ? ids : 'All users'- setFilters({ createdBy: createdByValue })- posthog.capture('saved insights filtered', {- filter_type: 'created_by',- value: createdByValue,- })- }}- borderless={borderless}- />- )}- {quickFilterSet.has('favorites') && (- <LemonButton- type="secondary"- status={borderless && !favorited ? 'alt' : 'default'}- active={favorited || false}- onClick={() => setFilters({ favorited: !favorited })}- size="small"- icon={- favorited ? (- <IconHeartFilled className="text-danger" />- ) : (- <IconHeart className="text-secondary" />- )- }- >- Favorites- </LemonButton>- )}- </div>+ <SavedInsightsQuickFilters+ filters={filters}+ setFilters={setFilters}+ quickFilters={quickFilters}+ borderless={borderless}+ />)}</div>)diff --git a/frontend/src/scenes/saved-insights/SavedInsightsQuickFilters.tsx b/frontend/src/scenes/saved-insights/SavedInsightsQuickFilters.tsxnew file mode 100644index 000000000000..005a623a4803--- /dev/null+++ b/frontend/src/scenes/saved-insights/SavedInsightsQuickFilters.tsx@@ -0,0 +1,63 @@+import posthog from 'posthog-js'++import { MemberSelectMultiplePopover } from 'lib/components/MemberSelectMultiplePopover'+import { TagSelect } from 'lib/components/TagSelect'+import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'++import { SavedInsightsFavoriteFilter } from './SavedInsightsFavoriteFilter'+import { QuickFilterKind } from './SavedInsightsFilters'+import { SavedInsightsTypeFilter } from './SavedInsightsTypeFilter'++type SetFilters = (filters: Partial<SavedInsightFilters>) => void++export function SavedInsightsQuickFilters({+ filters,+ setFilters,+ quickFilters,+ borderless,+}: {+ filters: SavedInsightFilters+ setFilters: SetFilters+ quickFilters: QuickFilterKind[]+ borderless: boolean+}): JSX.Element {+ const { favorited, tags, insightType, createdBy } = filters+ const quickFilterSet = new Set(quickFilters)++ return (+ <div className="flex gap-2 items-center flex-wrap ml-auto">+ {quickFilterSet.has('insightType') && (+ <SavedInsightsTypeFilter insightType={insightType} setFilters={setFilters} borderless={borderless} />+ )}+ {quickFilterSet.has('tags') && (+ <TagSelect+ defaultLabel="Tags"+ listDataAttr="saved-insights-tags-list"+ value={tags || []}+ borderless={borderless}+ onChange={(tags) => {+ setFilters({ tags: tags.length > 0 ? tags : [] })+ posthog.capture('saved insights filtered', { filter_type: 'tags', value: tags })+ }}+ />+ )}+ {quickFilterSet.has('createdBy') && (+ <MemberSelectMultiplePopover+ value={createdBy !== 'All users' ? (createdBy as number[]) : []}+ onChange={(ids) => {+ const createdByValue = ids.length > 0 ? ids : 'All users'+ setFilters({ createdBy: createdByValue })+ posthog.capture('saved insights filtered', {+ filter_type: 'created_by',+ value: createdByValue,+ })+ }}+ borderless={borderless}+ />+ )}+ {quickFilterSet.has('favorites') && (+ <SavedInsightsFavoriteFilter favorited={favorited} setFilters={setFilters} borderless={borderless} />+ )}+ </div>+ )+}diff --git a/frontend/src/scenes/saved-insights/SavedInsightsTagSelect.tsx b/frontend/src/scenes/saved-insights/SavedInsightsTagSelect.tsxdeleted file mode 100644index dce535b9c28b..000000000000--- a/frontend/src/scenes/saved-insights/SavedInsightsTagSelect.tsx+++ /dev/null@@ -1,131 +0,0 @@-import { useActions, useValues } from 'kea'-import { useId } from 'react'--import { LemonButton, LemonDropdown, LemonInput } from '@posthog/lemon-ui'--import { useScrollObserver } from 'lib/hooks/useScrollObserver'-import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'--import { savedInsightsTagFilterLogic } from './savedInsightsTagFilterLogic'--export function SavedInsightsTagSelect({- value,- onChange,- borderless = false,-}: {- value: string[]- onChange: (value: string[]) => void- borderless?: boolean-}): JSX.Element {- const fallbackKey = useId()- const logic = savedInsightsTagFilterLogic({ logicKey: fallbackKey })- const { tagPageError, tagPageLoading, tagResults, tagSearch } = useValues(logic)- const { loadMoreTagResults, retryTagResults, setTagPopoverOpen, setTagSearch } = useActions(logic)- const tagListScrollRef = useScrollObserver({ onScrollBottom: loadMoreTagResults })- const displayedTags = Array.from(new Set([...value, ...tagResults]))-- const handleTagToggle = (tag: string): void => {- const selected = new Set(value)- if (selected.has(tag)) {- selected.delete(tag)- } else {- selected.add(tag)- }- onChange(Array.from(selected))- }-- return (- <LemonDropdown- closeOnClickInside={false}- matchWidth={false}- actionable- onVisibilityChange={setTagPopoverOpen}- overlay={- <div className="max-w-100 deprecated-space-y-2">- <LemonInput- type="search"- placeholder="Search tags"- autoFocus- value={tagSearch}- onChange={setTagSearch}- fullWidth- className="max-w-full"- />- <div- ref={tagListScrollRef}- className="max-h-80 overflow-y-auto"- data-attr="saved-insights-tags-list"- >- <ul className="deprecated-space-y-px">- {displayedTags.map((tag) => (- <li key={tag}>- <LemonButton- fullWidth- role="menuitem"- size="small"- onClick={() => handleTagToggle(tag)}- >- <span className="flex items-center gap-2 max-w-full">- <input- type="checkbox"- className="cursor-pointer"- checked={value.includes(tag)}- readOnly- />- <span>{tag}</span>- </span>- </LemonButton>- </li>- ))}- {!tagPageLoading && !tagPageError && tagResults.length === 0 ? (- <li className="p-2 text-secondary italic truncate border-t">- {tagSearch ? 'No matching tags' : 'No tags'}- </li>- ) : null}- {tagPageLoading ? (- <li className="p-1" aria-label="Loading tags">- <LemonSkeleton.Row- className="h-8 mb-1"- repeat={tagResults.length === 0 ? 5 : 2}- fade- />- </li>- ) : null}- </ul>- </div>- {tagPageError && (- <LemonButton- fullWidth- size="small"- type="secondary"- loading={tagPageLoading}- onClick={retryTagResults}- >- Couldn't load tags. Try again.- </LemonButton>- )}- {value.length > 0 && (- <LemonButton- fullWidth- role="menuitem"- size="small"- onClick={() => onChange([])}- type="secondary"- >- Clear selection- </LemonButton>- )}- </div>- }- >- <LemonButton- size="small"- type="secondary"- active={value.length > 0}- status={borderless && value.length === 0 ? 'alt' : 'default'}- >- {value.length > 0 ? `Tags (${value.length})` : 'Tags'}- </LemonButton>- </LemonDropdown>- )-}diff --git a/frontend/src/scenes/saved-insights/SavedInsightsTypeFilter.tsx b/frontend/src/scenes/saved-insights/SavedInsightsTypeFilter.tsxnew file mode 100644index 000000000000..4b289ce5bd8e--- /dev/null+++ b/frontend/src/scenes/saved-insights/SavedInsightsTypeFilter.tsx@@ -0,0 +1,31 @@+import posthog from 'posthog-js'++import { LemonSelect } from 'lib/lemon-ui/LemonSelect'+import { INSIGHT_TYPE_OPTIONS } from 'scenes/saved-insights/SavedInsights'+import { SavedInsightFilters } from 'scenes/saved-insights/savedInsightsLogic'++export function SavedInsightsTypeFilter({+ insightType,+ setFilters,+ borderless,+}: {+ insightType: string+ setFilters: (filters: Partial<SavedInsightFilters>) => void+ borderless: boolean+}): JSX.Element {+ const active = !!insightType && insightType !== 'All types'+ return (+ <LemonSelect+ dropdownMatchSelectWidth={false}+ size="small"+ active={active}+ status={borderless && !active ? 'alt' : 'default'}+ onChange={(value) => {+ setFilters({ insightType: value as string })+ posthog.capture('saved insights filtered', { filter_type: 'insight_type', value })+ }}+ options={INSIGHT_TYPE_OPTIONS}+ value={insightType || 'All types'}+ />+ )+}diff --git a/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.test.ts b/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.test.tsdeleted file mode 100644index d6f96ff3a6d9..000000000000--- a/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.test.ts+++ /dev/null@@ -1,41 +0,0 @@-import { expectLogic } from 'kea-test-utils'--import { initKeaTests } from '~/test/init'--import { savedInsightsTagFilterLogic } from './savedInsightsTagFilterLogic'--describe('savedInsightsTagFilterLogic', () => {- it('replaces the first tag page and appends the next one', async () => {- initKeaTests()- const logic = savedInsightsTagFilterLogic({ logicKey: 'test' })- logic.mount()-- await expectLogic(logic, () => {- logic.actions.loadTagResultsSuccess(- { next: 'next-page', previous: null, results: ['alpha', 'beta'] },- { search: '', offset: 0 }- )- }).toMatchValues({ hasMoreTagResults: true, tagResults: ['alpha', 'beta'] })-- await expectLogic(logic, () => {- logic.actions.loadTagResultsSuccess(- { next: null, previous: 'previous-page', results: ['gamma'] },- { search: '', offset: 2 }- )- }).toMatchValues({ hasMoreTagResults: false, tagResults: ['alpha', 'beta', 'gamma'] })- })-- it('keeps loaded tags and exposes a failed page for retry', async () => {- initKeaTests()- const logic = savedInsightsTagFilterLogic({ logicKey: 'failure' })- logic.mount()-- await expectLogic(logic, () => {- logic.actions.loadTagResultsSuccess(- { next: 'next-page', previous: null, results: ['alpha'] },- { search: '', offset: 0 }- )- logic.actions.loadTagResultsFailure('Unable to load tags')- }).toMatchValues({ tagPageError: 'Unable to load tags', tagResults: ['alpha'] })- })-})diff --git a/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.ts b/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.tsdeleted file mode 100644index f2e5d5521ad2..000000000000--- a/frontend/src/scenes/saved-insights/savedInsightsTagFilterLogic.ts+++ /dev/null@@ -1,162 +0,0 @@-import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers } from 'kea'-import { loaders } from 'kea-loaders'--import api, { PaginatedResponse } from 'lib/api'-import { teamLogic } from 'scenes/teamLogic'--const TAGS_PER_PAGE = 50--export interface SavedInsightsTagFilterLogicProps {- logicKey: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface savedInsightsTagFilterLogicValues {- currentTeamId: number | null // teamLogic- hasMoreTagResults: boolean- tagPage: PaginatedResponse<string> | null- tagPageError: string | null- tagPageLoading: boolean- tagResults: string[]- tagSearch: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface savedInsightsTagFilterLogicActions {- loadMoreTagResults: () => {- value: true- }- loadTagResults: ({ search, offset }: { offset: number; search: string }) => {- search: string- offset: number- }- loadTagResultsFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadTagResultsSuccess: (- tagPage: PaginatedResponse<string>,- payload?: {- search: string- offset: number- }- ) => {- tagPage: PaginatedResponse<string>- payload?: {- search: string- offset: number- }- }- retryTagResults: () => {- value: true- }- setTagPopoverOpen: (open: boolean) => {- open: boolean- }- setTagSearch: (search: string) => {- search: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface savedInsightsTagFilterLogicMeta {- key: string-}--export type savedInsightsTagFilterLogicType = MakeLogicType<- savedInsightsTagFilterLogicValues,- savedInsightsTagFilterLogicActions,- SavedInsightsTagFilterLogicProps,- savedInsightsTagFilterLogicMeta->--export const savedInsightsTagFilterLogic = kea<savedInsightsTagFilterLogicType>([- props({} as SavedInsightsTagFilterLogicProps),- key((props) => props.logicKey),- path((logicKey) => ['scenes', 'saved-insights', 'savedInsightsTagFilterLogic', logicKey]),- connect(() => ({ values: [teamLogic, ['currentTeamId']] })),- actions({- loadMoreTagResults: true,- retryTagResults: true,- setTagSearch: (search: string) => ({ search }),- setTagPopoverOpen: (open: boolean) => ({ open }),- }),- loaders(({ values }) => ({- tagPage: [- null as PaginatedResponse<string> | null,- {- loadTagResults: async ({ search, offset }: { search: string; offset: number }, breakpoint) => {- if (offset === 0) {- await breakpoint(250)- }- if (values.currentTeamId == null) {- return { results: [], next: null }- }- const params = new URLSearchParams({ search, limit: String(TAGS_PER_PAGE), offset: String(offset) })- const tagPage: PaginatedResponse<string> = await api.get(- `api/projects/${values.currentTeamId}/tags?${params.toString()}`- )- breakpoint()- return tagPage- },- },- ],- })),- reducers({- tagSearch: [- '',- {- setTagSearch: (_, { search }) => search,- setTagPopoverOpen: (state, { open }) => (open ? state : ''),- },- ],- tagResults: [- [] as string[],- {- setTagSearch: () => [],- setTagPopoverOpen: (state, { open }) => (open ? [] : state),- loadTagResultsSuccess: (state, { tagPage, payload }) =>- payload?.offset === 0 ? (tagPage.results ?? []) : [...state, ...(tagPage.results ?? [])],- },- ],- hasMoreTagResults: [- false,- {- setTagSearch: () => false,- setTagPopoverOpen: (_, { open }) => open,- loadTagResultsSuccess: (_, { tagPage }) => tagPage.next != null,- },- ],- tagPageError: [- null as string | null,- {- setTagSearch: () => null,- setTagPopoverOpen: () => null,- loadTagResultsSuccess: () => null,- retryTagResults: () => null,- loadTagResultsFailure: (_, { error }) => error,- },- ],- }),- listeners(({ actions, values }) => ({- setTagPopoverOpen: ({ open }) => {- if (open) {- actions.loadTagResults({ search: '', offset: 0 })- }- },- setTagSearch: ({ search }) => {- actions.loadTagResults({ search, offset: 0 })- },- loadMoreTagResults: () => {- if (values.hasMoreTagResults && !values.tagPageLoading) {- actions.loadTagResults({ search: values.tagSearch, offset: values.tagResults.length })- }- },- retryTagResults: () => {- actions.loadTagResults({ search: values.tagSearch, offset: values.tagResults.length })- },- })),-])diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsxindex f435e6da7cab..45b78b023171 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutTags.stories.tsx@@ -1,4 +1,6 @@import type { Meta, StoryObj } from '@storybook/react'+import { screen, within } from '@testing-library/dom'+import userEvent from '@testing-library/user-event'import { useState } from 'react'import type {@@ -72,18 +74,7 @@ function ScoutTagsPreview(): JSX.Element {</div><div className="flex items-center gap-2"><span className="text-xs text-muted">Tagged</span>- <ScoutTagsFilter- options={options}- selected={selected}- onToggle={(tag) =>- setSelected(- selected.includes(tag)- ? selected.filter((candidate) => candidate !== tag)- : [...selected, tag]- )- }- onClear={() => setSelected([])}- />+ <ScoutTagsFilter options={options} selected={selected} onChange={setSelected} /></div></div>)@@ -101,3 +92,47 @@ type Story = StoryObjexport const EditorAndFilter: Story = {render: () => <ScoutTagsPreview />,}++const MANY_TAG_OPTIONS = Array.from({ length: 75 }, (_, index) => ({+ tag: `topic-${String(index + 1).padStart(2, '0')}`,+ count: 75 - index,+}))++function ManyTagsPreview(): JSX.Element {+ const [selected, setSelected] = useState<string[]>(['topic-02'])++ return (+ <div className="w-64 mx-auto rounded border border-primary bg-bg-light p-3">+ <ScoutTagsFilter options={MANY_TAG_OPTIONS} selected={selected} onChange={setSelected} />+ </div>+ )+}++export const ManyTags: Story = {+ render: () => <ManyTagsPreview />,+}++async function openFilter(canvasElement: HTMLElement): Promise<void> {+ await userEvent.click(await within(canvasElement).findByRole('button', { name: 'Filter scouts by tag' }))+ await screen.findByRole('checkbox', { name: 'topic-01 (75)' })+}++export const OpenFilter: Story = {+ ...ManyTags,+ parameters: {+ layout: 'padded',+ testOptions: { snapshotTargetSelector: 'body', viewportWidths: ['narrow', 'wide'] },+ },+ play: async ({ canvasElement }) => {+ await openFilter(canvasElement)+ },+}++export const SearchedFilter: Story = {+ ...OpenFilter,+ play: async ({ canvasElement }) => {+ await openFilter(canvasElement)+ await userEvent.type(await screen.findByPlaceholderText('Search tags'), 'topic-75')+ await screen.findByRole('checkbox', { name: 'topic-75 (1)' })+ },+}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutTagsFilter.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutTagsFilter.tsxindex 28ae03353b2f..1528a86d751a 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutTagsFilter.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutTagsFilter.tsx@@ -1,49 +1,26 @@-import { IconChevronDown } from '@posthog/icons'-import { LemonButton, LemonCheckbox, LemonMenu, LemonMenuItems } from '@posthog/lemon-ui'+import { TagSelect } from 'lib/components/TagSelect'import type { ScoutTagOption } from '../../../utils/scoutTags'export function ScoutTagsFilter({options,selected,- onToggle,- onClear,+ onChange,size = 'small',}: {options: ScoutTagOption[]selected: string[]- onToggle: (tag: string) => void- onClear: () => void+ onChange: (tags: string[]) => voidsize?: 'xsmall' | 'small'}): JSX.Element {- const label = selected.length === 0 ? 'Any tag' : selected.length === 1 ? selected[0] : `${selected.length} tags`- const items: LemonMenuItems = [- {- title: 'Tagged',- items: options.map((option) => ({- icon: <LemonCheckbox checked={selected.includes(option.tag)} className="pointer-events-none" />,- label: (- <span className="flex min-w-40 items-center justify-between gap-3">- <span className="truncate">{option.tag}</span>- <span className="text-muted tabular-nums">{option.count}</span>- </span>- ),- onClick: () => onToggle(option.tag),- })),- footer:- selected.length > 0 ? (- <LemonButton type="tertiary" size="xsmall" fullWidth onClick={onClear}>- Clear tags- </LemonButton>- ) : undefined,- },- ]-return (- <LemonMenu items={items} closeOnClickInside={false} placement="bottom-end">- <LemonButton type="secondary" size={size} sideIcon={<IconChevronDown />} aria-label="Filter scouts by tag">- {label}- </LemonButton>- </LemonMenu>+ <TagSelect+ options={options}+ value={selected}+ defaultLabel="Any tag"+ size={size}+ aria-label="Filter scouts by tag"+ onChange={onChange}+ />)}diff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFilters.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFilters.tsxindex 52e92b490588..d53436495773 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFilters.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFilters.tsx@@ -58,18 +58,7 @@ export function ScoutsRosterFilters(): JSX.Element {data-attr="inbox-scout-filter-enabled"/>{scoutTagOptions.length > 0 && (- <ScoutTagsFilter- options={scoutTagOptions}- selected={activeScoutTags}- onToggle={(tag) =>- setScoutTagFilter(- activeScoutTags.includes(tag)- ? activeScoutTags.filter((candidate) => candidate !== tag)- : [...activeScoutTags, tag]- )- }- onClear={() => setScoutTagFilter([])}- />+ <ScoutTagsFilter options={scoutTagOptions} selected={activeScoutTags} onChange={setScoutTagFilter} />)}{scoutOwnerOptions.length > 0 && (<ScoutOwnerFilterdiff --git a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFiltersLegacy.tsx b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFiltersLegacy.tsxindex 45f490626ee9..961f97c6137a 100644--- a/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFiltersLegacy.tsx+++ b/products/signals/frontend/inbox/components/config/scouts/ScoutsRosterFiltersLegacy.tsx@@ -42,14 +42,7 @@ export function ScoutsRosterFiltersLegacy({ compact }: { compact: boolean }): JSsize="xsmall"options={scoutTagOptions}selected={activeScoutTags}- onToggle={(tag) =>- setScoutTagFilter(- activeScoutTags.includes(tag)- ? activeScoutTags.filter((candidate) => candidate !== tag)- : [...activeScoutTags, tag]- )- }- onClear={() => setScoutTagFilter([])}+ onChange={setScoutTagFilter}/>)}{scoutOwnerOptions.length > 0 && (