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.

feat(dashboards): paginate tag filters (#93652)

Matt Pua8944d5363326
diff --git a/frontend/src/lib/components/ObjectTags/ObjectTags.tsx b/frontend/src/lib/components/ObjectTags/ObjectTags.tsx
index 2c732f032e03..ce3e58f34232 100644
--- a/frontend/src/lib/components/ObjectTags/ObjectTags.tsx
+++ b/frontend/src/lib/components/ObjectTags/ObjectTags.tsx
@@ -1,9 +1,9 @@
import clsx from 'clsx'
import { useActions, useValues } from 'kea'
-import { ComponentProps, CSSProperties, useId } from 'react'
+import { ComponentProps, CSSProperties, useId, useState } from 'react'
import { IconPencil, IconPlus } from '@posthog/icons'
-import { LemonInputSelect, LemonTag, LemonTagType } from '@posthog/lemon-ui'
+import { LemonButton, LemonInputSelect, LemonTag, LemonTagType, Popover } from '@posthog/lemon-ui'
import { objectTagsLogic } from 'lib/components/ObjectTags/objectTagsLogic'
import { colorForString } from 'lib/utils/colors'
@@ -24,6 +24,8 @@ interface ObjectTagsPropsBase {
inputPlaceholder?: string
/** Makes each displayed tag clickable, e.g. to filter by it. */
onTagClick?: (tag: string) => void
+ /** Maximum number of tags to show before showing the rest in a popover. */
+ maxVisibleTags?: number
/**
* Let a long tag wrap and shrink rather than overflow its container. For narrow containers like a
* sidebar column — off by default, since it lowers the min-content width and so shifts how much
@@ -71,6 +73,7 @@ export function ObjectTags({
editLabel = 'Edit tags',
inputPlaceholder = 'try "official"',
onTagClick,
+ maxVisibleTags,
wrap = false,
}: ObjectTagsProps): JSX.Element {
const objectTagId = useId()
@@ -84,7 +87,11 @@ export function ObjectTags({
style.color = 'var(--color-text-secondary)'
}
- const hasTags = tags && tags.length > 0
+ const displayTags = tags.filter((tag) => !!tag)
+ const hasTags = displayTags.length > 0
+ const [showOverflowTags, setShowOverflowTags] = useState(false)
+ const visibleTags = maxVisibleTags === undefined ? displayTags : displayTags.slice(0, maxVisibleTags)
+ const overflowTags = maxVisibleTags === undefined ? [] : displayTags.slice(maxVisibleTags)
return (
<div
@@ -114,21 +121,44 @@ export function ObjectTags({
<>
{showPlaceholder
? '—'
- : tags
- .filter((t) => !!t)
- .map((tag, index) => {
- return (
- <LemonTag
- key={index}
- type={COLOR_OVERRIDES[tag] || colorForString(tag)}
- onClick={onTagClick ? () => onTagClick(tag) : undefined}
- className={wrap ? 'max-w-full' : undefined}
- wrap={wrap}
- >
- {tag}
- </LemonTag>
- )
- })}
+ : visibleTags.map((tag, index) => {
+ return (
+ <LemonTag
+ key={index}
+ type={COLOR_OVERRIDES[tag] || colorForString(tag)}
+ onClick={onTagClick ? () => onTagClick(tag) : undefined}
+ className={wrap ? 'max-w-full' : undefined}
+ wrap={wrap}
+ >
+ {tag}
+ </LemonTag>
+ )
+ })}
+ {overflowTags.length > 0 && (
+ <Popover
+ visible={showOverflowTags}
+ onClickOutside={() => setShowOverflowTags(false)}
+ overlay={
+ <ObjectTags
+ tags={overflowTags}
+ staticOnly
+ onTagClick={onTagClick}
+ wrap
+ className="max-w-md"
+ />
+ }
+ >
+ <LemonButton
+ size="xsmall"
+ type="tertiary"
+ onClick={() => setShowOverflowTags(!showOverflowTags)}
+ data-attr={dataAttr ? `${dataAttr}-overflow` : undefined}
+ aria-label={`Show ${overflowTags.length} more ${overflowTags.length === 1 ? 'tag' : 'tags'}`}
+ >
+ +{overflowTags.length}
+ </LemonButton>
+ </Popover>
+ )}
{!staticOnly && onChange && saving !== undefined && (
<span className="inline-flex font-normal">
<LemonTag
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.test.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.test.tsx
new file mode 100644
index 000000000000..aa007b036fbc
--- /dev/null
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.test.tsx
@@ -0,0 +1,70 @@
+import '@testing-library/jest-dom'
+
+import { fireEvent, render, screen } from '@testing-library/react'
+import { useActions, useValues } from 'kea'
+import type { ReactNode } from 'react'
+
+import { DashboardsFiltersBar } from './DashboardsFiltersBar'
+import { DashboardsTab } from './dashboardsLogic'
+
+jest.mock('kea', () => ({ ...jest.requireActual('kea'), useValues: jest.fn(), useActions: jest.fn() }))
+jest.mock('lib/components/MemberSelectMultiplePopover', () => ({ MemberSelectMultiplePopover: () => null }))
+jest.mock('@posthog/lemon-ui', () => ({
+ ...jest.requireActual('@posthog/lemon-ui'),
+ Popover: ({ children, overlay }: { children: ReactNode; overlay: ReactNode }) => (
+ <>
+ {children}
+ {overlay}
+ </>
+ ),
+}))
+
+describe('DashboardsFiltersBar', () => {
+ it('loads more tags when the tag list reaches its bottom', () => {
+ const loadMoreTagResults = jest.fn()
+ ;(useActions as jest.Mock).mockReturnValue({
+ loadMoreTagResults,
+ setFilters: jest.fn(),
+ setTagSearch: jest.fn(),
+ setShowTagPopover: jest.fn(),
+ setSearch: jest.fn(),
+ })
+ ;(useValues as jest.Mock).mockReturnValue({
+ filters: { createdBy: 'All users', search: '', tags: [] },
+ currentTab: DashboardsTab.All,
+ tagPageLoading: false,
+ tagResults: ['alpha'],
+ tagSearch: '',
+ showTagPopover: true,
+ })
+
+ const { rerender } = render(<DashboardsFiltersBar />)
+
+ const tagList = document.querySelector<HTMLDivElement>('[data-attr="dashboard-tags-list"]')
+ if (!tagList) {
+ throw new Error('Tag list is not rendered')
+ }
+ Object.defineProperties(tagList, {
+ clientHeight: { value: 100 },
+ scrollHeight: { value: 200 },
+ scrollTop: { value: 101 },
+ })
+
+ fireEvent.scroll(tagList)
+
+ expect(loadMoreTagResults).toHaveBeenCalledTimes(1)
+ expect(screen.queryByText('Load more tags')).not.toBeInTheDocument()
+
+ ;(useValues as jest.Mock).mockReturnValue({
+ filters: { createdBy: 'All users', search: '', tags: [] },
+ currentTab: DashboardsTab.All,
+ tagPageLoading: true,
+ tagResults: [],
+ tagSearch: '',
+ showTagPopover: true,
+ })
+ rerender(<DashboardsFiltersBar />)
+
+ expect(screen.getAllByText('Loading…')).toHaveLength(5)
+ })
+})
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx
index 3ca5a52df5a0..ad1803dc8e1d 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsFiltersBar.tsx
@@ -4,7 +4,9 @@ import { IconChevronDown, IconFolder, IconPin, IconPinFilled, IconShare, IconX }
import { LemonInput, Popover } from '@posthog/lemon-ui'
import { MemberSelectMultiplePopover } from 'lib/components/MemberSelectMultiplePopover'
+import { useScrollObserver } from 'lib/hooks/useScrollObserver'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { DashboardsTab, dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
interface DashboardsFiltersBarProps {
@@ -12,8 +14,9 @@ interface DashboardsFiltersBarProps {
}
export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarProps): JSX.Element {
- const { filters, currentTab, filteredTags, tagSearch, showTagPopover } = useValues(dashboardsLogic)
- const { setFilters, setTagSearch, setShowTagPopover, setSearch } = useActions(dashboardsLogic)
+ const { filters, currentTab, tagPageLoading, tagResults, tagSearch, showTagPopover } = useValues(dashboardsLogic)
+ const { loadMoreTagResults, setFilters, setTagSearch, setShowTagPopover, setSearch } = useActions(dashboardsLogic)
+ const tagListScrollRef = useScrollObserver({ onScrollBottom: loadMoreTagResults })
const createdByIds = filters.createdBy === 'All users' ? [] : filters.createdBy
const handleTagToggle = (tag: string): void => {
@@ -59,51 +62,66 @@ export function DashboardsFiltersBar({ extraActions }: DashboardsFiltersBarProps
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={filters.tags?.includes(tag) || false}
- readOnly
- />
- <span>{tag}</span>
- </span>
- </span>
- </LemonButton>
- </li>
- ))}
- {filteredTags.length === 0 ? (
- <div className="p-2 text-secondary italic truncate border-t">
- {tagSearch ? <span>No matching tags</span> : <span>No tags</span>}
- </div>
- ) : null}
- {(filters.tags?.length || 0) > 0 && (
- <>
- <div className="my-1 border-t" />
- <li>
+ <div
+ ref={tagListScrollRef}
+ className="max-h-80 overflow-y-auto"
+ data-attr="dashboard-tags-list"
+ tabIndex={0}
+ aria-label="Tags"
+ >
+ <ul className="deprecated-space-y-px">
+ {tagResults.map((tag: string) => (
+ <li key={tag}>
<LemonButton
fullWidth
role="menuitem"
size="small"
- onClick={() => setFilters({ tags: [] })}
- type="tertiary"
+ onClick={() => handleTagToggle(tag)}
>
- Clear selection
+ <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={filters.tags?.includes(tag) || false}
+ readOnly
+ />
+ <span>{tag}</span>
+ </span>
+ </span>
</LemonButton>
</li>
- </>
- )}
- </ul>
+ ))}
+ {!tagPageLoading && tagResults.length === 0 ? (
+ <div className="p-2 text-secondary italic truncate border-t">
+ {tagSearch ? <span>No matching tags</span> : <span>No tags</span>}
+ </div>
+ ) : 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>
+ {(filters.tags?.length || 0) > 0 && (
+ <>
+ <div className="my-1 border-t" />
+ <LemonButton
+ fullWidth
+ role="menuitem"
+ size="small"
+ onClick={() => setFilters({ tags: [] })}
+ type="tertiary"
+ >
+ Clear selection
+ </LemonButton>
+ </>
+ )}
</div>
}
>
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
index 2d76c20c2d6e..8a12a854838f 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
@@ -142,4 +142,45 @@ describe('DashboardsTable move to folder', () => {
expect(setFilters).toHaveBeenCalledWith({ tags: ['finance'] })
})
+
+ it('shows overflow tags in a popover and filters by them', () => {
+ const setFilters = jest.fn()
+ ;(useActions as jest.Mock).mockReturnValue({
+ unpinDashboard: jest.fn(),
+ pinDashboard: jest.fn(),
+ tableSortingChanged: jest.fn(),
+ setFilters,
+ showDuplicateDashboardModal: jest.fn(),
+ showDeleteDashboardModal: jest.fn(),
+ moveDashboardsToFolder,
+ })
+ ;(useValues as jest.Mock).mockReturnValue({
+ tableSorting: null,
+ filters: { search: '' },
+ currentTeam: { id: 1 },
+ filedDashboardIds: new Set([1]),
+ })
+
+ render(
+ <DashboardsTable
+ dashboards={
+ [
+ {
+ id: 1,
+ name: 'Dashboard 1',
+ tags: ['alpha', 'beta', 'gamma', 'delta', 'epsilon', '', 'zeta'],
+ user_access_level: AccessControlLevel.Editor,
+ },
+ ] as any
+ }
+ dashboardsLoading={false}
+ />
+ )
+
+ expect(screen.getByText('+1')).toBeInTheDocument()
+ fireEvent.click(screen.getByText('+1'))
+ fireEvent.click(screen.getByText('zeta'))
+
+ expect(setFilters).toHaveBeenCalledWith({ tags: ['zeta'] })
+ })
})
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
index 0f9f47582dc7..df115bcc6d42 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
@@ -178,7 +178,13 @@ export function DashboardsTable({
dataIndex: 'tags' as keyof DashboardType,
render: function Render(tags: DashboardType['tags']) {
return tags ? (
- <ObjectTags tags={[...tags].sort()} staticOnly onTagClick={(tag) => setFilters({ tags: [tag] })} />
+ <ObjectTags
+ tags={[...tags].sort()}
+ staticOnly
+ maxVisibleTags={5}
+ data-attr="dashboard-tags"
+ onTagClick={(tag) => setFilters({ tags: [tag] })}
+ />
) : null
},
} as LemonTableColumn<DashboardType, keyof DashboardType | undefined>,
@@ -330,7 +336,7 @@ export function DashboardsTable({
<DashboardsFiltersBar extraActions={extraActions} />
<LemonTable
data-attr="dashboards-table"
- pagination={{ pageSize: 100 }}
+ pagination={{ pageSize: 50 }}
dataSource={dashboards as DashboardType[]}
rowKey="id"
rowClassName={(record) => (record._highlight ? 'highlighted' : null)}
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index 725f72192810..b0d0d16ccd3a 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -160,6 +160,22 @@ describe('dashboardsLogic', () => {
expect(router.values.searchParams.created_by).toBeUndefined()
})
+ it('replaces tag results for a new search and appends the next page', async () => {
+ 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'] })
+ })
+
describe('reflecting a completed move', () => {
it('updates the moved dashboard to its new folder', async () => {
await expectLogic(logic, () => {
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index 560520df7e74..5916745606b2 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -17,7 +17,6 @@ import { userLogic } from 'scenes/userLogic'
import { SIDE_PANEL_CONTEXT_KEY, SidePanelSceneContext } from '~/layout/navigation-3000/sidepanel/types'
import { projectTreeDataLogic } from '~/layout/panel-layout/ProjectTree/projectTreeDataLogic'
import { dashboardsModel } from '~/models/dashboardsModel'
-import { tagsModel } from '~/models/tagsModel'
import { FileSystemEntry } from '~/queries/schema/schema-general'
import { ActivityScope, Breadcrumb, DashboardBasicType } from '~/types'
@@ -84,21 +83,23 @@ function urlSearchParamToString(value: unknown): string {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface dashboardsLogicValues {
featureFlags: FeatureFlagsSet // featureFlagLogic
- tags: string[] // tagsModel
user: UserType | null // userLogic
breadcrumbs: Breadcrumb[]
currentTab: DashboardsTab
dashboards: DashboardBasicType[]
dashboardsById: Record<string, DashboardBasicType>
filedDashboardIds: Set<number>
- filteredTags: string[]
filters: DashboardsFilters
+ hasMoreTagResults: boolean
isFiltering: boolean
searchedDashboards: DashboardBasicType[] | null
searchedDashboardsLoading: boolean
showTagPopover: boolean
sidePanelContext: SidePanelSceneContext
tableSorting: Sorting
+ tagPage: PaginatedResponse<string> | null
+ tagPageLoading: boolean
+ tagResults: string[]
tagSearch: string
}
@@ -123,6 +124,9 @@ export interface dashboardsLogicActions {
newPath: string
oldPath: string
} // projectTreeDataLogic
+ loadMoreTagResults: () => {
+ value: true
+ }
loadSearchedDashboards: ({ search, tags, folder }: { folder: string | null; search: string; tags: string[] }) => {
search: string
tags: string[]
@@ -150,6 +154,44 @@ export interface dashboardsLogicActions {
folder: string | null
}
}
+ loadTagResults: ({ search, offset }: { offset: number; search: string }) => {
+ search: string
+ offset: number
+ }
+ loadTagResultsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadTagResultsSuccess: (
+ tagPage:
+ | PaginatedResponse<string>
+ | {
+ count: number
+ next: null
+ previous: null
+ results: never[]
+ },
+ payload?: {
+ search: string
+ offset: number
+ }
+ ) => {
+ tagPage:
+ | PaginatedResponse<string>
+ | {
+ count: number
+ next: null
+ previous: null
+ results: never[]
+ }
+ payload?: {
+ search: string
+ offset: number
+ }
+ }
moveDashboardsToFolder: (
ids: number[],
method: 'bulk' | 'single',
@@ -183,7 +225,6 @@ export interface dashboardsLogicActions {
export interface dashboardsLogicMeta {
__keaTypeGenInternalSelectorTypes: {
isFiltering: (filters: DashboardsFilters) => boolean
- filteredTags: (tags: string[], tagSearch: string) => string[]
dashboards: (
nameSortedDashboards: (
| DashboardBasicType
@@ -222,7 +263,7 @@ export type dashboardsLogicType = MakeLogicType<
export const dashboardsLogic = kea<dashboardsLogicType>([
path(['scenes', 'dashboard', 'dashboardsLogic']),
connect(() => ({
- values: [userLogic, ['user'], featureFlagLogic, ['featureFlags'], tagsModel, ['tags']],
+ values: [userLogic, ['user'], featureFlagLogic, ['featureFlags']],
actions: [
moveToLogic,
['openMoveToModal'],
@@ -248,6 +289,7 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
}),
setTagSearch: (search: string) => ({ search }),
setShowTagPopover: (visible: boolean) => ({ visible }),
+ loadMoreTagResults: true,
}),
reducers(() => {
const filtersPersistence = buildUserScopedPersistenceConfig('dashboard_list_filters__')
@@ -344,19 +386,50 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
},
},
],
+ tagPage: [
+ null as PaginatedResponse<string> | null,
+ {
+ loadTagResults: async ({ search, offset }: { search: string; offset: number }, breakpoint) => {
+ if (offset === 0) {
+ await breakpoint(250)
+ }
+ const teamId = teamLogic.values.currentTeamId
+ if (teamId == null) {
+ return { count: 0, next: null, previous: null, results: [] }
+ }
+ const params = new URLSearchParams({ search, limit: '50', offset: String(offset) })
+ const tagPage: PaginatedResponse<string> = await api.get(
+ `api/projects/${teamId}/tags?${params.toString()}`
+ )
+ breakpoint()
+ return tagPage
+ },
+ },
+ ],
}),
- selectors({
- isFiltering: [(s) => [s.filters], (filters: DashboardsFilters) => hasDashboardFilters(filters)],
- filteredTags: [
- (s) => [s.tags, s.tagSearch],
- (tags: string[], search: string) => {
- if (!search) {
- return tags || []
- }
- return (tags || []).filter((tag) => tag.toLowerCase().includes(search.toLowerCase()))
+ reducers({
+ tagResults: [
+ [] as string[],
+ {
+ setShowTagPopover: (state, { visible }) => (visible ? [] : state),
+ setTagSearch: () => [],
+ loadTagResultsSuccess: (state, { tagPage, payload }) =>
+ payload?.offset === 0 ? (tagPage.results ?? []) : [...state, ...(tagPage.results ?? [])],
},
],
+ hasMoreTagResults: [
+ false,
+ {
+ setShowTagPopover: (state, { visible }) => (visible ? false : state),
+ setTagSearch: () => false,
+ loadTagResultsSuccess: (_, { tagPage }) => tagPage.next != null,
+ },
+ ],
+ }),
+
+ selectors({
+ isFiltering: [(s) => [s.filters], (filters: DashboardsFilters) => hasDashboardFilters(filters)],
dashboards: [
(s) => [
dashboardsModel.selectors.nameSortedDashboards,
@@ -643,5 +716,18 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
})
}
},
+ setShowTagPopover: ({ visible }) => {
+ if (visible) {
+ actions.loadTagResults({ search: values.tagSearch, offset: 0 })
+ }
+ },
+ setTagSearch: ({ search }) => {
+ actions.loadTagResults({ search, offset: 0 })
+ },
+ loadMoreTagResults: () => {
+ if (values.hasMoreTagResults && !values.tagPageLoading) {
+ actions.loadTagResults({ search: values.tagSearch, offset: values.tagResults.length })
+ }
+ },
})),
])
diff --git a/posthog/api/tagged_item.py b/posthog/api/tagged_item.py
index 265622775fb9..abfa5e2b0cf6 100644
--- a/posthog/api/tagged_item.py
+++ b/posthog/api/tagged_item.py
@@ -5,8 +5,8 @@ from typing import TYPE_CHECKING, Any, Optional, cast
from django.db import models
from django.db.models import Prefetch, Q, QuerySet, prefetch_related_objects
-from drf_spectacular.utils import extend_schema
-from rest_framework import response, serializers, status, viewsets
+from drf_spectacular.utils import OpenApiParameter, OpenApiTypes, extend_schema
+from rest_framework import pagination, response, serializers, status, viewsets
from rest_framework.viewsets import GenericViewSet
from posthog.api.routing import TeamAndOrgViewSetMixin
@@ -404,7 +404,25 @@ class TaggedItemViewSet(TeamAndOrgViewSetMixin, GenericViewSet):
serializer_class = TaggedItemSerializer
queryset = Tag.objects.none()
+ @extend_schema(
+ parameters=[
+ OpenApiParameter("search", OpenApiTypes.STR, required=False),
+ OpenApiParameter("limit", OpenApiTypes.INT, required=False),
+ OpenApiParameter("offset", OpenApiTypes.INT, required=False),
+ ]
+ )
def list(self, request, *args, **kwargs) -> response.Response:
- return response.Response(
- Tag.objects.filter(team=self.team).values_list("name", flat=True).distinct().order_by("name")
- )
+ tags = Tag.objects.filter(team=self.team).values_list("name", flat=True).distinct().order_by("name")
+ search = request.query_params.get("search")
+
+ if search is None:
+ return response.Response(tags)
+
+ if search:
+ tags = tags.filter(name__icontains=search)
+
+ paginator = pagination.LimitOffsetPagination()
+ paginator.default_limit = 100
+ paginator.max_limit = 100
+ page = paginator.paginate_queryset(tags, request, view=self)
+ return paginator.get_paginated_response(page)
diff --git a/posthog/api/test/test_tagged_item.py b/posthog/api/test/test_tagged_item.py
index 9e1d131a130c..a4a744554b8e 100644
--- a/posthog/api/test/test_tagged_item.py
+++ b/posthog/api/test/test_tagged_item.py
@@ -97,6 +97,15 @@ class TestTaggedItemSerializerMixin(APIBaseTest):
# Tags are returned in alphabetical order regardless of insertion order
assert response.json() == ["apple tag", "zebra tag"]
+ def test_can_search_tags_with_pagination(self) -> None:
+ Tag.objects.bulk_create([Tag(name=f"dashboard-{index:03}", team_id=self.team.id) for index in range(3)])
+
+ response = self.client.get(f"/api/projects/{self.team.id}/tags?search=dashboard&limit=2")
+
+ assert response.status_code == status.HTTP_200_OK
+ assert response.json()["results"] == ["dashboard-000", "dashboard-001"]
+ assert response.json()["next"] is not None
+
class TestBulkUpdateTags(APIBaseTest):
def _bulk_update_url(self):
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 639c79158594..2f091ceb55b9 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -99085,14 +99085,9 @@ export namespace Schemas {
};
export type TagsListParams = {
- /**
- * Number of results to return per page.
- */
limit?: number;
- /**
- * The initial index from which to return the results.
- */
offset?: number;
+ search?: string;
};
export type TaskActivityListParams = {