: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(cross-project-dashboards): picker search and tile removal undo (#112504)
Yasenf21813697179
diff --git a/products/cross_project_dashboards/frontend/AddCrossProjectTileModal.tsx b/products/cross_project_dashboards/frontend/AddCrossProjectTileModal.tsxindex 3f8551444abe..f97c356dfefe 100644--- a/products/cross_project_dashboards/frontend/AddCrossProjectTileModal.tsx+++ b/products/cross_project_dashboards/frontend/AddCrossProjectTileModal.tsx@@ -1,10 +1,23 @@import { useActions, useValues } from 'kea'-import { LemonButton, LemonInputSelect, LemonModal, LemonSelect } from '@posthog/lemon-ui'+import { LemonButton, LemonInputSelect, LemonModal } from '@posthog/lemon-ui'+import { dayjs } from 'lib/dayjs'import { LemonField } from 'lib/lemon-ui/LemonField'-import { addCrossProjectTileLogic } from './addCrossProjectTileLogic'+import { InsightOption, addCrossProjectTileLogic } from './addCrossProjectTileLogic'++function InsightOptionLabel({ insight }: { insight: InsightOption }): JSX.Element {+ const detail = [insight.createdBy, insight.lastModifiedAt && `edited ${dayjs(insight.lastModifiedAt).fromNow()}`]+ .filter(Boolean)+ .join(' · ')+ return (+ <span className="flex items-center gap-2 w-full min-w-0">+ <span className="flex-1 truncate">{insight.name}</span>+ {detail ? <span className="shrink-0 text-xs text-secondary">{detail}</span> : null}+ </span>+ )+}export interface AddCrossProjectTileModalProps {dashboardId: string@@ -25,6 +38,17 @@ export function AddCrossProjectTileModal({ dashboardId }: AddCrossProjectTileMod} = useValues(logic)const { closeModal, setProjectId, setInsight, setInsightSearch, loadMoreInsights, addTile } = useActions(logic)+ const insightsByKey = new Map(+ [...insightPage.insights, ...(selectedInsight ? [selectedInsight] : [])].map((insight) => [+ String(insight.id),+ insight,+ ])+ )+ const loadMoreLabel =+ insightPage.total !== undefined+ ? `Load more insights (${insightPage.insights.length} of ${insightPage.total})`+ : 'Load more insights'+return (<LemonModalisOpen={isOpen}@@ -50,11 +74,14 @@ export function AddCrossProjectTileModal({ dashboardId }: AddCrossProjectTileMod><div className="flex flex-col gap-4 min-w-100"><LemonField.Pure label="Project">- <LemonSelect- value={projectId}- onChange={setProjectId}+ <LemonInputSelect+ mode="single"+ value={projectId ? [String(projectId)] : []}+ onChange={(keys) => setProjectId(keys[0] ? Number(keys[0]) : null)}options={projectOptions}- placeholder="Select a project"+ // An organization can pass the 100 options the plain list stops at.+ virtualized+ placeholder="Search projects"data-attr="cross-project-add-tile-project"fullWidth/>@@ -67,7 +94,12 @@ export function AddCrossProjectTileModal({ dashboardId }: AddCrossProjectTileModsetInsight(insightPage.insights.find((insight) => String(insight.id) === keys[0]) ?? null)}onInputChange={setInsightSearch}- options={insightOptions}+ options={insightOptions.map((option) => {+ const insight = insightsByKey.get(option.key)+ return insight+ ? { ...option, labelComponent: <InsightOptionLabel insight={insight} /> }+ : option+ })}// The search runs on the server, so the list is already the answer to it.disableFiltering// Loaded pages can pass the 100 options the plain list stops at.@@ -78,7 +110,7 @@ export function AddCrossProjectTileModal({ dashboardId }: AddCrossProjectTileModaction={insightPage.hasMore? {- children: 'Load more insights',+ children: loadMoreLabel,onClick: loadMoreInsights,disabledReason: insightPageLoading ? 'Loading insights' : undefined,}diff --git a/products/cross_project_dashboards/frontend/CrossProjectDashboardsList.tsx b/products/cross_project_dashboards/frontend/CrossProjectDashboardsList.tsxindex 44e0e388bd66..99ece053fd1d 100644--- a/products/cross_project_dashboards/frontend/CrossProjectDashboardsList.tsx+++ b/products/cross_project_dashboards/frontend/CrossProjectDashboardsList.tsx@@ -91,6 +91,11 @@ export function CrossProjectDashboardsList(): JSX.Element {<LemonInputvalue={newName}onChange={setNewName}+ onPressEnter={() => {+ if (newName.trim() && !isCreating) {+ createDashboard()+ }+ }}placeholder="Company overview"autoFocusdata-attr="cross-project-dashboard-new-name"diff --git a/products/cross_project_dashboards/frontend/CrossProjectTile.tsx b/products/cross_project_dashboards/frontend/CrossProjectTile.tsxindex dddd69e4a99a..fef48c9f9d66 100644--- a/products/cross_project_dashboards/frontend/CrossProjectTile.tsx+++ b/products/cross_project_dashboards/frontend/CrossProjectTile.tsx@@ -33,7 +33,8 @@ const UNAVAILABLE_COPY: Record<TileUnavailableReason, string> = {function asCardTile(tile: CrossProjectDashboardTileApi): DashboardTile {return {id: tile.id,- filters_overrides: tile.filters_overrides,+ // The card's links carry any override as a URL parameter, an empty one included.+ filters_overrides: Object.keys(tile.filters_overrides ?? {}).length > 0 ? tile.filters_overrides : null,show_description: null,color: tile.color,layouts: tile.layouts,diff --git a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.tsindex 63bd32992d66..e3824d65c5ea 100644--- a/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts+++ b/products/cross_project_dashboards/frontend/addCrossProjectTileLogic.ts@@ -14,11 +14,16 @@ import { crossProjectDashboardsTilesCreate } from './generated/api'export interface InsightOption {id: numbername: string+ /** Shown next to the name, so the picker can tell apart insights that share one. */+ createdBy?: string+ lastModifiedAt?: string}export interface InsightPage {insights: InsightOption[]hasMore: boolean+ /** Insights in the project that match the search, across all pages. */+ total?: number}export interface AddCrossProjectTileLogicProps {@@ -39,10 +44,7 @@ export interface addCrossProjectTileLogicValues {isAdding: booleanisOpen: booleanprojectId: number | null- projectOptions: {- label: string- value: number- }[]+ projectOptions: LemonInputSelectOption[]selectedInsight: InsightOption | null}@@ -108,10 +110,7 @@ export interface addCrossProjectTileLogicActions {export interface addCrossProjectTileLogicMeta {key: string__keaTypeGenInternalSelectorTypes: {- projectOptions: (currentOrganization: null | import('~/types').OrganizationType) => {- label: string- value: number- }[]+ projectOptions: (currentOrganization: null | import('~/types').OrganizationType) => LemonInputSelectOption[]insightOptions: (insightPage: InsightPage, selectedInsight: InsightOption | null) => LemonInputSelectOption[]canAdd: (projectId: number | null, selectedInsight: InsightOption | null) => boolean}@@ -171,8 +170,11 @@ export const addCrossProjectTileLogic = kea<addCrossProjectTileLogicType>([insights: response.results.map((insight) => ({id: insight.id,name: insight.name || insight.derived_name || `Insight ${insight.id}`,+ createdBy: insight.created_by?.first_name || insight.created_by?.email || undefined,+ lastModifiedAt: insight.last_modified_at ?? undefined,})),hasMore: !!response.next,+ total: response.count,}}@@ -201,7 +203,11 @@ export const addCrossProjectTileLogic = kea<addCrossProjectTileLogicType>([if (isStale(projectId, insightSearch)) {return values.insightPage}- return { insights: [...values.insightPage.insights, ...next.insights], hasMore: next.hasMore }+ return {+ insights: [...values.insightPage.insights, ...next.insights],+ hasMore: next.hasMore,+ total: next.total,+ }},},],@@ -210,8 +216,10 @@ export const addCrossProjectTileLogic = kea<addCrossProjectTileLogicType>([selectors({projectOptions: [() => [organizationLogic.selectors.currentOrganization],- (organization: null | import('~/types').OrganizationType) =>- (organization?.projects ?? []).map((project) => ({ value: project.id, label: project.name })),+ (organization: null | import('~/types').OrganizationType): LemonInputSelectOption[] =>+ [...(organization?.projects ?? [])]+ .sort((a, b) => a.name.localeCompare(b.name))+ .map((project) => ({ key: String(project.id), label: project.name })),],// Keeps the picked insight in the options, so the field still shows its name after the search moves on.insightOptions: [diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.tsindex fe7463ec6631..c40a77b10188 100644--- a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.test.ts@@ -2,6 +2,7 @@ import { router } from 'kea-router'import { expectLogic } from 'kea-test-utils'import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { lemonToast } from 'lib/lemon-ui/LemonToast'import { organizationLogic } from 'scenes/organizationLogic'import { initKeaTests } from '~/test/init'@@ -11,6 +12,8 @@ import {crossProjectDashboardsDestroy,crossProjectDashboardsPartialUpdate,crossProjectDashboardsRetrieve,+ crossProjectDashboardsTilesCreate,+ crossProjectDashboardsTilesDestroy,crossProjectDashboardsTilesPartialUpdate,} from './generated/api'@@ -21,6 +24,7 @@ jest.mock('./generated/api', () => ({crossProjectDashboardsDestroy: jest.fn(),crossProjectDashboardsRetrieve: jest.fn(),crossProjectDashboardsPartialUpdate: jest.fn(),+ crossProjectDashboardsTilesCreate: jest.fn(),crossProjectDashboardsTilesDestroy: jest.fn(),crossProjectDashboardsTilesPartialUpdate: jest.fn(),}))@@ -30,6 +34,8 @@ const mockedDestroy = crossProjectDashboardsDestroy as jest.Mockconst mockedRetrieve = crossProjectDashboardsRetrieve as jest.Mockconst mockedPartialUpdate = crossProjectDashboardsPartialUpdate as jest.Mockconst mockedTilePartialUpdate = crossProjectDashboardsTilesPartialUpdate as jest.Mock+const mockedTileCreate = crossProjectDashboardsTilesCreate as jest.Mock+const mockedTileDestroy = crossProjectDashboardsTilesDestroy as jest.Mockconst DASHBOARD_ID = '01a0f19d-1c44-715a-a679-188869bd033f'@@ -61,6 +67,8 @@ describe('crossProjectDashboardLogic', () => {mockedRetrieve.mockReset()mockedPartialUpdate.mockReset()mockedTilePartialUpdate.mockReset()+ mockedTileCreate.mockReset()+ mockedTileDestroy.mockReset()mockedTilePartialUpdate.mockImplementation(async (_org, _id, tileId, body) => ({...TILE,id: tileId,@@ -120,6 +128,45 @@ describe('crossProjectDashboardLogic', () => {expect(logic.values.dashboardFilters).toEqual({ date_from: '-7d' })})+ it('restores a removed tile with its layout, color and filters when the person clicks Undo', async () => {+ const styledTile = {+ ...TILE,+ layouts: { sm: { x: 6, y: 0, w: 6, h: 5 } },+ color: 'green',+ filters_overrides: { date_from: '-30d' },+ }+ // The mocks keep a tile list, so each reload reads back what the delete and the create left.+ let storedTiles: Record<string, unknown>[] = [styledTile]+ mockedRetrieve.mockImplementation(async () => ({ ...dashboardWith({}), tiles: storedTiles }))+ mockedTileDestroy.mockImplementation(async (_org, _id, tileId) => {+ storedTiles = storedTiles.filter((tile) => tile.id !== tileId)+ })+ mockedTileCreate.mockImplementation(async (_org, _id, body) => {+ storedTiles = [...storedTiles, { id: 'tile-restored', ...body }]+ })+ const toastInfo = jest.spyOn(lemonToast, 'info')+ await mountWith({})++ logic.actions.removeTile(styledTile.id)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.tiles).toEqual([])+ // A second click lands while the toast closes, before the first restore returns.+ toastInfo.mock.calls[0][1]?.button?.action()+ toastInfo.mock.calls[0][1]?.button?.action()+ await expectLogic(logic).toFinishAllListeners()++ expect(mockedTileCreate).toHaveBeenCalledTimes(1)+ expect(logic.values.tiles).toEqual([expect.objectContaining({ id: 'tile-restored' })])++ expect(mockedTileCreate).toHaveBeenCalledWith('org-1', DASHBOARD_ID, {+ project_id: styledTile.project_id,+ insight_id: styledTile.insight_id,+ layouts: styledTile.layouts,+ color: styledTile.color,+ filters_overrides: styledTile.filters_overrides,+ })+ })+it('keeps both of two quick filter edits instead of letting the second overwrite the first', async () => {await mountWith({})diff --git a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.tsindex 66766f683b9b..2ef2bcdb965a 100644--- a/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts+++ b/products/cross_project_dashboards/frontend/crossProjectDashboardLogic.ts@@ -18,6 +18,7 @@ import {crossProjectDashboardsDestroy,crossProjectDashboardsPartialUpdate,crossProjectDashboardsRetrieve,+ crossProjectDashboardsTilesCreate,crossProjectDashboardsTilesDestroy,crossProjectDashboardsTilesPartialUpdate,} from './generated/api'@@ -118,6 +119,9 @@ export interface crossProjectDashboardLogicActions {removeTile: (tileId: string) => {tileId: string}+ restoreTile: (tile: CrossProjectDashboardTileApi) => {+ tile: CrossProjectDashboardTileApi+ }saveLayout: () => {value: true}@@ -204,6 +208,7 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([actions({loadDashboard: true,removeTile: (tileId: string) => ({ tileId }),+ restoreTile: (tile: CrossProjectDashboardTileApi) => ({ tile }),setDates: (dateFrom: string | null, dateTo: string | null) => ({ dateFrom, dateTo }),setInterval: (interval: IntervalType | null) => ({ interval }),enterLayoutEdit: true,@@ -314,6 +319,8 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([// Saves send the whole filters object, so they run one at a time to never start from a stale copy.// A rename joins the same queue, so a late response cannot put back filters that a newer save replaced.let saves: Promise<boolean> = Promise.resolve(true)+ // Undo stays clickable while its toast closes, and a second restore of the same tile fails as a duplicate.+ const restoringTileIds = new Set<string>()const saveDashboard = (changes: () => PatchedCrossProjectDashboardApi,errorMessage: string@@ -477,13 +484,42 @@ export const crossProjectDashboardLogic = kea<crossProjectDashboardLogicType>([if (!organizationId) {return}+ const removedTile = values.tiles.find((tile) => tile.id === tileId)try {await crossProjectDashboardsTilesDestroy(organizationId, props.id, tileId)+ if (removedTile) {+ lemonToast.info('Tile removed from the dashboard', {+ button: { label: 'Undo', action: () => actions.restoreTile(removedTile) },+ })+ }} catch (error: any) {lemonToast.error(error?.detail || 'Could not remove that tile. Try again.')}actions.loadDashboard()},+ // Removal deletes the tile, so undo adds it back with everything it carried.+ restoreTile: async ({ tile }) => {+ const organizationId = organizationLogic.values.currentOrganization?.id+ if (!organizationId || restoringTileIds.has(tile.id)) {+ return+ }+ restoringTileIds.add(tile.id)+ try {+ await crossProjectDashboardsTilesCreate(organizationId, props.id, {+ project_id: tile.project_id,+ insight_id: tile.insight_id,+ layouts: tile.layouts,+ color: tile.color,+ filters_overrides: tile.filters_overrides,+ })+ lemonToast.success('Tile restored')+ } catch (error: any) {+ lemonToast.error(error?.detail || 'Could not restore the tile. Add the insight again.')+ } finally {+ restoringTileIds.delete(tile.id)+ }+ actions.loadDashboard()+ },}}),beforeUnload(({ values, actions }) => ({