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(frontend): improve narrow dashboard and subscription layouts (#106295)

Matt Pua570dde4eb11b
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 3981b5fd50c8..c3147938ca60 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6841,13 +6841,13 @@ snapshots:
products-subscriptions-subscription-delivery-history--with-expanded-summary--light:
hash: v1.k794b7964.e8ea5acdf82c72e927990f4672e1615f9b8269abc31a3feb639fa9b993babad0.5j1v9u_2-7CyIDaD0INwHMOAarvZot8UsqYDMVc0UAE
products-subscriptions-subscriptions-modal--dashboard-with-subscriptions--dark:
- hash: v1.k794b7964.34be5065c2a6641f0ad2a24e1dc57e6505d59ef2757dfe1e720d7d5de9ec33c5.50acEl5pVMJGUvu24toA5wvLdYXmqldRUH0gbdbdZgM
+ hash: v1.k794b7964.c40534e6ed4ad299ed4b0317035ef2867ce1fa1dd9400dc05f63b58fafa2f3a8.uhuetA6HfBqWc8E72Mnwihnwg71M7zKnXlzl9FEAJmY
products-subscriptions-subscriptions-modal--dashboard-with-subscriptions--light:
- hash: v1.k794b7964.bc54b9d5571ad9aa342a092e9bfee263d87d3ca472b5475a82a0d314a2e261bb.KWqAhfaruwwC3f5RvtDhs9Tob0nYttE25oTOydFDAzs
+ hash: v1.k794b7964.c15899635ef0c3648db8eea7d84a56aea8f21c330f9d01b75081b7a861db8acb.eCh5Pi_muj3UGT2YbhFeCMZUWyiag2nzZEaPHZM8mGs
products-subscriptions-subscriptions-modal--insight-with-subscriptions--dark:
- hash: v1.k794b7964.fdd194fa7f91e1eaa642256ba2dd7e0951bc382b7df24e39c504ba428cfabe0a.KLwxXJI2yw_P7hQMu-vHOJKoXi4mSHf3IVabPbV2vdM
+ hash: v1.k794b7964.2a76c5dee0d1163aa0b18c73a84aa4e1a0eeff1d28ac11dc69f341a2003adf03.tKxC779rDOtgJwDHbTTavTlMZQ2os8NBgr6GKwmSdiM
products-subscriptions-subscriptions-modal--insight-with-subscriptions--light:
- hash: v1.k794b7964.0850b21723e94659d48e7930f44b3806423409fa4e324370cea825f7ee834371.uKJgYFJ-_LNL0M6CQHDlG1kNfpEccF8eSmPDv3hO-1c
+ hash: v1.k794b7964.12c1d929119ea21b339d2fd3b7dfe4ae37b5f465b3b3d6760263521d51823d03.fPCViqa6g5lL6J66e8lYzVswb7rr8uEQXpLAqptOCPk
products-subscriptions-subscriptions-modal--long-ai-prompt--dark:
hash: v1.k794b7964.4248b9034e799f5515f79e1ce1be94acbf161108a113024a695378bbf6f91964.nU8G1dPefUfme1EtuazK3GPd4iK3QnD3f1z8N9F6FwI
products-subscriptions-subscriptions-modal--long-ai-prompt--light:
@@ -6857,9 +6857,9 @@ snapshots:
products-subscriptions-subscriptions-modal--subscriptions-new--light:
hash: v1.k794b7964.a25e52c871d0eda0d3aa152eae70692b6e7afdce17781140e344d9118222c5a0.Gkor9YbakPCnaMSX1yE-zSLAdW5BiqviNdUEPOid_40
products-subscriptions-subscriptions-modal--subscriptions-tabbed--dark:
- hash: v1.k794b7964.1f9aa8adee753b12e1b50c143ed4e2eed36a5ceaea7f934a43cb16b16ff9974a.KtXqx6ZGFgLFGRPjRxGd10KmRLwCgZPyMSowVK2PPKg
+ hash: v1.k794b7964.c40534e6ed4ad299ed4b0317035ef2867ce1fa1dd9400dc05f63b58fafa2f3a8.VAJTkZ_eMTUy7drF60jNdhkCX-qvYPCia-CXXFTzGDg
products-subscriptions-subscriptions-modal--subscriptions-tabbed--light:
- hash: v1.k794b7964.91be617dbb895598296bf9370e60fb6406ea394392bb5d8a0a85a1991c91962c.2EVEcja1V1g6msLBVlGDWjDKr5VTuFGqt5byG97YtTA
+ hash: v1.k794b7964.c15899635ef0c3648db8eea7d84a56aea8f21c330f9d01b75081b7a861db8acb.genIZt2wCwgSFzhBKwOZIWOffAwnHk3g1mBZ3XKPvn0
products-subscriptions-subscriptions-table--default--dark:
hash: v1.k794b7964.53cf84a8e66f2c6598a8b17644138403b0b118cd36d2c87e070516f235f0998c.OIIaEVja8iIKsAUIxOpPy6o-5Ior7lV4Fb7nbcPIkzs
products-subscriptions-subscriptions-table--default--light:
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
index 18d454beda67..4b6d7769cb2d 100644
--- a/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardInsightDisplayOptions.tsx
@@ -1,3 +1,5 @@
+import { IconChevronRight } from '@posthog/icons'
+
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
@@ -35,7 +37,9 @@ export function DashboardInsightDisplayOptions({
placement="right-start"
fallbackPlacements={['left-start']}
>
- <LemonButton fullWidth>Display options</LemonButton>
+ <LemonButton fullWidth sideIcon={<IconChevronRight className="size-3" />}>
+ Display options
+ </LemonButton>
</LemonDropdown>
</>
)
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
index 21176089d65f..1141a7bc4288 100644
--- a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
@@ -1,6 +1,8 @@
import { useActions, useValues } from 'kea'
import { useCallback, useState } from 'react'
+import { IconChevronRight } from '@posthog/icons'
+
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonMenu, LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
@@ -128,7 +130,9 @@ export function DashboardWidgetPlacementMenu({
}
}}
>
- <LemonButton fullWidth>{label}</LemonButton>
+ <LemonButton fullWidth sideIcon={<IconChevronRight className="size-3" />}>
+ {label}
+ </LemonButton>
</LemonMenu>
)
}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index c61ab40041d1..ff6b7db11cc6 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -50,6 +50,7 @@ import { DashboardResizeHandles } from '../handles'
import { EditModeEdge, EditModeEdgeOverlay } from './EditModeEdgeOverlay'
import { INSIGHT_CARD_KEY_ATTR, insightCardKey } from './insightCardImageCapture'
import { InsightMeta } from './InsightMeta'
+import { InsightVisualizationSkeleton } from './InsightVisualizationSkeleton'
const IS_STORYBOOK = inStorybook() || inStorybookTestRunner()
@@ -440,7 +441,9 @@ function InsightCardInternal(
// Only canvas viz (charts) redraw per resize frame; tables/numbers/maps are cheap DOM/SVG and stay fully live.
const vizContent = shouldRenderViz ? (
<ResizeThrottledViz throttled={!!isResizing && rendersToCanvas}>{vizInner}</ResizeThrottledViz>
- ) : null
+ ) : (
+ <InsightVisualizationSkeleton query={insight.query} />
+ )
return (
<div
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 74437ec3c49a..1039c0518590 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -2,7 +2,15 @@ import clsx from 'clsx'
import { useActions, useValues } from 'kea'
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
-import { IconClock, IconInfo, IconPulse, IconThumbsDown, IconThumbsUp, IconWarning } from '@posthog/icons'
+import {
+ IconChevronRight,
+ IconClock,
+ IconInfo,
+ IconPulse,
+ IconThumbsDown,
+ IconThumbsUp,
+ IconWarning,
+} from '@posthog/icons'
import { lemonToast } from '@posthog/lemon-ui'
import { CardMeta } from 'lib/components/Cards/CardMeta'
@@ -621,7 +629,9 @@ export function InsightMeta({
fallbackPlacements={['left-start']}
closeParentPopoverOnClickInside
>
- <LemonButton fullWidth>Set color</LemonButton>
+ <LemonButton fullWidth sideIcon={<IconChevronRight className="size-3" />}>
+ Set color
+ </LemonButton>
</LemonMenu>
)}
{hasDashboardPlacementActions && (
@@ -671,6 +681,7 @@ export function InsightMeta({
<LemonDivider />
<ExportButton
fullWidth
+ sideIcon={<IconChevronRight className="size-3" />}
items={[
{
export_format: ExporterFormat.PNG,
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightVisualizationSkeleton.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightVisualizationSkeleton.tsx
new file mode 100644
index 000000000000..93b65b203952
--- /dev/null
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightVisualizationSkeleton.tsx
@@ -0,0 +1,94 @@
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+
+import { InsightModel } from '~/types'
+
+import { visualizationShape } from './visualizationShape'
+
+const BAR_HEIGHTS = ['h-2/5', 'h-3/5', 'h-1/2', 'h-4/5', 'h-2/3', 'h-3/4', 'h-1/3', 'h-3/5']
+const FUNNEL_WIDTHS = ['w-full', 'w-4/5', 'w-3/5', 'w-2/5']
+export function InsightVisualizationSkeleton({ query }: { query: InsightModel['query'] }): JSX.Element {
+ const shape = visualizationShape(query)
+
+ let chart: JSX.Element
+ if (shape === 'number') {
+ chart = (
+ <div className="flex flex-1 flex-col items-center justify-center gap-4">
+ <LemonSkeleton className="h-12 w-1/3" active={false} />
+ <LemonSkeleton className="h-3 w-1/4" active={false} />
+ </div>
+ )
+ } else if (shape === 'pie' || shape === 'donut') {
+ chart = (
+ <div className="flex flex-1 flex-wrap items-center justify-center gap-4">
+ <div className="relative size-28 shrink-0">
+ <svg viewBox="0 0 100 100" className="size-full">
+ <path d="M50 50 L50 0 A50 50 0 0 1 97 67 Z" fill="var(--color-skeleton-dark)" />
+ <path d="M50 50 L97 67 A50 50 0 0 1 3 67 Z" fill="var(--color-skeleton-light)" />
+ <path d="M50 50 L3 67 A50 50 0 0 1 50 0 Z" fill="var(--color-skeleton-dark)" />
+ </svg>
+ {shape === 'donut' && <div className="absolute inset-8 rounded-full bg-surface-primary" />}
+ </div>
+ <div className="flex flex-col gap-4">
+ <LemonSkeleton className="h-3 w-20" active={false} />
+ <LemonSkeleton className="h-3 w-16" active={false} />
+ <LemonSkeleton className="h-3 w-20" active={false} />
+ </div>
+ </div>
+ )
+ } else if (shape === 'table' || shape === 'heatmap') {
+ const rowCount = shape === 'heatmap' ? 3 : 5
+ const columnCount = shape === 'heatmap' ? 5 : 3
+ chart = (
+ <div className="flex flex-1 flex-col justify-around gap-2">
+ {Array.from({ length: rowCount }, (_, rowIndex) => (
+ <div key={rowIndex} className="flex flex-1 gap-3">
+ {Array.from({ length: columnCount }, (_, columnIndex) => (
+ <LemonSkeleton key={columnIndex} className="h-full flex-1" active={false} />
+ ))}
+ </div>
+ ))}
+ </div>
+ )
+ } else if (shape === 'funnel') {
+ chart = (
+ <div className="flex flex-1 flex-col items-center justify-center gap-4">
+ {FUNNEL_WIDTHS.map((widthClass) => (
+ <LemonSkeleton key={widthClass} className={`h-9 ${widthClass}`} active={false} />
+ ))}
+ </div>
+ )
+ } else {
+ const plot =
+ shape === 'bar' ? (
+ BAR_HEIGHTS.map((heightClass, index) => (
+ <LemonSkeleton key={index} className={`flex-1 ${heightClass}`} active={false} />
+ ))
+ ) : (
+ <svg viewBox="0 0 320 160" preserveAspectRatio="none" className="size-full">
+ <path
+ d="M0 125 C35 120 55 45 90 85 S135 145 175 65 S235 115 270 45 S305 70 320 20"
+ fill="none"
+ stroke="var(--color-skeleton-dark)"
+ strokeWidth="4"
+ vectorEffect="non-scaling-stroke"
+ />
+ </svg>
+ )
+ chart = (
+ <>
+ <div className="flex flex-1 min-h-0 items-end gap-2 border-b border-l border-primary p-3">{plot}</div>
+ <div className="flex justify-between gap-3">
+ {Array.from({ length: 5 }, (_, index) => (
+ <LemonSkeleton key={index} className="h-2 w-8" active={false} />
+ ))}
+ </div>
+ </>
+ )
+ }
+
+ return (
+ <div className="InsightCard__viz p-4" aria-hidden="true">
+ <div className="flex flex-1 min-h-0 flex-col gap-3">{chart}</div>
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/Cards/InsightCard/visualizationShape.test.ts b/frontend/src/lib/components/Cards/InsightCard/visualizationShape.test.ts
new file mode 100644
index 000000000000..c678ebb33146
--- /dev/null
+++ b/frontend/src/lib/components/Cards/InsightCard/visualizationShape.test.ts
@@ -0,0 +1,55 @@
+import { NodeKind } from '~/queries/schema/schema-general'
+import { ChartDisplayType, FunnelVizType, InsightModel } from '~/types'
+
+import { visualizationShape } from './visualizationShape'
+
+describe('visualizationShape', () => {
+ const dataVisualization = (display?: ChartDisplayType): InsightModel['query'] =>
+ ({ kind: NodeKind.DataVisualizationNode, display }) as InsightModel['query']
+
+ const insightVisualization = (source: object): InsightModel['query'] =>
+ ({ kind: NodeKind.InsightVizNode, source }) as InsightModel['query']
+
+ test.each([
+ ['data table', { kind: NodeKind.DataTableNode }, 'table'],
+ ['SQL default', dataVisualization(), 'table'],
+ ['SQL bars', dataVisualization(ChartDisplayType.ActionsBar), 'bar'],
+ ['SQL pie', dataVisualization(ChartDisplayType.ActionsPie), 'pie'],
+ ['SQL donut', dataVisualization(ChartDisplayType.ActionsDonut), 'donut'],
+ ['SQL number', dataVisualization(ChartDisplayType.BoldNumber), 'number'],
+ ['SQL heatmap', dataVisualization(ChartDisplayType.CalendarHeatmap), 'heatmap'],
+ ['SQL line', dataVisualization(ChartDisplayType.ActionsLineGraph), 'line'],
+ ['retention', insightVisualization({ kind: NodeKind.RetentionQuery }), 'table'],
+ ['paths', insightVisualization({ kind: NodeKind.PathsQuery }), 'table'],
+ ['funnel', insightVisualization({ kind: NodeKind.FunnelsQuery, series: [] }), 'funnel'],
+ [
+ 'funnel trends',
+ insightVisualization({
+ kind: NodeKind.FunnelsQuery,
+ series: [],
+ funnelsFilter: { funnelVizType: FunnelVizType.Trends },
+ }),
+ 'line',
+ ],
+ [
+ 'funnel time to convert',
+ insightVisualization({
+ kind: NodeKind.FunnelsQuery,
+ series: [],
+ funnelsFilter: { funnelVizType: FunnelVizType.TimeToConvert },
+ }),
+ 'table',
+ ],
+ [
+ 'trend display',
+ insightVisualization({
+ kind: NodeKind.TrendsQuery,
+ series: [],
+ trendsFilter: { display: ChartDisplayType.ActionsBar },
+ }),
+ 'bar',
+ ],
+ ] as const)('%s uses a %s skeleton', (_name, query, expected) => {
+ expect(visualizationShape(query as InsightModel['query'])).toBe(expected)
+ })
+})
diff --git a/frontend/src/lib/components/Cards/InsightCard/visualizationShape.ts b/frontend/src/lib/components/Cards/InsightCard/visualizationShape.ts
new file mode 100644
index 000000000000..8926782ac786
--- /dev/null
+++ b/frontend/src/lib/components/Cards/InsightCard/visualizationShape.ts
@@ -0,0 +1,73 @@
+import {
+ getDisplay,
+ isDataTableNode,
+ isDataVisualizationNode,
+ isFunnelsQuery,
+ isInsightVizNode,
+ isPathsQuery,
+ isRetentionQuery,
+} from '~/queries/utils'
+import { ChartDisplayType, FunnelVizType, InsightModel } from '~/types'
+
+type VisualizationShape = 'line' | 'bar' | 'pie' | 'donut' | 'number' | 'table' | 'heatmap' | 'funnel'
+
+const warnedDisplays = new Set<string>()
+
+export function visualizationShape(query: InsightModel['query']): VisualizationShape {
+ if (isDataTableNode(query)) {
+ return 'table'
+ }
+
+ let display: ChartDisplayType | undefined
+ if (isDataVisualizationNode(query)) {
+ display = query.display ?? ChartDisplayType.ActionsTable
+ } else if (isInsightVizNode(query)) {
+ const source = query.source
+ if (isRetentionQuery(source) || isPathsQuery(source)) {
+ return 'table'
+ }
+ if (isFunnelsQuery(source)) {
+ if (source.funnelsFilter?.funnelVizType === FunnelVizType.TimeToConvert) {
+ return 'table'
+ }
+ return source.funnelsFilter?.funnelVizType === FunnelVizType.Trends ? 'line' : 'funnel'
+ }
+ display = getDisplay(source)
+ }
+
+ switch (display) {
+ case ChartDisplayType.ActionsBar:
+ case ChartDisplayType.ActionsUnstackedBar:
+ case ChartDisplayType.ActionsStackedBar:
+ case ChartDisplayType.ActionsBarValue:
+ case ChartDisplayType.BoxPlot:
+ return 'bar'
+ case ChartDisplayType.ActionsPie:
+ return 'pie'
+ case ChartDisplayType.ActionsDonut:
+ return 'donut'
+ case ChartDisplayType.BoldNumber:
+ case ChartDisplayType.Metric:
+ return 'number'
+ case ChartDisplayType.ActionsTable:
+ case ChartDisplayType.Auto:
+ return 'table'
+ case ChartDisplayType.CalendarHeatmap:
+ case ChartDisplayType.TwoDimensionalHeatmap:
+ case ChartDisplayType.WorldMap:
+ return 'heatmap'
+ case ChartDisplayType.ActionsLineGraph:
+ case ChartDisplayType.ActionsAreaGraph:
+ case ChartDisplayType.ActionsLineGraphCumulative:
+ case ChartDisplayType.SlopeGraph:
+ case ChartDisplayType.ScatterPlot:
+ return 'line'
+ default:
+ display satisfies undefined
+ if (display !== undefined && !warnedDisplays.has(display)) {
+ warnedDisplays.add(display)
+ console.warn('Unknown chart display type for visualization skeleton:', display)
+ }
+ return 'line'
+ }
+}
diff --git a/frontend/src/scenes/dashboard/DashboardCustomizeButton.tsx b/frontend/src/scenes/dashboard/DashboardCustomizeButton.tsx
index bfdfc949a63d..09115595c22a 100644
--- a/frontend/src/scenes/dashboard/DashboardCustomizeButton.tsx
+++ b/frontend/src/scenes/dashboard/DashboardCustomizeButton.tsx
@@ -1,11 +1,11 @@
-import { useActions } from 'kea'
+import { useActions, useValues } from 'kea'
import { IconGridMasonry } from '@posthog/icons'
import { Shortcut } from 'lib/components/Shortcuts/Shortcut'
import { keyBinds } from 'lib/components/Shortcuts/shortcuts'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
-import { LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu'
+import { LemonMenu, LemonMenuOverlay } from 'lib/lemon-ui/LemonMenu'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import { Scene } from 'scenes/sceneTypes'
@@ -15,6 +15,27 @@ import { dashboardLogic } from './dashboardLogic'
export function DashboardCustomizeButton(): JSX.Element {
const { setDashboardEditing } = useActions(dashboardLogic)
+ const { currentLayoutSize } = useValues(dashboardLogic)
+ const layoutAvailable = currentLayoutSize !== 'xs'
+
+ if (!layoutAvailable) {
+ return (
+ <LemonMenu
+ items={[{ label: () => <DashboardCustomizeMenu /> }]}
+ closeOnClickInside={false}
+ placement="bottom-end"
+ >
+ <LemonButton
+ type="secondary"
+ data-attr="dashboard-edit-layout-customize-dropdown"
+ size="small"
+ icon={<IconGridMasonry fontSize="16" />}
+ >
+ Customize
+ </LemonButton>
+ </LemonMenu>
+ )
+ }
return (
<Shortcut
diff --git a/frontend/src/scenes/dashboard/DashboardHeader.test.tsx b/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
index 100a07e68f22..7aa545c0cd3d 100644
--- a/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeader.test.tsx
@@ -1,6 +1,6 @@
import '@testing-library/jest-dom'
-import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
import { BindLogic } from 'kea'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
@@ -143,6 +143,7 @@ describe('DashboardHeader', () => {
tiles: [{ id: 1, color: null, layouts: {}, text: { body: 'Dashboard note' } }],
})
const { logic } = renderHeader({ dashboard, dashboardEditing })
+ act(() => logic.actions.updateContainerWidth(1200, 12))
fireEvent.keyDown(document.body, { key: 'e', code: 'KeyE' })
@@ -155,6 +156,33 @@ describe('DashboardHeader', () => {
}
)
+ it.each([600, 768])('shows customization without layout editing at %ipx', async (width) => {
+ const originalWidth = window.innerWidth
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: width })
+ window.dispatchEvent(new Event('resize'))
+
+ try {
+ const dashboard = makeDashboard({
+ tiles: [{ id: 1, color: null, layouts: {}, text: { body: 'Dashboard note' } }],
+ })
+ const { logic } = renderHeader({ dashboard })
+
+ expect(document.querySelector('[data-attr="dashboard-edit-mode-button"]')).not.toBeInTheDocument()
+ expect(document.querySelector('[data-attr="dashboard-edit-layout-customize-dropdown"]')).toBeInTheDocument()
+ fireEvent.click(
+ document.querySelector('[data-attr="dashboard-edit-layout-customize-dropdown"]') as HTMLElement
+ )
+ expect(await screen.findByText('Tile density')).toBeInTheDocument()
+ expect(screen.queryByText('When you move a tile')).not.toBeInTheDocument()
+ expect(logic.values.layoutEditMode).toBe(false)
+
+ logic.unmount()
+ } finally {
+ Object.defineProperty(window, 'innerWidth', { configurable: true, value: originalWidth })
+ window.dispatchEvent(new Event('resize'))
+ }
+ })
+
it('recognizes sandbox insight calls that add to the open dashboard', () => {
expect(insightIsAddedToDashboard({ dashboards: ['5', 8] }, 5)).toBe(true)
expect(insightIsAddedToDashboard({ dashboards: [8] }, 5)).toBe(false)
diff --git a/frontend/src/scenes/dashboard/DashboardScenePanel.tsx b/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
index def3d9fd51cf..6e8251ba6cd9 100644
--- a/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
+++ b/frontend/src/scenes/dashboard/DashboardScenePanel.tsx
@@ -9,7 +9,6 @@ import { SceneDuplicate } from 'lib/components/Scenes/SceneDuplicate'
import { SceneFile } from 'lib/components/Scenes/SceneFile'
import { SceneFullscreen } from 'lib/components/Scenes/SceneFullscreen'
import { SceneMetalyticsSummaryButton } from 'lib/components/Scenes/SceneMetalyticsSummaryButton'
-import { ScenePin } from 'lib/components/Scenes/ScenePin'
import { SceneSubscribeButton } from 'lib/components/Scenes/SceneSubscribeButton'
import { SceneTags } from 'lib/components/Scenes/SceneTags'
import { SceneActivityIndicator } from 'lib/components/Scenes/SceneUpdateActivityInfo'
@@ -46,13 +45,12 @@ export function DashboardScenePanel(): JSX.Element | null {
dashboardMode,
canEditDashboard,
isSavingTags,
- isPinned,
asDashboardTemplate,
currentDashboardVariables,
apiUrl,
tiles,
} = useValues(dashboardLogic)
- const { setDashboardMode, updateDashboardTags, togglePinned, setTerraformModalOpen } = useActions(dashboardLogic)
+ const { setDashboardMode, updateDashboardTags, setTerraformModalOpen } = useActions(dashboardLogic)
const { createNotebookFromDashboard } = useActions(notebooksModel)
const { showInsightColorsModal } = useActions(dashboardInsightColorsModalLogic)
const { showDuplicateDashboardModal } = useActions(duplicateDashboardLogic)
@@ -99,7 +97,6 @@ export function DashboardScenePanel(): JSX.Element | null {
Copy to another project
</ButtonPrimitive>
)}
- <ScenePin dataAttrKey={RESOURCE_TYPE} onClick={togglePinned} isPinned={isPinned} />
<SceneFullscreen
dataAttrKey={RESOURCE_TYPE}
onClick={() => {
diff --git a/frontend/src/scenes/dashboard/DuplicateDashboardModal.tsx b/frontend/src/scenes/dashboard/DuplicateDashboardModal.tsx
index ce71412e815e..65da0ff48dcf 100644
--- a/frontend/src/scenes/dashboard/DuplicateDashboardModal.tsx
+++ b/frontend/src/scenes/dashboard/DuplicateDashboardModal.tsx
@@ -8,13 +8,14 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'
export function DuplicateDashboardModal(): JSX.Element {
- const { hideDuplicateDashboardModal, duplicateAndGoToDashboard } = useActions(duplicateDashboardLogic)
- const { isDuplicateDashboardSubmitting, duplicateDashboardModalVisible } = useValues(duplicateDashboardLogic)
+ const { hideDuplicateDashboardModal } = useActions(duplicateDashboardLogic)
+ const { isDuplicateDashboardSubmitting, duplicateDashboardModalVisible, duplicateRequestId } =
+ useValues(duplicateDashboardLogic)
return (
<LemonModal
title="Duplicate dashboard"
- onClose={hideDuplicateDashboardModal}
+ onClose={duplicateRequestId === null ? hideDuplicateDashboardModal : undefined}
isOpen={duplicateDashboardModalVisible}
footer={
<>
@@ -22,27 +23,18 @@ export function DuplicateDashboardModal(): JSX.Element {
form="new-dashboard-form"
type="secondary"
data-attr="dashboard-cancel"
- disabled={isDuplicateDashboardSubmitting}
+ disabled={isDuplicateDashboardSubmitting || duplicateRequestId !== null}
onClick={hideDuplicateDashboardModal}
>
Cancel
</LemonButton>
- <LemonButton
- form="new-dashboard-form"
- type="secondary"
- data-attr="dashboard-submit-and-go"
- disabled={isDuplicateDashboardSubmitting}
- onClick={duplicateAndGoToDashboard}
- >
- Duplicate and go to dashboard
- </LemonButton>
<LemonButton
form="duplicate-dashboard-form"
htmlType="submit"
type="primary"
data-attr="duplicate-dashboard-submit"
- loading={isDuplicateDashboardSubmitting}
- disabled={isDuplicateDashboardSubmitting}
+ loading={isDuplicateDashboardSubmitting || duplicateRequestId !== null}
+ disabled={isDuplicateDashboardSubmitting || duplicateRequestId !== null}
>
Duplicate
</LemonButton>
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
index edf3c5f17b78..818e27ea97bc 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.test.tsx
@@ -2,6 +2,10 @@ import '@testing-library/jest-dom'
import { cleanup, fireEvent, render, screen } from '@testing-library/react'
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
+
+import { Scene } from 'scenes/sceneTypes'
+import { urls } from 'scenes/urls'
import { AccessControlLevel } from '~/types'
@@ -33,6 +37,7 @@ jest.mock('lib/lemon-ui/LemonTable', () => ({
describe('DashboardsTable move to folder', () => {
const moveDashboardsToFolder = jest.fn()
+ const setHomepage = jest.fn()
const clearSelection = jest.fn()
const setSelectedKeys = jest.fn()
@@ -47,6 +52,7 @@ describe('DashboardsTable move to folder', () => {
showDuplicateDashboardModal: jest.fn(),
showDeleteDashboardModal: jest.fn(),
moveDashboardsToFolder,
+ setHomepage,
})
})
@@ -54,12 +60,17 @@ describe('DashboardsTable move to folder', () => {
rows: number[],
selectedKeys: number[] = [],
filedRows: number[] = rows,
- tags?: string[]
+ tags?: string[],
+ primaryDashboard?: number,
+ homepageDashboard?: number,
+ homepageSaving: boolean = false
): void => {
;(useValues as jest.Mock).mockReturnValue({
tableSorting: null,
filters: { search: '' },
- currentTeam: { id: 1 },
+ currentTeam: { id: 1, primary_dashboard: primaryDashboard },
+ homepage: homepageDashboard ? { id: `homepage-dashboard-${homepageDashboard}` } : null,
+ homepageSaving,
filedDashboardIds: new Set(filedRows),
})
mockCtx = { selectedKeys, clearSelection, setSelectedKeys }
@@ -78,6 +89,37 @@ describe('DashboardsTable move to folder', () => {
)
}
+ it("sets only the current user's homepage from the row menu", () => {
+ const capture = jest.spyOn(posthog, 'capture')
+ renderTable([1, 2], [], [1, 2], undefined, 1, 2)
+
+ expect(screen.getByText('Your homepage')).toBeInTheDocument()
+ expect(screen.getAllByText('Set as my homepage')).toHaveLength(1)
+ fireEvent.click(screen.getByText('Set as my homepage'))
+
+ expect(setHomepage).toHaveBeenCalledWith(
+ expect.objectContaining({
+ id: 'homepage-dashboard-1',
+ pathname: urls.dashboard(1),
+ title: 'Dashboard 1',
+ sceneId: Scene.Dashboard,
+ }),
+ 'dashboards list'
+ )
+ expect(capture).toHaveBeenCalledWith('dashboard set as homepage clicked', { source: 'dashboards list' })
+ capture.mockRestore()
+ })
+
+ it('disables homepage selection while another dashboard is saving', () => {
+ renderTable([1, 2], [], [1, 2], undefined, undefined, undefined, true)
+
+ for (const button of screen.getAllByText('Set as my homepage')) {
+ expect(button.closest('button')).toHaveAttribute('aria-disabled', 'true')
+ }
+ fireEvent.click(screen.getAllByText('Set as my homepage')[0])
+ expect(setHomepage).not.toHaveBeenCalled()
+ })
+
it('offers the per-row move action and moves that dashboard', () => {
renderTable([1])
fireEvent.click(screen.getByText('Move to another folder'))
diff --git a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
index 446381540b8d..bc1aa9359ee2 100644
--- a/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
+++ b/frontend/src/scenes/dashboard/dashboards/DashboardsTable.tsx
@@ -1,4 +1,5 @@
import { useActions, useValues } from 'kea'
+import posthog from 'posthog-js'
import { IconFolder, IconHome, IconLock, IconPin, IconPinFilled, IconShare } from '@posthog/icons'
@@ -20,6 +21,9 @@ import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { dashboardsLogic } from 'scenes/dashboard/dashboards/dashboardsLogic'
import { deleteDashboardLogic } from 'scenes/dashboard/deleteDashboardLogic'
import { duplicateDashboardLogic } from 'scenes/dashboard/duplicateDashboardLogic'
+import { sceneLogic } from 'scenes/sceneLogic'
+import { emptySceneParams } from 'scenes/scenes'
+import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
@@ -87,6 +91,8 @@ export function DashboardsTable({
// while the user has an active search term.
const effectiveTableSorting = filters.search ? null : tableSorting
const { currentTeam } = useValues(teamLogic)
+ const { homepage, homepageSaving } = useValues(sceneLogic)
+ const { setHomepage } = useActions(sceneLogic)
const { showDuplicateDashboardModal } = useActions(duplicateDashboardLogic)
const { showDeleteDashboardModal } = useActions(deleteDashboardLogic)
@@ -291,17 +297,37 @@ export function DashboardsTable({
<LemonDivider />
- <LemonRow
- icon={<IconHome className="size-4 text-warning" />}
- fullWidth
- status="warning"
- >
- <span className="text-secondary">
- Change the default dashboard
- <br />
- from the <Link to={urls.projectHomepage()}>project home page</Link>.
- </span>
- </LemonRow>
+ {homepage?.id === `homepage-dashboard-${id}` ? (
+ <LemonRow fullWidth>Your homepage</LemonRow>
+ ) : (
+ <LemonButton
+ onClick={() => {
+ setHomepage(
+ {
+ id: `homepage-dashboard-${id}`,
+ pathname: urls.dashboard(id),
+ search: '',
+ hash: '',
+ title: name || 'Untitled',
+ iconType: 'dashboard',
+ sceneId: Scene.Dashboard,
+ sceneKey: `dashboard-${id}`,
+ sceneParams: emptySceneParams,
+ },
+ 'dashboards list'
+ )
+ posthog.capture('dashboard set as homepage clicked', {
+ source: 'dashboards list',
+ })
+ }}
+ fullWidth
+ data-attr="dashboard-set-as-homepage"
+ loading={homepageSaving}
+ disabled={homepageSaving}
+ >
+ Set as my homepage
+ </LemonButton>
+ )}
<LemonDivider />
diff --git a/frontend/src/scenes/dashboard/duplicateDashboardLogic.ts b/frontend/src/scenes/dashboard/duplicateDashboardLogic.ts
index b08b523207fe..290190d339b3 100644
--- a/frontend/src/scenes/dashboard/duplicateDashboardLogic.ts
+++ b/frontend/src/scenes/dashboard/duplicateDashboardLogic.ts
@@ -3,8 +3,10 @@ import { forms } from 'kea-forms'
import type { DeepPartial, DeepPartialMap, FieldName, ValidationErrorType } from 'kea-forms'
import { router } from 'kea-router'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { urls } from 'scenes/urls'
+import { sidePanelStateLogic } from '~/layout/navigation-3000/sidepanel/sidePanelStateLogic'
import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
@@ -14,14 +16,12 @@ export interface DuplicateDashboardForm {
dashboardId: number | null
dashboardName?: string
duplicateTiles: boolean
- show?: boolean
}
const defaultFormValues: DuplicateDashboardForm = {
dashboardId: null,
duplicateTiles: false,
dashboardName: undefined,
- show: false,
}
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
@@ -36,6 +36,7 @@ export interface duplicateDashboardLogicValues {
duplicateDashboardTouched: boolean
duplicateDashboardTouches: Record<string, boolean>
duplicateDashboardValidationErrors: DeepPartialMap<DuplicateDashboardForm, ValidationErrorType>
+ duplicateRequestId: number | null
isDuplicateDashboardSubmitting: boolean
isDuplicateDashboardValid: boolean
showDuplicateDashboardErrors: boolean
@@ -47,9 +48,6 @@ export interface duplicateDashboardLogicActions {
dashboardId: number
insightIds: number[]
} // insightsModel
- duplicateAndGoToDashboard: () => {
- value: true
- }
hideDuplicateDashboardModal: () => {
value: true
}
@@ -69,6 +67,9 @@ export interface duplicateDashboardLogicActions {
setDuplicateDashboardValues: (values: DeepPartial<DuplicateDashboardForm>) => {
values: DeepPartial<DuplicateDashboardForm>
}
+ setDuplicateRequestId: (id: number | null) => {
+ id: number | null
+ }
showDuplicateDashboardModal: (
id: number,
name: string
@@ -108,7 +109,7 @@ export const duplicateDashboardLogic = kea<duplicateDashboardLogicType>([
name,
}),
hideDuplicateDashboardModal: true,
- duplicateAndGoToDashboard: true,
+ setDuplicateRequestId: (id: number | null) => ({ id }),
}),
reducers({
duplicateDashboardModalVisible: [
@@ -118,24 +119,26 @@ export const duplicateDashboardLogic = kea<duplicateDashboardLogicType>([
hideDuplicateDashboardModal: () => false,
},
],
+ duplicateRequestId: [null as number | null, { setDuplicateRequestId: (_, { id }) => id }],
}),
- forms(() => ({
+ forms(({ actions, values }) => ({
duplicateDashboard: {
defaults: defaultFormValues,
errors: () => ({}),
- submit: async ({ dashboardId, dashboardName, show, duplicateTiles }) => {
- if (dashboardId) {
+ submit: async ({ dashboardId, dashboardName, duplicateTiles }) => {
+ if (dashboardId && values.duplicateRequestId === null) {
+ actions.setDuplicateRequestId(dashboardId)
dashboardsModel.actions.duplicateDashboard({
id: dashboardId,
name: dashboardName,
- show,
+ show: false,
duplicateTiles,
})
}
},
},
})),
- listeners(({ actions }) => ({
+ listeners(({ actions, values }) => ({
hideDuplicateDashboardModal: () => {
actions.resetDuplicateDashboard()
},
@@ -144,8 +147,12 @@ export const duplicateDashboardLogic = kea<duplicateDashboardLogicType>([
payload,
}: {
dashboard: DashboardType
- payload?: Pick<DuplicateDashboardForm, 'duplicateTiles' | 'show'>
+ payload?: { id: number; duplicateTiles: boolean }
}) => {
+ if (values.duplicateRequestId === null || payload?.id !== values.duplicateRequestId) {
+ return
+ }
+ actions.setDuplicateRequestId(null)
actions.hideDuplicateDashboardModal()
if (!payload?.duplicateTiles) {
@@ -159,17 +166,18 @@ export const duplicateDashboardLogic = kea<duplicateDashboardLogicType>([
})
}
- if (payload?.show) {
- router.actions.push(urls.dashboard(dashboard.id))
- } else {
- if (router.values.currentLocation.pathname !== urls.dashboards()) {
- router.actions.push(urls.dashboards())
- }
+ const sidePanel = sidePanelStateLogic.findMounted()
+ if (sidePanel?.values.modalMode) {
+ sidePanel.actions.closeSidePanel()
}
+
+ router.actions.push(urls.dashboard(dashboard.id))
},
- duplicateAndGoToDashboard: () => {
- actions.setDuplicateDashboardValue('show', true)
- actions.submitDuplicateDashboard()
+ [dashboardsModel.actionTypes.duplicateDashboardFailure]: () => {
+ if (values.duplicateRequestId !== null) {
+ actions.setDuplicateRequestId(null)
+ lemonToast.error('Could not duplicate dashboard. Please try again.')
+ }
},
showDuplicateDashboardModal: ({ id, name }) => {
actions.setDuplicateDashboardValues({ dashboardId: id, dashboardName: name })
diff --git a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts
index dfb0369e6441..03af7ef62783 100644
--- a/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts
+++ b/frontend/src/scenes/project-homepage/ai-first/aiFirstHomepageLogic.ts
@@ -163,7 +163,11 @@ export interface aiFirstHomepageLogicActions {
startNewConversation: () => {
value: true
} // maxLogic
- setHomepage: (tab: SceneTab | null) => {
+ setHomepage: (
+ tab: SceneTab | null,
+ homepageSource?: 'dashboards list' | undefined
+ ) => {
+ homepageSource: 'dashboards list' | undefined
tab: SceneTab | null
} // sceneLogic
setChatDraftForTab: (
diff --git a/frontend/src/scenes/sceneLogic.test.tsx b/frontend/src/scenes/sceneLogic.test.tsx
index 13f8c688af16..ecf3e8199ea5 100644
--- a/frontend/src/scenes/sceneLogic.test.tsx
+++ b/frontend/src/scenes/sceneLogic.test.tsx
@@ -3,14 +3,18 @@ import { MOCK_USER_UUID } from 'lib/api.mock'
import { kea, path } from 'kea'
import { router } from 'kea-router'
import { expectLogic, partial, testUtilsContext, truth } from 'kea-test-utils'
+import posthog from 'posthog-js'
import api from 'lib/api'
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { removeProjectIdIfPresent } from 'lib/utils/kea-router'
import { Scene } from 'scenes/sceneTypes'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import * as exporterViewLogic from '~/exporter/exporterViewLogic'
+import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
import { AccessControlLevel, AccessControlResourceType, type AppContext } from '~/types'
@@ -307,6 +311,81 @@ describe('sceneLogic', () => {
sceneParams: { params: {}, searchParams: {}, hashParams: {} },
}
+ it('saves a dashboard homepage and confirms the change', async () => {
+ const sharedView = jest.spyOn(exporterViewLogic, 'isSharedView').mockReturnValue(false)
+ const successToast = jest.spyOn(lemonToast, 'success').mockReturnValue('toast-id')
+ const capture = jest.spyOn(posthog, 'capture')
+ useMocks({ patch: { '/api/user_home_settings/@me/': [200, {}] } })
+
+ await expectLogic(logic, () =>
+ logic.actions.setHomepage(dashboardHomepage, 'dashboards list')
+ ).toFinishAllListeners()
+
+ expect(logic.values.homepage?.id).toBe(dashboardHomepage.id)
+ expect(successToast).toHaveBeenCalledWith('Homepage updated')
+ expect(capture).toHaveBeenCalledWith('dashboard set as homepage', { source: 'dashboards list' })
+ capture.mockRestore()
+ successToast.mockRestore()
+ sharedView.mockRestore()
+ })
+
+ it('keeps the previous homepage if saving from the dashboard list fails', async () => {
+ const sharedView = jest.spyOn(exporterViewLogic, 'isSharedView').mockReturnValue(false)
+ const errorToast = jest.spyOn(lemonToast, 'error').mockReturnValue('toast-id')
+ const errorLog = jest.spyOn(console, 'error').mockImplementation()
+ useMocks({ patch: { '/api/user_home_settings/@me/': [500, {}] } })
+ const previousHomepage = logic.values.homepage
+
+ await expectLogic(logic, () =>
+ logic.actions.setHomepage(dashboardHomepage, 'dashboards list')
+ ).toFinishAllListeners()
+
+ expect(logic.values.homepage).toEqual(previousHomepage)
+ expect(logic.values.homepageSaving).toBe(false)
+ expect(errorToast).toHaveBeenCalledWith('Could not save your homepage. Please try again.')
+ errorLog.mockRestore()
+ errorToast.mockRestore()
+ sharedView.mockRestore()
+ })
+
+ it('keeps a newer homepage when a dashboard-list save is in flight', async () => {
+ const sharedView = jest.spyOn(exporterViewLogic, 'isSharedView').mockReturnValue(false)
+ const successToast = jest.spyOn(lemonToast, 'success').mockReturnValue('toast-id')
+ let finishSave!: () => void
+ let startSave!: () => void
+ const saveResponse = new Promise<void>((resolve) => (finishSave = resolve))
+ const saveStarted = new Promise<void>((resolve) => (startSave = resolve))
+ const savedHomepageIds: string[] = []
+ useMocks({
+ patch: {
+ '/api/user_home_settings/@me/': async ({ request }) => {
+ const body = (await request.json()) as { homepage: { id: string } }
+ savedHomepageIds.push(body.homepage.id)
+ if (savedHomepageIds.length === 1) {
+ startSave()
+ await saveResponse
+ }
+ return [200, {}] as const
+ },
+ },
+ })
+
+ logic.actions.setHomepage(dashboardHomepage, 'dashboards list')
+ await saveStarted
+ const latestHomepage = { ...dashboardHomepage, id: 'homepage-dashboard-43', pathname: urls.dashboard(43) }
+ logic.actions.setHomepage(latestHomepage)
+ expect(logic.values.homepage?.id).toBe(latestHomepage.id)
+
+ finishSave()
+ await expectLogic(logic).toFinishAllListeners()
+ expect(savedHomepageIds).toEqual([dashboardHomepage.id, latestHomepage.id])
+ expect(logic.values.homepage?.id).toBe(latestHomepage.id)
+ expect(logic.values.homepageSaving).toBe(false)
+ expect(successToast).not.toHaveBeenCalled()
+ successToast.mockRestore()
+ sharedView.mockRestore()
+ })
+
it('redirects /home to the configured dashboard homepage', async () => {
logic.actions.setHomepage(dashboardHomepage)
router.actions.push(urls.projectHomepage())
diff --git a/frontend/src/scenes/sceneLogic.tsx b/frontend/src/scenes/sceneLogic.tsx
index e068725df3fb..5309a1709009 100644
--- a/frontend/src/scenes/sceneLogic.tsx
+++ b/frontend/src/scenes/sceneLogic.tsx
@@ -245,6 +245,7 @@ export interface sceneLogicValues {
exportedScenes: Record<string, SceneExport<SceneProps>>
hashParams: Record<string, any>
homepage: SceneTab | null
+ homepageSaving: boolean
lastReloadAt: number | null
lastSetScenePayload: Record<string, any>
loadingScene: string | null
@@ -264,6 +265,9 @@ export interface sceneLogicActions {
hideInviteModal: () => {
value: true
} // inviteLogic
+ homepageSaved: (tab: SceneTab | null) => {
+ tab: SceneTab | null
+ }
loadScene: (
sceneId: string,
sceneKey: string | undefined,
@@ -303,9 +307,16 @@ export interface sceneLogicActions {
sceneId: string
sceneKey: string | undefined
}
- setHomepage: (tab: SceneTab | null) => {
+ setHomepage: (
+ tab: SceneTab | null,
+ homepageSource?: 'dashboards list'
+ ) => {
+ homepageSource: 'dashboards list' | undefined
tab: SceneTab | null
}
+ setHomepageSaving: (saving: boolean) => {
+ saving: boolean
+ }
setScene: (
sceneId: string,
sceneKey: string | undefined,
@@ -385,6 +396,8 @@ export const sceneLogic = kea<sceneLogicType>([
afterMount(({ cache }) => {
cache.mountedSceneLogic = null as MountedSceneLogic | null
cache.lastTrackedScene = null as { sceneId?: string; sceneKey?: string } | null
+ cache.homepageSave = Promise.resolve()
+ cache.homepageRequest = 0
}),
actions({
/* 1. Prepares to open the scene, as the listener may override and do something
@@ -429,7 +442,9 @@ export const sceneLogic = kea<sceneLogicType>([
}),
reloadBrowserDueToImportError: true,
- setHomepage: (tab: SceneTab | null) => ({ tab }),
+ setHomepage: (tab: SceneTab | null, homepageSource?: 'dashboards list') => ({ tab, homepageSource }),
+ homepageSaved: (tab: SceneTab | null) => ({ tab }),
+ setHomepageSaving: (saving: boolean) => ({ saving }),
resetUnavailableHomepage: (pathname: string) => ({ pathname }),
}),
reducers({
@@ -494,9 +509,16 @@ export const sceneLogic = kea<sceneLogicType>([
homepage: [
getBootstrappedHomepage(),
{
- setHomepage: (_, { tab }) => (tab ? tabToPersistableSnapshot(tab) : null),
+ setHomepage: (state, { tab, homepageSource }) => {
+ if (homepageSource) {
+ return state
+ }
+ return tab ? tabToPersistableSnapshot(tab) : null
+ },
+ homepageSaved: (_, { tab }) => (tab ? tabToPersistableSnapshot(tab) : null),
},
],
+ homepageSaving: [false, { setHomepageSaving: (_, { saving }) => saving }],
})),
selectors({
sceneConfig: [
@@ -701,16 +723,39 @@ export const sceneLogic = kea<sceneLogicType>([
)
}
},
- setHomepage: ({ tab }) => {
- if (isSharedView()) {
+ setHomepage: async ({ tab, homepageSource }) => {
+ if (isSharedView() || (homepageSource && values.homepageSaving)) {
return
}
- // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use userHomeSettingsPartialUpdate() from 'products/platform_features/frontend/generated/api' instead.
- api.update('api/user_home_settings/@me/', {
- homepage: tab ? tabToPersistableSnapshot(tab) : null,
- }).catch((error) => {
- console.error('Failed to persist homepage', error)
- })
+ if (homepageSource) {
+ actions.setHomepageSaving(true)
+ }
+ const requestId = ++cache.homepageRequest
+ const previousSave = cache.homepageSave
+ cache.homepageSave = (async () => {
+ await previousSave
+ try {
+ // nosemgrep: prefer-codegen-api -- Legacy raw API call with a hand-written URL and an unchecked response type. Use userHomeSettingsPartialUpdate() from 'products/platform_features/frontend/generated/api' instead.
+ await api.update('api/user_home_settings/@me/', {
+ homepage: tab ? tabToPersistableSnapshot(tab) : null,
+ })
+ if (homepageSource && requestId === cache.homepageRequest) {
+ actions.homepageSaved(tab)
+ lemonToast.success('Homepage updated')
+ posthog.capture('dashboard set as homepage', { source: homepageSource })
+ }
+ } catch (error) {
+ console.error('Failed to persist homepage', error)
+ if (homepageSource && requestId === cache.homepageRequest) {
+ lemonToast.error('Could not save your homepage. Please try again.')
+ }
+ } finally {
+ if (homepageSource) {
+ actions.setHomepageSaving(false)
+ }
+ }
+ })()
+ await cache.homepageSave
},
setScene: ({ sceneKey, sceneId, exportedScene, params, scrollToTop }, _, __, previousState) => {
const {
diff --git a/playwright/e2e/product-analytics/dashboards.spec.ts b/playwright/e2e/product-analytics/dashboards.spec.ts
index 35ea51eccab5..89d6b53698ba 100644
--- a/playwright/e2e/product-analytics/dashboards.spec.ts
+++ b/playwright/e2e/product-analytics/dashboards.spec.ts
@@ -399,6 +399,7 @@ test.describe('Dashboard duplication', () => {
await test.step('set date filter', async () => {
sourceDashboardUrl = page.url()
await dashboard.setDateFilter('Last 30 days')
+ await dashboard.saveFilters()
})
await test.step('duplicate the dashboard', async () => {
diff --git a/playwright/page-models/dashboardPage.ts b/playwright/page-models/dashboardPage.ts
index fc5b353f6341..5790d9bca510 100644
--- a/playwright/page-models/dashboardPage.ts
+++ b/playwright/page-models/dashboardPage.ts
@@ -140,14 +140,17 @@ export class DashboardPage {
}
async duplicate(): Promise<void> {
+ const sourceDashboardId = new URL(this.page.url()).pathname.match(/\/dashboard\/(\d+)/)?.[1]
await this.openInfoPanel()
await this.page.getByTestId('dashboard-duplicate-button').click()
const modal = this.page.locator('.LemonModal').filter({ hasText: 'Duplicate dashboard' })
await expect(modal).toBeVisible()
- await this.page.getByTestId('dashboard-submit-and-go').click()
+ await this.page.getByTestId('duplicate-dashboard-submit').click()
- await expect(this.page).toHaveURL(/\/dashboard\//)
+ await expect
+ .poll(() => new URL(this.page.url()).pathname.match(/\/dashboard\/(\d+)/)?.[1])
+ .not.toBe(sourceDashboardId)
}
async deleteDashboard(): Promise<void> {
@@ -166,6 +169,16 @@ export class DashboardPage {
await expect(this.dateFilter).toContainText(option)
}
+ async saveFilters(): Promise<void> {
+ const saveButton = this.page.getByTestId('dashboard-save-filters')
+ if (!(await saveButton.isVisible())) {
+ await this.page.getByTestId('dashboard-filters-unsaved').getByRole('button', { name: 'Actions' }).click()
+ }
+
+ await saveButton.click()
+ await expect(this.page.getByTestId('dashboard-filters-unsaved')).toBeHidden()
+ }
+
async setVariable(name: string, value: string | number): Promise<void> {
const field = this.page.locator('.Field').filter({ hasText: name })
await field.locator('.DataVizVariable_Button').click()
diff --git a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx
index 55852e40909b..41b4c4feca33 100644
--- a/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx
+++ b/products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu.tsx
@@ -64,7 +64,8 @@ const GRID_COMPACTION_OPTIONS: {
]
export function DashboardCustomizeMenu(): JSX.Element | null {
- const { dashboard, canEditDashboard } = useValues(dashboardLogic)
+ const { dashboard, canEditDashboard, currentLayoutSize } = useValues(dashboardLogic)
+ const layoutAvailable = currentLayoutSize !== 'xs'
const { changeDashboardGridCompaction, setDashboardTileSpacing, saveDashboardTileSpacing } =
useActions(dashboardLogic)
if (!dashboard || !canEditDashboard) {
@@ -89,29 +90,33 @@ export function DashboardCustomizeMenu(): JSX.Element | null {
}
return (
- <div className="space-y-2 p-2">
- <div className="flex flex-wrap items-center gap-x-3 gap-y-1">
+ <div className={layoutAvailable ? 'space-y-2 p-2' : 'w-[min(20rem,calc(100vw-2rem))] space-y-2 p-2'}>
+ <div className={layoutAvailable ? 'flex flex-wrap items-center gap-x-3 gap-y-1' : 'flex flex-col gap-2'}>
<span className="text-xs text-muted whitespace-nowrap">Tile density</span>
<LemonRadio<DashboardTileSpacing>
value={tileSpacing}
onChange={setTileSpacing}
options={TILE_SPACING_OPTIONS}
orientation="horizontal"
- className="flex-1 flex-wrap gap-x-3 gap-y-1"
+ className={layoutAvailable ? 'flex-1 flex-wrap gap-x-3 gap-y-1' : 'flex-wrap gap-x-3 gap-y-1'}
aria-label="Tile density"
/>
</div>
- <div className="flex gap-x-3 border-t pt-2">
- <span className="pt-3 text-xs text-muted whitespace-nowrap">When you move a tile</span>
- <LemonRadio<DashboardGridCompactionType>
- value={layoutCompaction}
- onChange={setGridCompaction}
- options={GRID_COMPACTION_OPTIONS}
- radioPosition="top"
- className="flex-1"
- aria-label="How moving a tile rearranges other tiles"
- />
- </div>
+ {layoutAvailable ? (
+ <div className="flex gap-x-3 border-t pt-2">
+ <span className="pt-3 text-xs text-muted whitespace-nowrap">When you move a tile</span>
+ <LemonRadio<DashboardGridCompactionType>
+ value={layoutCompaction}
+ onChange={setGridCompaction}
+ options={GRID_COMPACTION_OPTIONS}
+ radioPosition="top"
+ className="flex-1"
+ aria-label="How moving a tile rearranges other tiles"
+ />
+ </div>
+ ) : (
+ <p className="border-t pt-2 text-xs text-muted">Use a larger screen to move or resize tiles.</p>
+ )}
</div>
)
}
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx b/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx
index 2654435d8841..176a93ff6de5 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/SubscriptionOverviewComponents.tsx
@@ -6,6 +6,7 @@ import { LemonTag, Tooltip } from '@posthog/lemon-ui'
import { TZLabel } from 'lib/components/TZLabel'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonCard } from 'lib/lemon-ui/LemonCard'
+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
import { ProfilePicture } from 'lib/lemon-ui/ProfilePicture'
import { Spinner } from 'lib/lemon-ui/Spinner'
import { capitalizeFirstLetter, pluralize } from 'lib/utils/strings'
@@ -109,7 +110,7 @@ export function SubscriptionEmptyState({
export function AIPromptReportsLink(): JSX.Element {
return (
<LemonCard hoverEffect={false} className="p-3 bg-fill-secondary border-transparent">
- <div className="flex gap-3 items-center">
+ <div className="flex flex-col gap-3 @min-[30rem]/subscription-modal:flex-row @min-[30rem]/subscription-modal:items-center">
<div className="flex items-center justify-center rounded bg-surface-primary size-9 text-lg shrink-0">
<IconAI />
</div>
@@ -120,10 +121,10 @@ export function AIPromptReportsLink(): JSX.Element {
</div>
</div>
<LemonButton
- type="tertiary"
- size="xsmall"
+ type="secondary"
+ size="small"
to={`${urls.subscriptions()}?tab=ai_prompt`}
- className="shrink-0"
+ className="self-start shrink-0 @min-[30rem]/subscription-modal:self-center"
>
Explore AI prompt reports
</LemonButton>
@@ -151,116 +152,111 @@ export function SubscriptionListItem({
const destination = subscriptionListDestination(subscription)
return (
- <LemonButton
- type="secondary"
- onClick={onClick}
- data-attr="subscription-list-item"
- fullWidth
- sideAction={{
- icon: sideActionBusy ? <Spinner /> : <IconEllipsis />,
- disabled: sideActionBusy,
- dropdown: {
- overlay: (
- <>
- {onToggleEnabled && (
- <LemonButton
- icon={enabled ? <IconPause /> : <IconPlay />}
- onClick={() => onToggleEnabled(!enabled)}
- data-attr="subscription-list-item-toggle-enabled"
- fullWidth
- disabled={isToggling}
- >
- {enabled ? 'Disable subscription' : 'Enable subscription'}
- </LemonButton>
- )}
- {onDeliver && enabled && (
- <LemonButton
- icon={<IconPlay />}
- onClick={onDeliver}
- data-attr="subscription-list-item-manual-deliver"
- fullWidth
- disabled={isDelivering}
- >
- Test delivery
- </LemonButton>
- )}
- {onDelete && (
- <LemonButton
- icon={<IconTrash />}
- onClick={onDelete}
- data-attr="subscription-list-item-delete"
- status="danger"
- fullWidth
- >
- Delete subscription
- </LemonButton>
- )}
- </>
- ),
- },
- }}
- >
- <div className="flex-auto p-2 min-w-0">
- <div className="flex flex-col gap-1 min-w-0">
- <div className="flex items-center justify-between gap-4">
- <div className="flex items-center gap-2 min-w-0">
- <div className={`font-medium truncate ${enabled ? 'text-link' : 'text-muted'}`}>
- {subscription.title}
+ <div className="relative">
+ <LemonButton type="secondary" onClick={onClick} data-attr="subscription-list-item" fullWidth>
+ <div className="flex-auto p-2 min-w-0">
+ <div className="flex flex-col gap-1 min-w-0">
+ <div className="flex min-w-0 flex-col items-start gap-1 pr-8 @min-[30rem]/subscription-modal:flex-row @min-[30rem]/subscription-modal:items-center @min-[30rem]/subscription-modal:justify-between @min-[30rem]/subscription-modal:gap-4">
+ <div className="flex items-center gap-2 min-w-0">
+ <div className={`font-medium truncate ${enabled ? 'text-link' : 'text-muted'}`}>
+ {subscription.title}
+ </div>
+ {!enabled && (
+ <LemonTag type="danger" size="small">
+ Disabled
+ </LemonTag>
+ )}
</div>
- {!enabled && (
- <LemonTag type="danger" size="small">
- Disabled
- </LemonTag>
- )}
- </div>
- <div
- className="flex items-center gap-1 text-xs text-secondary shrink-0"
- title={destination.title}
- >
- {destination.icon}
- <span className="max-w-40 truncate">{destination.label}</span>
- </div>
- </div>
- {aiPrompt ? (
- <Tooltip title={aiPromptTruncated ? aiPrompt : undefined}>
- <div className="text-sm text-muted italic">{`"${aiPromptPreview}"`}</div>
- </Tooltip>
- ) : null}
- {subscription.resource_type === SubscriptionResourceTypes.Insight && subscription.resource_name ? (
- <div className="flex items-center gap-1 text-xs text-secondary">
- <IconGraph />
- <span>
- Insight: <span className="font-medium">{subscription.resource_name}</span>
- </span>
- </div>
- ) : null}
- <div className="text-xs text-secondary">
- {capitalizeFirstLetter(subscription.summary)}
- {selectedInsightsCount
- ? ` · ${pluralize(selectedInsightsCount, 'insight', 'insights', true)}`
- : null}
- </div>
- <div className="flex items-center justify-between gap-3 min-h-5 whitespace-nowrap">
- {enabled && subscription.next_delivery_date && (
- <div className="text-xs text-secondary shrink-0">
- Next delivery:{' '}
- <TZLabel
- time={subscription.next_delivery_date}
- formatDate="ddd, MMM D"
- formatTime="h:mm A"
- timestampStyle="absolute"
- />
+ <div
+ className="flex min-w-0 max-w-full items-center gap-1 text-xs text-secondary @min-[30rem]/subscription-modal:shrink-0"
+ title={destination.title}
+ >
+ {destination.icon}
+ <span className="max-w-40 truncate">{destination.label}</span>
</div>
- )}
- {subscription.created_by ? (
- <div className="flex items-center gap-1 text-xs text-tertiary ml-auto opacity-60 min-w-0 overflow-hidden">
- <span>Created by</span>
- <ProfilePicture user={subscription.created_by} size="xs" showName />
+ </div>
+ {aiPrompt ? (
+ <Tooltip title={aiPromptTruncated ? aiPrompt : undefined}>
+ <div className="text-sm text-muted italic">{`"${aiPromptPreview}"`}</div>
+ </Tooltip>
+ ) : null}
+ {subscription.resource_type === SubscriptionResourceTypes.Insight &&
+ subscription.resource_name ? (
+ <div className="flex items-center gap-1 text-xs text-secondary">
+ <IconGraph />
+ <span>
+ Insight: <span className="font-medium">{subscription.resource_name}</span>
+ </span>
</div>
) : null}
+ <div className="text-xs text-secondary">
+ {capitalizeFirstLetter(subscription.summary)}
+ {selectedInsightsCount
+ ? ` · ${pluralize(selectedInsightsCount, 'insight', 'insights', true)}`
+ : null}
+ </div>
+ <div className="flex min-h-5 flex-col items-start gap-1 @min-[30rem]/subscription-modal:flex-row @min-[30rem]/subscription-modal:items-center @min-[30rem]/subscription-modal:justify-between @min-[30rem]/subscription-modal:gap-3">
+ {enabled && subscription.next_delivery_date && (
+ <div className="text-xs text-secondary shrink-0">
+ Next delivery:{' '}
+ <TZLabel
+ time={subscription.next_delivery_date}
+ formatDate="ddd, MMM D"
+ formatTime="h:mm A"
+ timestampStyle="absolute"
+ />
+ </div>
+ )}
+ {subscription.created_by ? (
+ <div className="flex min-w-0 items-center gap-1 overflow-hidden text-xs text-tertiary opacity-60 @min-[30rem]/subscription-modal:ml-auto">
+ <span>Created by</span>
+ <ProfilePicture user={subscription.created_by} size="xs" showName />
+ </div>
+ ) : null}
+ </div>
</div>
</div>
+ </LemonButton>
+ <div className="absolute right-2 top-2 z-10">
+ <LemonMenu
+ items={[
+ onToggleEnabled
+ ? {
+ label: enabled ? 'Disable subscription' : 'Enable subscription',
+ icon: enabled ? <IconPause fontSize="12" /> : <IconPlay fontSize="12" />,
+ onClick: () => onToggleEnabled(!enabled),
+ 'data-attr': 'subscription-list-item-toggle-enabled',
+ }
+ : false,
+ onDeliver && enabled
+ ? {
+ label: 'Test delivery',
+ icon: <IconPlay fontSize="12" />,
+ onClick: onDeliver,
+ 'data-attr': 'subscription-list-item-manual-deliver',
+ }
+ : false,
+ onDelete
+ ? {
+ label: 'Delete subscription',
+ icon: <IconTrash fontSize="12" />,
+ onClick: onDelete,
+ status: 'danger' as const,
+ 'data-attr': 'subscription-list-item-delete',
+ }
+ : false,
+ ]}
+ >
+ <LemonButton
+ type="tertiary"
+ size="xsmall"
+ icon={sideActionBusy ? <Spinner /> : <IconEllipsis />}
+ disabled={sideActionBusy}
+ aria-label="Subscription actions"
+ data-attr="subscription-list-item-actions"
+ />
+ </LemonMenu>
</div>
- </LemonButton>
+ </div>
)
}
diff --git a/products/subscriptions/frontend/components/Subscriptions/views/TabbedManageSubscriptions.tsx b/products/subscriptions/frontend/components/Subscriptions/views/TabbedManageSubscriptions.tsx
index dc0e74e3683b..7c15b55ee1da 100644
--- a/products/subscriptions/frontend/components/Subscriptions/views/TabbedManageSubscriptions.tsx
+++ b/products/subscriptions/frontend/components/Subscriptions/views/TabbedManageSubscriptions.tsx
@@ -213,13 +213,20 @@ export function TabbedManageSubscriptions({
</p>
</div>
</LemonModal.Header>
- <LemonModal.Content>
+ <LemonModal.Content className="@container/subscription-modal">
+ {activeTab === 'resource' && subscriptions.length > 0 && (
+ <div className="mb-3 flex justify-end @min-[34rem]/subscription-modal:hidden">
+ <LemonButton type="primary" onClick={() => onSelect('new')} data-attr="add-subscription">
+ Create subscription
+ </LemonButton>
+ </div>
+ )}
<LemonTabs
activeKey={activeTab}
onChange={onChangeTab}
tabs={tabs}
data-attr="manage-subscriptions-tabs"
- rightSlotClassName="bg-transparent"
+ rightSlotClassName="hidden bg-transparent @min-[34rem]/subscription-modal:flex"
rightSlot={
activeTab === 'resource' && subscriptions.length > 0 ? (
<LemonButton type="primary" onClick={() => onSelect('new')} data-attr="add-subscription">