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): add tile groups from the dashboard add menu (#128394)

Matt Pua87b63ab61520
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index ed364fd4ed3d..c3a270d92d0d 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -7279,9 +7279,9 @@ snapshots:
products-dashboards-tiles-tile-group--styles--light:
hash: v1.k794b7964.1ea4c4743d7380fe85985e50795f9a6dd4dc1909f37a926800aa316aebb26a31.-z1Igyir2gbb9kVTuxP9EAoUX1Dg5J1fKGFJINxzh7g
products-dashboards-tiles-tile-group-tabs--group-tab-menu-open--dark:
- hash: v1.k794b7964.1b61c52567f1b5a1c8ab1327f463f5e0c26e786fb8eaab08b4b5fa02669a5be2.JRSjR2Xd9-SyNQ_zbaqBj9pARoWVep8y3Ny-pjlUuUQ
+ hash: v1.k794b7964.74a3396379d3d124eb2eb2cc72a469d8462ce171165520f4eac53445e66048d1.I7daZuPAmrvBSy07AIboVszhemm6aFqeNXjhv0aYa_Q
products-dashboards-tiles-tile-group-tabs--group-tab-menu-open--light:
- hash: v1.k794b7964.320c1708f492f3663d25503a1d652ad244c25ac3e87ea4f9bd9a3914136addf4.TNlLgNvpjwPY5H5_XPQmXkVo3cii6zySskqUci-BhPk
+ hash: v1.k794b7964.e2d706d982b2d73de2eaf3825b5d45107bb20144e87565a6f1001edb4d8828ee.jKnJZmiOw1m_zZWbKz9z-kxyqS2E7NHfriwumEodCjs
products-dashboards-tiles-tile-group-tabs--overview-tab-menu-open--dark:
hash: v1.k794b7964.5bb3321201cfd932ad8b4678f85ccb1c14d998ded1e2be520aed4fb5f78b4228.Jecda0GeagvkWplgFZiTQQr70fOzZhc3BAWFL3lRJek
products-dashboards-tiles-tile-group-tabs--overview-tab-menu-open--light:
diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx
index 7f2a7f9c232e..c9cfc262b878 100644
--- a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx
+++ b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx
@@ -9,21 +9,23 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
-import { DashboardPlacement, DashboardTile, DashboardTileIdOrNew, DashboardType } from '~/types'
+import { DashboardPlacement, DashboardTile, DashboardTileIdOrNew, DashboardType, NewDashboardTile } from '~/types'
export function ButtonTileCardModal({
isOpen,
onClose,
dashboard,
buttonTileId,
+ onCreateTile,
}: {
isOpen: boolean
onClose: () => void
dashboard: DashboardType
buttonTileId: DashboardTileIdOrNew
+ onCreateTile?: (tile: NewDashboardTile) => void
}): JSX.Element {
const isNewTile = buttonTileId === null
- const modalLogic = buttonTileCardModalLogic({ dashboard, buttonTileId, onClose })
+ const modalLogic = buttonTileCardModalLogic({ dashboard, buttonTileId, onClose, onCreateTile })
const { buttonTile, isButtonTileSubmitting, buttonTileValidationErrors } = useValues(modalLogic)
const { submitButtonTile, resetButtonTile } = useActions(modalLogic)
diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts b/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts
index d75c5698653d..a47cd1dc3464 100644
--- a/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts
+++ b/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts
@@ -6,7 +6,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { dashboardsModel } from '~/models/dashboardsModel'
-import { DashboardTileIdOrNew, DashboardType } from '~/types'
+import { DashboardTileIdOrNew, DashboardType, NewDashboardTile } from '~/types'
export interface ButtonTileForm {
url: string
@@ -20,6 +20,8 @@ export interface ButtonTileCardModalProps {
dashboard: DashboardType
buttonTileId: DashboardTileIdOrNew
onClose: () => void
+ /** Creates the new tile. Without it, the tile is created on the dashboard as is. */
+ onCreateTile?: (tile: NewDashboardTile) => void
}
const getExistingButtonTile = (dashboard: DashboardType, buttonTileId: number): ButtonTileForm => {
@@ -176,10 +178,12 @@ export const buttonTileCardModalLogic = kea<buttonTileCardModalLogicType>([
}))
if (props.buttonTileId === null) {
- actions.updateDashboard({
- id: props.dashboard.id,
- tiles: [{ button_tile: buttonTileFields, transparent_background }],
- })
+ const tile = { button_tile: buttonTileFields, transparent_background }
+ if (props.onCreateTile) {
+ props.onCreateTile(tile)
+ } else {
+ actions.updateDashboard({ id: props.dashboard.id, tiles: [tile] })
+ }
} else {
const updatedTiles = tiles.map((tile) => {
if (tile.id === props.buttonTileId && tile.button_tile) {
diff --git a/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx b/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
index 8012637120b0..eb6be7cea2dd 100644
--- a/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
+++ b/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
@@ -14,21 +14,23 @@ import { DialogClose, DialogPrimitive, DialogPrimitiveTitle } from 'lib/ui/Dialo
import { cn } from 'lib/utils/css-classes'
import { aiConsentLogic } from '~/layout/ai/aiConsentLogic'
-import { DashboardTileIdOrNew, DashboardType } from '~/types'
+import { DashboardTileIdOrNew, DashboardType, NewDashboardTile } from '~/types'
export function TextCardModal({
isOpen,
onClose,
dashboard,
textTileId,
+ onCreateTile,
}: {
isOpen: boolean
onClose: () => void
dashboard: DashboardType
textTileId: DashboardTileIdOrNew
+ onCreateTile?: (tile: NewDashboardTile) => void
}): JSX.Element {
const isNewTile = textTileId === null
- const modalLogicProps: TextCardModalProps = { dashboard, textTileId, onClose, tileType: 'text' }
+ const modalLogicProps: TextCardModalProps = { dashboard, textTileId, onClose, tileType: 'text', onCreateTile }
const modalLogic = textCardModalLogic(modalLogicProps)
// Form `body` + validation drive updates while typing; splitting useValues does not reduce rerenders.
const { isTextTileSubmitting, textTileValidationErrors, textTileChanged } = useValues(modalLogic)
diff --git a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts
index 53d9caf89c20..df0db985a766 100644
--- a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts
+++ b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts
@@ -6,7 +6,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { dashboardsModel } from '~/models/dashboardsModel'
-import { DashboardTile, DashboardTileIdOrNew, DashboardType } from '~/types'
+import { DashboardTile, DashboardTileIdOrNew, DashboardType, NewDashboardTile } from '~/types'
import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'
@@ -23,6 +23,8 @@ export interface TextCardModalProps {
textTileId: DashboardTileIdOrNew
onClose: () => void
tileType: TextCardTileType
+ /** Creates the new tile. Without it, the tile is created on the dashboard as is. */
+ onCreateTile?: (tile: NewDashboardTile) => void
}
const MAX_TEXT_CARD_BODY_LENGTH = 4000
@@ -183,15 +185,15 @@ export const textCardModalLogic = kea<textCardModalLogicType>([
},
submit: (formValues) => {
if (props.textTileId === null) {
- actions.updateDashboard({
- id: props.dashboard.id,
- tiles: [
- {
- text: { body: formValues.body, agent_context: formValues.agent_context },
- transparent_background: formValues.transparent_background,
- },
- ],
- })
+ const tile = {
+ text: { body: formValues.body, agent_context: formValues.agent_context },
+ transparent_background: formValues.transparent_background,
+ }
+ if (props.onCreateTile) {
+ props.onCreateTile(tile)
+ } else {
+ actions.updateDashboard({ id: props.dashboard.id, tiles: [tile] })
+ }
} else {
const updatedTiles = (props.dashboard.tiles || []).reduce((acc, tile) => {
if (tile.id === props.textTileId && tile.text) {
diff --git a/frontend/src/lib/lemon-ui/LemonTabs/LemonTabs.tsx b/frontend/src/lib/lemon-ui/LemonTabs/LemonTabs.tsx
index 289791bda49e..2eae1bbb98a4 100644
--- a/frontend/src/lib/lemon-ui/LemonTabs/LemonTabs.tsx
+++ b/frontend/src/lib/lemon-ui/LemonTabs/LemonTabs.tsx
@@ -45,6 +45,8 @@ export interface LemonTabsProps<T extends string | number> {
/** Pass in JSX to be sticky to the right of the tabs. */
rightSlot?: React.ReactNode
rightSlotClassName?: string
+ /** Keeps the underline in place when a tab label changes width, as in an in-place rename. */
+ trackTabSizes?: boolean
}
interface LemonTabsCSSProperties extends React.CSSProperties {
@@ -63,13 +65,14 @@ export function LemonTabs<T extends string | number>({
sceneInset = false,
rightSlot,
rightSlotClassName,
+ trackTabSizes = false,
}: LemonTabsProps<T>): JSX.Element {
/** Tabs with falsy entries filtered out. */
const realTabs = tabs.filter(Boolean) as LemonTab<T>[]
const { containerRef, selectionRef, sliderWidth, sliderOffset, transitioning } = useSliderPositioning<
HTMLUListElement,
HTMLLIElement
- >(activeKey, 200, realTabs.map((tab) => tab.key).join('|'))
+ >(activeKey, 200, realTabs.map((tab) => tab.key).join('|'), trackTabSizes)
return (
<div
diff --git a/frontend/src/lib/lemon-ui/hooks.ts b/frontend/src/lib/lemon-ui/hooks.ts
index de3666d5b9f1..234629de24f4 100644
--- a/frontend/src/lib/lemon-ui/hooks.ts
+++ b/frontend/src/lib/lemon-ui/hooks.ts
@@ -10,7 +10,9 @@ export function useSliderPositioning<C extends HTMLElement, S extends HTMLElemen
currentValue: React.Key | null | undefined,
transitionMs: number,
/** Changes when the options change, so the slider follows a selection that moved without changing. */
- layoutKey?: string
+ layoutKey?: string,
+ /** Moves the slider when an option's width changes, as when a tab label is renamed in place. */
+ trackOptionSizes = false
): {
containerRef: React.RefObject<C>
selectionRef: React.RefObject<S>
@@ -37,6 +39,25 @@ export function useSliderPositioning<C extends HTMLElement, S extends HTMLElemen
}
}, [currentValue, containerWidth, layoutKey]) // oxlint-disable-line react-hooks/exhaustive-deps
+ // An option whose label changes width moves the selection without changing the container's width.
+ useLayoutEffect(() => {
+ const container = containerRef.current
+ if (!trackOptionSizes || !container) {
+ return
+ }
+ const observer = new ResizeObserver(() => {
+ const selection = selectionRef.current
+ if (selection) {
+ const next: [number, number] = [selection.offsetWidth, selection.offsetLeft]
+ setSelectionWidthAndOffset((current) =>
+ current[0] === next[0] && current[1] === next[1] ? current : next
+ )
+ }
+ })
+ Array.from(container.children).forEach((option) => observer.observe(option))
+ return () => observer.disconnect()
+ }, [currentValue, layoutKey, trackOptionSizes])
+
return {
containerRef,
selectionRef,
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index e2f0fba8f14b..7182eea5faf7 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1853,11 +1853,13 @@ export const productUrls = {
insightNew: ({
type,
dashboardId,
+ tileGroupKey,
query,
sceneSource,
}: {
type?: InsightType
dashboardId?: DashboardType['id'] | null
+ tileGroupKey?: string | null
query?: Node
sceneSource?: InsightSceneSource
} = {}): string => {
@@ -1872,11 +1874,15 @@ export const productUrls = {
if ((isDataVisualizationNode(query) || isDataTableNode(query)) && isHogQLQuery(query.source)) {
return urls.sqlEditor({ query })
}
- return combineUrl('/insights/new', dashboardId ? { dashboard: dashboardId } : {}, {
- ...(type ? { insight: type } : {}),
- ...(query ? { q: typeof query === 'string' ? query : JSON.stringify(query) } : {}),
- ...(sceneSource ? { sceneSource } : {}),
- }).url
+ return combineUrl(
+ '/insights/new',
+ dashboardId ? { dashboard: dashboardId, ...(tileGroupKey ? { tile_group: tileGroupKey } : {}) } : {},
+ {
+ ...(type ? { insight: type } : {}),
+ ...(query ? { q: typeof query === 'string' ? query : JSON.stringify(query) } : {}),
+ ...(sceneSource ? { sceneSource } : {}),
+ }
+ ).url
},
insightNewHogQL: ({ query, filters }: { query: string; filters?: HogQLFilters }): string =>
urls.insightNew({
diff --git a/frontend/src/scenes/dashboard/DashboardAddTileSubMenu.tsx b/frontend/src/scenes/dashboard/DashboardAddTileSubMenu.tsx
index fee38e8c9ad5..7098d59295b9 100644
--- a/frontend/src/scenes/dashboard/DashboardAddTileSubMenu.tsx
+++ b/frontend/src/scenes/dashboard/DashboardAddTileSubMenu.tsx
@@ -1,13 +1,21 @@
-import { useActions } from 'kea'
+import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
-import { SceneMenuBarItem, SceneMenuBarSubMenu } from '~/layout/scenes/components/SceneMenuBar'
+import { SceneMenuBarItem, SceneMenuBarSeparator, SceneMenuBarSubMenu } from '~/layout/scenes/components/SceneMenuBar'
-import { getDashboardAddTileOptions } from './dashboardAddTileOptions'
+import { getDashboardAddTileOptions, groupDashboardAddTileOptions } from './dashboardAddTileOptions'
import { dashboardLogic } from './dashboardLogic'
export function DashboardAddTileSubMenu(): JSX.Element {
- const { openAddInsightModal, openTextTileModal, openImageTileModal, openButtonTileModal, setAddWidgetModalOpen } =
- useActions(dashboardLogic)
+ const { tileGroupSectionsEnabled } = useValues(dashboardLogic)
+ const {
+ openAddInsightModal,
+ openTextTileModal,
+ openImageTileModal,
+ openButtonTileModal,
+ setAddWidgetModalOpen,
+ addTileGroup,
+ } = useActions(dashboardLogic)
const options = getDashboardAddTileOptions({
onAddInsight: openAddInsightModal,
@@ -15,19 +23,25 @@ export function DashboardAddTileSubMenu(): JSX.Element {
onAddImage: openImageTileModal,
onAddButton: openButtonTileModal,
setAddWidgetModalOpen,
+ onAddGroup: tileGroupSectionsEnabled ? () => addTileGroup() : undefined,
})
return (
<SceneMenuBarSubMenu label="Add">
- {options.map((option) => (
- <SceneMenuBarItem
- key={option.key}
- opensFloatingUi
- onClick={option.onClick}
- data-attr={`dashboard-menubar-add-${option.key}`}
- >
- {option.label}
- </SceneMenuBarItem>
+ {groupDashboardAddTileOptions(options).map(({ section, options: sectionOptions }, index) => (
+ <Fragment key={section}>
+ {index > 0 && <SceneMenuBarSeparator />}
+ {sectionOptions.map((option) => (
+ <SceneMenuBarItem
+ key={option.key}
+ opensFloatingUi
+ onClick={option.onClick}
+ data-attr={`dashboard-menubar-add-${option.key}`}
+ >
+ {option.label}
+ </SceneMenuBarItem>
+ ))}
+ </Fragment>
))}
</SceneMenuBarSubMenu>
)
diff --git a/frontend/src/scenes/dashboard/DashboardEmptyGroupAddButton.tsx b/frontend/src/scenes/dashboard/DashboardEmptyGroupAddButton.tsx
new file mode 100644
index 000000000000..519c524e391d
--- /dev/null
+++ b/frontend/src/scenes/dashboard/DashboardEmptyGroupAddButton.tsx
@@ -0,0 +1,42 @@
+import { useActions } from 'kea'
+
+import { IconPlusSmall } from '@posthog/icons'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
+
+import { getAddTileMenuItems } from './DashboardHeaderActions'
+import { dashboardLogic } from './dashboardLogic'
+
+export function DashboardEmptyGroupAddButton({ groupKey }: { groupKey: string }): JSX.Element {
+ const {
+ setAddWidgetModalOpen,
+ openAddInsightModal,
+ openTextTileModal,
+ openImageTileModal,
+ openButtonTileModal,
+ setAddTargetTileGroupKey,
+ } = useActions(dashboardLogic)
+
+ return (
+ <LemonMenu
+ items={getAddTileMenuItems({
+ onBeforeSelect: () => setAddTargetTileGroupKey(groupKey),
+ onAddInsight: openAddInsightModal,
+ onAddText: openTextTileModal,
+ onAddImage: openImageTileModal,
+ onAddButton: openButtonTileModal,
+ setAddWidgetModalOpen,
+ })}
+ >
+ <LemonButton
+ type="primary"
+ size="small"
+ icon={<IconPlusSmall />}
+ data-attr="dashboard-tile-group-empty-tab-add"
+ >
+ Add
+ </LemonButton>
+ </LemonMenu>
+ )
+}
diff --git a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
index b21e889df087..29e683c913fc 100644
--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
@@ -20,7 +20,13 @@ import { AccessControlLevel, AccessControlResourceType, DashboardPlacement, Dash
import { DashboardCustomizeMenu } from 'products/dashboards/frontend/components/DashboardCustomizeMenu/DashboardCustomizeMenu'
-import { DashboardAddTileHandlers, DashboardAddTileKey, getDashboardAddTileOptions } from './dashboardAddTileOptions'
+import {
+ DashboardAddTileHandlers,
+ DashboardAddTileKey,
+ DashboardAddTileOption,
+ getDashboardAddTileOptions,
+ groupDashboardAddTileOptions,
+} from './dashboardAddTileOptions'
import { DashboardCustomizeButton } from './DashboardCustomizeButton'
import { reportDashboardAddMenuOpened } from './dashboardEvents'
import { DashboardLoadAction, dashboardLogic } from './dashboardLogic'
@@ -33,13 +39,14 @@ const ADD_TILE_MENU_DATA_ATTRS: Record<DashboardAddTileKey, string> = {
image: 'dashboard-add-image-tile',
button: 'dashboard-add-button-tile',
widget: 'dashboard-add-widget',
+ group: 'dashboard-add-tile-group',
}
export function getAddTileMenuItems({
onBeforeSelect,
...handlers
}: DashboardAddTileHandlers & { onBeforeSelect?: () => void }): LemonMenuItems {
- const items: LemonMenuItem[] = getDashboardAddTileOptions(handlers).map((option) => ({
+ const toItem = (option: DashboardAddTileOption): LemonMenuItem => ({
label: option.label,
tag: option.tag,
onClick: () => {
@@ -47,13 +54,16 @@ export function getAddTileMenuItems({
option.onClick()
},
'data-attr': ADD_TILE_MENU_DATA_ATTRS[option.key],
- }))
+ })
- return [{ title: 'Content', items }]
+ return groupDashboardAddTileOptions(getDashboardAddTileOptions(handlers)).map(({ title, options }) => ({
+ title,
+ items: options.map(toItem),
+ }))
}
export function DashboardAddTileButton(): JSX.Element | null {
- const { dashboard, tiles } = useValues(dashboardLogic)
+ const { dashboard, tiles, tileGroupSectionsEnabled } = useValues(dashboardLogic)
const {
loadDashboard,
setAddWidgetModalOpen,
@@ -61,6 +71,7 @@ export function DashboardAddTileButton(): JSX.Element | null {
openTextTileModal,
openImageTileModal,
openButtonTileModal,
+ addTileGroup,
} = useActions(dashboardLogic)
if (!dashboard || tiles.length === 0) {
@@ -99,6 +110,7 @@ export function DashboardAddTileButton(): JSX.Element | null {
onAddImage: openImageTileModal,
onAddButton: openButtonTileModal,
setAddWidgetModalOpen,
+ onAddGroup: tileGroupSectionsEnabled ? () => addTileGroup() : undefined,
})}
onVisibilityChange={(visible) => {
if (visible) {
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index e38bdd9a2bf6..626c114cb6bc 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -225,6 +225,7 @@ const mockUpdateContainerWidth = jest.fn()
const mockMoveTileToSection = jest.fn()
const mockChangeTileGroupDisplay = jest.fn()
const mockRenameTileGroup = jest.fn()
+const mockSetRenamingTileGroupKey = jest.fn()
const mockPositionStrategies = new Map<Element, unknown>()
let mockGridWidth = 1200
let mockGridMounts = 0
@@ -299,6 +300,7 @@ describe('DashboardItems', () => {
moveTileToSection: mockMoveTileToSection,
changeTileGroupDisplay: mockChangeTileGroupDisplay,
renameTileGroup: mockRenameTileGroup,
+ setRenamingTileGroupKey: mockSetRenamingTileGroupKey,
}
}
@@ -833,14 +835,26 @@ describe('DashboardItems', () => {
logic === dashboardsModel ? { loadDashboardsIfNeeded: jest.fn() } : defaultActions(logic)
)
- const { container, findByText, findByDisplayValue, unmount } = render(<DashboardItems />)
+ const { container, findByText, findByDisplayValue, rerender, unmount } = render(<DashboardItems />)
fireEvent.click(container.querySelector('[data-attr="dashboard-tile-group-menu"]')!)
fireEvent.click(await findByText(item))
+ expect(mockSetRenamingTileGroupKey).toHaveBeenCalledWith('plans')
- fireEvent.change(await findByDisplayValue('Plans'), { target: { value: 'Pricing plans' } })
- fireEvent.click(await findByText('Submit'))
+ mockedUseValues.mockImplementation((logic) =>
+ logic === dashboardsModel
+ ? { dashboardsLoading: false }
+ : logic === dashboardLogic
+ ? { ...bandValues(logic), renamingTileGroupKey: 'plans' }
+ : bandValues(logic)
+ )
+ rerender(<DashboardItems />)
+
+ const titleInput = await findByDisplayValue('Plans')
+ fireEvent.change(titleInput, { target: { value: 'Pricing plans' } })
+ fireEvent.blur(titleInput)
await waitFor(() => expect(mockRenameTileGroup).toHaveBeenCalledWith('plans', 'Pricing plans'))
+ expect(mockSetRenamingTileGroupKey).toHaveBeenLastCalledWith(null)
unmount()
})
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index fd5fd5a3c3c0..7dcfc4f26507 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -18,6 +18,8 @@ import { TileDecorations } from 'lib/components/TileDecorations/TileDecorations'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { DashboardEventSource } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
+import { getDashboardAddTileOptions } from 'scenes/dashboard/dashboardAddTileOptions'
+import { DashboardEmptyGroupAddButton } from 'scenes/dashboard/DashboardEmptyGroupAddButton'
import { reportDashboardTileRepositioned } from 'scenes/dashboard/dashboardEvents'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import {
@@ -122,6 +124,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
widgetResultsByTileId,
widgetRefreshStatus,
scrollToBottomSignal,
+ renamingTileGroupKey,
sizeKey,
tileGroupSectionsEnabled,
tileGroupSections,
@@ -155,6 +158,14 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
copyGroupToDashboard,
changeTileGroupDisplay,
renameTileGroup,
+ setRenamingTileGroupKey,
+ setAddTargetTileGroupKey,
+ openAddInsightModal,
+ openTextTileModal,
+ openImageTileModal,
+ openButtonTileModal,
+ setAddWidgetModalOpen,
+ removeTileGroup,
setDashboardEditing,
toggleTileGroup,
selectTileGroupTab,
@@ -280,6 +291,30 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const onCopyGroupToDashboard = canEditDashboard && isEditablePlacement ? copyGroupToDashboard : undefined
const onChangeGroupDisplay = canEditDashboard && isEditablePlacement ? changeTileGroupDisplay : undefined
const onRenameTileGroup = canEditDashboard && isEditablePlacement ? renameTileGroup : undefined
+ // A layout edit only stages tile moves, but a delete saves at once, so Cancel would bring tiles back to a lost group.
+ const getAddTileOptions =
+ canEditDashboard && isEditablePlacement && !layoutEditMode
+ ? (groupKey: string) =>
+ getDashboardAddTileOptions({
+ onAddInsight: openAddInsightModal,
+ onAddText: openTextTileModal,
+ onAddImage: openImageTileModal,
+ onAddButton: openButtonTileModal,
+ setAddWidgetModalOpen,
+ }).map((option) => ({
+ key: option.key,
+ label: option.label,
+ onClick: () => {
+ setAddTargetTileGroupKey(groupKey)
+ option.onClick()
+ },
+ }))
+ : undefined
+ const getEmptyGroupAddAction =
+ canEditDashboard && isEditablePlacement && !layoutEditMode
+ ? (groupKey: string) => <DashboardEmptyGroupAddButton groupKey={groupKey} />
+ : undefined
+ const onRemoveTileGroup = canEditDashboard && isEditablePlacement && !layoutEditMode ? removeTileGroup : undefined
const isLayoutZoomToggled = layoutEditMode && layoutZoom !== 1
@@ -847,10 +882,15 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
collapsedTileGroupKeys={collapsedTileGroupKeys}
onToggleTileGroup={toggleTileGroup}
onRenameTileGroup={onRenameTileGroup}
+ renamingTileGroupKey={renamingTileGroupKey}
+ onRenamingTileGroupKeyChange={setRenamingTileGroupKey}
+ onRemoveTileGroup={onRemoveTileGroup}
copyToDestinations={copyToDestinations}
onCopyGroupToDashboard={onCopyGroupToDashboard}
copyLoading={copyGroupToDashboardLoading}
onChangeGroupDisplay={onChangeGroupDisplay}
+ getAddTileOptions={getAddTileOptions}
+ getEmptyGroupAddAction={getEmptyGroupAddAction}
>
{renderSectionGrid(section, index)}
</DashboardTileSectionBand>
@@ -871,10 +911,15 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
activeSectionKey={tileGroupSections[activeTabIndex].key}
onSelect={selectTileGroupTab}
onRenameGroup={onRenameTileGroup}
+ renamingGroupKey={renamingTileGroupKey}
+ onRenamingGroupKeyChange={setRenamingTileGroupKey}
+ onRemoveGroup={onRemoveTileGroup}
copyToDestinations={copyToDestinations}
onCopyGroupToDashboard={onCopyGroupToDashboard}
copyLoading={copyGroupToDashboardLoading}
onChangeGroupDisplay={onChangeGroupDisplay}
+ getAddTileOptions={getAddTileOptions}
+ getEmptyGroupAddAction={getEmptyGroupAddAction}
>
{renderSectionGrid(tileGroupSections[activeTabIndex], activeTabIndex)}
</DashboardTileGroupTabs>
diff --git a/frontend/src/scenes/dashboard/DashboardModals.tsx b/frontend/src/scenes/dashboard/DashboardModals.tsx
index 25b7bfb18a0c..516ccc833eb5 100644
--- a/frontend/src/scenes/dashboard/DashboardModals.tsx
+++ b/frontend/src/scenes/dashboard/DashboardModals.tsx
@@ -60,7 +60,8 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType }): JS
addWidgetModalOpen,
addWidgetTileLoading,
} = useValues(dashboardLogic)
- const { setTerraformModalOpen, setAddWidgetModalOpen, addWidgetTiles, closeTileModal } = useActions(dashboardLogic)
+ const { setTerraformModalOpen, setAddWidgetModalOpen, addWidgetTiles, closeTileModal, createTiles } =
+ useActions(dashboardLogic)
const { updateDashboardSuccess } = useActions(dashboardsModel)
const { push } = useActions(router)
const { user } = useValues(userLogic)
@@ -149,6 +150,7 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType }): JS
onClose={closeTile}
dashboard={dashboard}
imageTileId={selectedImageTileId}
+ onCreateTile={(tile) => createTiles([tile])}
/>
</Suspense>
) : shouldRenderTextTile ? (
@@ -158,6 +160,7 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType }): JS
onClose={closeTile}
dashboard={dashboard}
textTileId={textTileId}
+ onCreateTile={(tile) => createTiles([tile])}
/>
</Suspense>
) : null}
@@ -166,6 +169,7 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType }): JS
onClose={closeTile}
dashboard={dashboard}
buttonTileId={buttonTileId}
+ onCreateTile={(tile) => createTiles([tile])}
/>
{shouldRenderAddWidget ? (
<Suspense
diff --git a/frontend/src/scenes/dashboard/QuillDashboardAddTileButton.tsx b/frontend/src/scenes/dashboard/QuillDashboardAddTileButton.tsx
index 283034ca718f..d72e4d107b4c 100644
--- a/frontend/src/scenes/dashboard/QuillDashboardAddTileButton.tsx
+++ b/frontend/src/scenes/dashboard/QuillDashboardAddTileButton.tsx
@@ -18,7 +18,11 @@ import { MaxTool } from 'scenes/max/MaxTool'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
import { AccessControlLevel, AccessControlResourceType } from '~/types'
-import { DashboardAddTileKey, getDashboardAddTileOptions } from './dashboardAddTileOptions'
+import {
+ DashboardAddTileKey,
+ getDashboardAddTileOptions,
+ groupDashboardAddTileOptions,
+} from './dashboardAddTileOptions'
import { reportDashboardAddMenuOpened } from './dashboardEvents'
import { DashboardLoadAction, dashboardLogic } from './dashboardLogic'
@@ -29,10 +33,11 @@ const ADD_TILE_MENU_DATA_ATTRS: Record<DashboardAddTileKey, string> = {
image: 'dashboard-add-image-tile',
button: 'dashboard-add-button-tile',
widget: 'dashboard-add-widget',
+ group: 'dashboard-add-tile-group',
}
export function QuillDashboardAddTileButton(): JSX.Element | null {
- const { dashboard, tiles } = useValues(dashboardLogic)
+ const { dashboard, tiles, tileGroupSectionsEnabled } = useValues(dashboardLogic)
const {
loadDashboard,
setAddWidgetModalOpen,
@@ -40,6 +45,7 @@ export function QuillDashboardAddTileButton(): JSX.Element | null {
openTextTileModal,
openImageTileModal,
openButtonTileModal,
+ addTileGroup,
} = useActions(dashboardLogic)
if (!dashboard || tiles.length === 0) {
@@ -57,6 +63,7 @@ export function QuillDashboardAddTileButton(): JSX.Element | null {
onAddImage: openImageTileModal,
onAddButton: openButtonTileModal,
setAddWidgetModalOpen,
+ onAddGroup: tileGroupSectionsEnabled ? () => addTileGroup() : undefined,
})
return (
@@ -97,25 +104,29 @@ export function QuillDashboardAddTileButton(): JSX.Element | null {
Add
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="min-w-40">
- <DropdownMenuGroup>
- <DropdownMenuLabel>Content</DropdownMenuLabel>
- {options.map((option) => {
- return (
- <DropdownMenuItem
- key={option.key}
- onClick={option.onClick}
- data-attr={ADD_TILE_MENU_DATA_ATTRS[option.key]}
- >
- {option.label}
- {option.tag && (
- <Badge variant="success" className="ml-auto">
- {option.tag.toUpperCase()}
- </Badge>
- )}
- </DropdownMenuItem>
- )
- })}
- </DropdownMenuGroup>
+ {groupDashboardAddTileOptions(options).map(({ section, title, options: sectionOptions }) => {
+ return (
+ <DropdownMenuGroup key={section}>
+ <DropdownMenuLabel>{title}</DropdownMenuLabel>
+ {sectionOptions.map((option) => {
+ return (
+ <DropdownMenuItem
+ key={option.key}
+ onClick={option.onClick}
+ data-attr={ADD_TILE_MENU_DATA_ATTRS[option.key]}
+ >
+ {option.label}
+ {option.tag && (
+ <Badge variant="success" className="ml-auto">
+ {option.tag.toUpperCase()}
+ </Badge>
+ )}
+ </DropdownMenuItem>
+ )
+ })}
+ </DropdownMenuGroup>
+ )
+ })}
</DropdownMenuContent>
</DropdownMenu>
)}
diff --git a/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx b/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
index 131328ab6294..d4a47bb7c24a 100644
--- a/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
+++ b/frontend/src/scenes/dashboard/addInsightToDashboardModal/AddInsightToDashboardModal.tsx
@@ -34,7 +34,7 @@ const QUICK_CREATE_TYPES = [
export function AddInsightToDashboardModal(): JSX.Element {
const { hideAddInsightToDashboardModal, toggleShowMoreInsightTypes } = useActions(addInsightToDashboardLogic)
const { addInsightToDashboardModalVisible, showMoreInsightTypes } = useValues(addInsightToDashboardLogic)
- const { dashboard } = useValues(dashboardLogic)
+ const { dashboard, newTileGroupKey } = useValues(dashboardLogic)
const { featureFlags } = useValues(featureFlagLogic)
const handleClose = (): void => {
@@ -86,7 +86,11 @@ export function AddInsightToDashboardModal(): JSX.Element {
type="primary"
size="small"
icon={<Icon />}
- to={urls.insightNew({ type: type, dashboardId: dashboard?.id })}
+ to={urls.insightNew({
+ type: type,
+ dashboardId: dashboard?.id,
+ tileGroupKey: newTileGroupKey,
+ })}
tooltip={INSIGHT_TYPES_METADATA[type]?.description}
data-attr={`quick-create-${type.toLowerCase()}`}
onClick={() => handleNewInsightClicked(type)}
@@ -105,10 +109,12 @@ export function AddInsightToDashboardModal(): JSX.Element {
type === InsightType.SQL
? urls.sqlEditor({
dashboard: dashboard?.id,
+ tileGroupKey: newTileGroupKey,
})
: urls.insightNew({
type: type as InsightType,
dashboardId: dashboard?.id,
+ tileGroupKey: newTileGroupKey,
})
return (
<LemonButton
@@ -132,6 +138,7 @@ export function AddInsightToDashboardModal(): JSX.Element {
to={urls.insightNew({
type: InsightType.METRICS,
dashboardId: dashboard?.id,
+ tileGroupKey: newTileGroupKey,
})}
data-attr="create-metrics"
onClick={() => handleNewInsightClicked(InsightType.METRICS)}
diff --git a/frontend/src/scenes/dashboard/dashboardAddTileOptions.ts b/frontend/src/scenes/dashboard/dashboardAddTileOptions.ts
index 3faa2f2cbaf7..7280748867d3 100644
--- a/frontend/src/scenes/dashboard/dashboardAddTileOptions.ts
+++ b/frontend/src/scenes/dashboard/dashboardAddTileOptions.ts
@@ -1,7 +1,32 @@
-export type DashboardAddTileKey = 'insight' | 'text' | 'image' | 'button' | 'widget'
+export type DashboardAddTileKey = 'insight' | 'text' | 'image' | 'button' | 'widget' | 'group'
+
+/** Content adds a tile; layout organizes the tiles already there. */
+export type DashboardAddTileSection = 'content' | 'layout'
+
+export const DASHBOARD_ADD_TILE_SECTION_TITLES: Record<DashboardAddTileSection, string> = {
+ content: 'Content',
+ layout: 'Layout',
+}
+
+export interface DashboardAddTileOptionGroup {
+ section: DashboardAddTileSection
+ title: string
+ options: DashboardAddTileOption[]
+}
+
+export function groupDashboardAddTileOptions(options: DashboardAddTileOption[]): DashboardAddTileOptionGroup[] {
+ return (Object.keys(DASHBOARD_ADD_TILE_SECTION_TITLES) as DashboardAddTileSection[])
+ .map((section) => ({
+ section,
+ title: DASHBOARD_ADD_TILE_SECTION_TITLES[section],
+ options: options.filter((option) => option.section === section),
+ }))
+ .filter((group) => group.options.length > 0)
+}
export interface DashboardAddTileOption {
key: DashboardAddTileKey
+ section: DashboardAddTileSection
label: string
tag?: 'new'
onClick: () => void
@@ -13,6 +38,8 @@ export interface DashboardAddTileHandlers {
onAddImage: () => void
onAddButton: () => void
setAddWidgetModalOpen: (open: boolean) => void
+ /** Left out where the dashboard can't show tile groups. */
+ onAddGroup?: () => void
}
/** What a dashboard can add, in menu order. The header's Add menu and the scene menu bar both render this list. */
@@ -22,12 +49,23 @@ export function getDashboardAddTileOptions({
onAddImage,
onAddButton,
setAddWidgetModalOpen,
+ onAddGroup,
}: DashboardAddTileHandlers): DashboardAddTileOption[] {
- return [
- { key: 'insight', label: 'Charts', onClick: onAddInsight },
- { key: 'text', label: 'Add text', onClick: onAddText },
- { key: 'image', label: 'Image', onClick: onAddImage },
- { key: 'button', label: 'Button', onClick: onAddButton },
- { key: 'widget', label: 'Widget', onClick: () => setAddWidgetModalOpen(true) },
+ const options: DashboardAddTileOption[] = [
+ { key: 'insight', section: 'content', label: 'Charts', onClick: onAddInsight },
+ { key: 'text', section: 'content', label: 'Add text', onClick: onAddText },
+ { key: 'image', section: 'content', label: 'Image', onClick: onAddImage },
+ { key: 'button', section: 'content', label: 'Button', onClick: onAddButton },
+ { key: 'widget', section: 'content', label: 'Widget', onClick: () => setAddWidgetModalOpen(true) },
]
+ if (onAddGroup) {
+ options.push({
+ key: 'group',
+ section: 'layout',
+ label: 'Group',
+ tag: 'new',
+ onClick: onAddGroup,
+ })
+ }
+ return options
}
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index 9be47b9b0582..ee42cf7362c8 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -438,6 +438,236 @@ describe('dashboardLogic', () => {
featureFlagLogic.actions.setFeatureFlags([], {})
})
+ it.each([
+ { name: 'an editor on the dashboard', access: 'editor', placement: undefined, shown: true },
+ { name: 'a viewer', access: 'viewer', placement: undefined, shown: false },
+ {
+ name: 'an editor on a public link',
+ access: 'editor',
+ placement: DashboardPlacement.Public,
+ shown: false,
+ },
+ ])('shows a group with no tiles only to $name', async ({ access, placement, shown }) => {
+ groupTiles({ target: { collapsed: false }, empty: { collapsed: false } })
+ dashboards[5] = { ...dashboards[5], user_access_level: access as DashboardType['user_access_level'] }
+ await mountDashboard(placement)
+
+ expect(logic.values.tileGroupSections.map((section) => section.key).includes('group-empty')).toBe(shown)
+ })
+
+ it.each([
+ {
+ name: 'adds a group and keeps the others',
+ dispatch: () => logic.actions.addTileGroup(' New '),
+ expectedKeys: ['target', 'other', 'empty', 'added'],
+ },
+ {
+ name: 'removes an empty group and keeps the others',
+ dispatch: () => logic.actions.removeTileGroup('empty'),
+ expectedKeys: ['target', 'other'],
+ },
+ {
+ name: 'keeps a group that still has tiles',
+ dispatch: () => logic.actions.removeTileGroup('other'),
+ expectedKeys: null,
+ },
+ {
+ name: 'removes a group whose last tile was deleted',
+ dispatch: () => {
+ logic.actions.removeTile(dashboards[5].tiles[1])
+ logic.actions.removeTileGroup('other')
+ },
+ expectedKeys: ['target', 'empty'],
+ },
+ {
+ name: 'keeps a group whose last tile moved out only in an unsaved layout edit',
+ dispatch: () => {
+ logic.actions.setDashboardEditing(
+ { filters: true, layout: true },
+ DashboardEventSource.SceneCommonButtons
+ )
+ logic.actions.setTileProperty(dashboards[5].tiles[1].id, { group_key: null })
+ logic.actions.removeTileGroup('other')
+ },
+ expectedKeys: null,
+ },
+ ])('$name', async ({ dispatch, expectedKeys }) => {
+ groupTiles({ target: { collapsed: true }, other: { collapsed: false }, empty: { collapsed: false } })
+ await mountDashboard()
+ const update = jest.spyOn(logic.actions, 'saveTileGroups')
+
+ dispatch()
+
+ if (expectedKeys === null) {
+ expect(update).not.toHaveBeenCalled()
+ return
+ }
+ const groups = update.mock.calls[0][0]
+ const keys = Object.keys(groups).map((key) => (['target', 'other', 'empty'].includes(key) ? key : 'added'))
+ expect(keys).toEqual(expectedKeys)
+ // The change shows before the save answers.
+ expect(logic.values.dashboard?.customization?.groups).toEqual(groups)
+ // The API replaces every group on write, so the others go back unchanged.
+ expect(groups.target).toEqual({ collapsed: true })
+ // The save holds the logic mounted until it answers, so let it finish inside this test.
+ await expectLogic(dashboardsModel).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it.each([
+ { display: 'tabs' as const, title: undefined, opensTab: true },
+ { display: 'sections' as const, title: ' Named ', opensTab: false },
+ ])('opens a new group in $display ready to name', async ({ display, title, opensTab }) => {
+ groupTiles({ target: { collapsed: false } })
+ dashboards[5] = {
+ ...dashboards[5],
+ user_access_level: 'editor' as DashboardType['user_access_level'],
+ customization: { ...dashboards[5].customization, group_display: display },
+ }
+ await mountDashboard()
+ const scrollSignal = logic.values.scrollToBottomSignal
+
+ logic.actions.addTileGroup(title)
+
+ const added = Object.keys(logic.values.dashboard?.customization?.groups ?? {}).find(
+ (key) => key !== 'target'
+ )!
+ expect(logic.values.dashboard?.customization?.groups?.[added]).toEqual(title ? { title: 'Named' } : {})
+ expect(logic.values.renamingTileGroupKey).toEqual(added)
+ expect(logic.values.activeTileGroupTab).toEqual(opensTab ? added : null)
+ expect(logic.values.scrollToBottomSignal).toEqual(opensTab ? scrollSignal : scrollSignal + 1)
+ // The save holds the logic mounted until it answers, so let it finish inside this test.
+ await expectLogic(dashboardsModel).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ it.each([
+ { name: 'while the dashboard stays open', leaveDuringSave: false },
+ { name: 'after the dashboard closes', leaveDuringSave: true },
+ ])('sends a rename made while the new group saves after that save, $name', async ({ leaveDuringSave }) => {
+ groupTiles({ target: { collapsed: false } })
+ await mountDashboard()
+ const update = jest.spyOn(logic.actions, 'saveTileGroups')
+
+ logic.actions.addTileGroup()
+ const added = logic.values.renamingTileGroupKey!
+ logic.actions.renameTileGroup(added, 'Named')
+ expect(update).toHaveBeenCalledTimes(1)
+ if (leaveDuringSave) {
+ logic.unmount()
+ }
+ await expectLogic(dashboardsModel).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(update).toHaveBeenCalledTimes(2)
+ expect(update.mock.calls[1][0]).toEqual({
+ target: { collapsed: false },
+ [added]: { title: 'Named' },
+ })
+ if (leaveDuringSave) {
+ logic.mount()
+ }
+ })
+
+ it('puts back the saved groups and keeps a staged layout when a group change fails to save', async () => {
+ groupTiles({ target: { collapsed: false } })
+ await mountDashboard()
+ useMocks({ patch: { '/api/environments/:team_id/dashboards/:id/': () => [500, {}] } })
+ const errorToast = jest.spyOn(lemonToast, 'error').mockImplementation(() => '')
+ const staged = {
+ sm: (logic.values.layouts.sm ?? []).map((item, index) => (index === 0 ? { ...item, w: 6 } : item)),
+ }
+ logic.actions.stageLayouts(staged)
+
+ logic.actions.renameTileGroup('target', 'Unsaved')
+ await expectLogic(dashboardsModel).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(logic.values.dashboard?.customization?.groups).toEqual({ target: { collapsed: false } })
+ expect(logic.values.draftLayouts).toEqual(staged)
+ expect(errorToast).toHaveBeenCalledWith("Couldn't save the group change. Try again.")
+ })
+
+ it('keeps a queued rename when another dashboard write fails during the group save', async () => {
+ groupTiles({ target: { collapsed: false } })
+ await mountDashboard()
+ let releaseGroupSave = (): void => {}
+ const groupSaveReleased = new Promise<void>((resolve) => {
+ releaseGroupSave = resolve
+ })
+ const groupPatches: unknown[] = []
+ useMocks({
+ patch: {
+ '/api/environments/:team_id/dashboards/:id/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ if (!body.groups) {
+ return [500, {}]
+ }
+ groupPatches.push(body.groups)
+ if (groupPatches.length === 1) {
+ await groupSaveReleased
+ }
+ return [200, { ...dashboards[5], customization: { ...dashboards[5].customization, ...body } }]
+ },
+ },
+ })
+ jest.spyOn(lemonToast, 'error').mockImplementation(() => '')
+
+ logic.actions.renameTileGroup('target', 'First')
+ logic.actions.renameTileGroup('target', 'Second')
+ logic.actions.updateDashboardTags(['unrelated'])
+ await expectLogic(dashboardsModel).toDispatchActions(['updateDashboardFailure'])
+ releaseGroupSave()
+ await expectLogic(dashboardsModel).toFinishAllListeners()
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(groupPatches).toEqual([
+ { target: { collapsed: false, title: 'First' } },
+ { target: { collapsed: false, title: 'Second' } },
+ ])
+ })
+
+ it.each([
+ {
+ name: 'the group whose menu started the add',
+ display: 'sections' as const,
+ before: () => logic.actions.setAddTargetTileGroupKey('other'),
+ expectedGroup: 'other',
+ },
+ {
+ name: 'the open tab',
+ display: 'tabs' as const,
+ before: () => {},
+ expectedGroup: 'target',
+ },
+ {
+ name: 'no group after the group menu add closed',
+ display: 'sections' as const,
+ before: () => {
+ logic.actions.setAddTargetTileGroupKey('other')
+ logic.actions.closeTileModal()
+ },
+ expectedGroup: null,
+ },
+ ])('puts a tile added from the Add menu into $name', async ({ display, before, expectedGroup }) => {
+ groupTiles({ target: { collapsed: false }, other: { collapsed: false }, empty: { collapsed: false } })
+ dashboards[5] = {
+ ...dashboards[5],
+ customization: { ...dashboards[5].customization, group_display: display },
+ }
+ await mountDashboard()
+ await expectLogic(dashboardsModel).toFinishAllListeners()
+ before()
+ const update = jest.spyOn(dashboardsModel.actions, 'updateDashboard').mockImplementation(() => {})
+
+ logic.actions.createTiles([{ text: { body: 'New' } as DashboardTile['text'] }])
+
+ expect(update).toHaveBeenCalledWith({
+ id: 5,
+ tiles: [{ text: { body: 'New' }, ...(expectedGroup ? { group_key: expectedGroup } : {}) }],
+ })
+ })
+
it.each([
{ name: 'a link opened before the dashboard loads', beforeLoad: true, viewerChoice: undefined },
{ name: 'a link followed on a loaded dashboard', beforeLoad: false, viewerChoice: undefined },
@@ -6500,42 +6730,81 @@ describe('dashboardLogic', () => {
expect(fetchRunWidgetsMock).toHaveBeenCalledWith(String(MOCK_TEAM_ID), 5, [addedTile.id], expect.anything())
})
- it('addWidgetTiles keeps an existing tile movement unsaved', async () => {
- const addedTile = {
- id: 99,
- widget: { id: '3', widget_type: 'error_tracking_list', config: { limit: 5 } },
- layouts: { sm: { i: '99', x: 0, y: 10, w: 6, h: 5 } },
- color: null,
- } as unknown as DashboardTile
- jest.spyOn(api, 'create').mockResolvedValueOnce({ tiles: [addedTile] })
-
- logic = dashboardLogic({ id: 5 })
- logic.mount()
- await expectLogic(logic).toFinishAllListeners()
+ it.each([
+ {
+ name: 'with no target group',
+ addTarget: null,
+ groupWriteFails: false,
+ expectedGroupWrites: [],
+ expectedGroup: undefined,
+ },
+ {
+ name: 'when it goes into a group',
+ addTarget: 'target',
+ groupWriteFails: false,
+ expectedGroupWrites: [[5, { tiles: [{ id: 99, group_key: 'target' }] }]],
+ expectedGroup: 'target',
+ },
+ {
+ name: 'and shows the widget outside the group when the group write fails',
+ addTarget: 'target',
+ groupWriteFails: true,
+ expectedGroupWrites: [[5, { tiles: [{ id: 99, group_key: 'target' }] }]],
+ expectedGroup: null,
+ },
+ ])(
+ 'addWidgetTiles keeps an existing tile movement unsaved $name',
+ async ({ addTarget, groupWriteFails, expectedGroupWrites, expectedGroup }) => {
+ const addedTile = {
+ id: 99,
+ widget: { id: '3', widget_type: 'error_tracking_list', config: { limit: 5 } },
+ layouts: { sm: { i: '99', x: 0, y: 10, w: 6, h: 5 } },
+ color: null,
+ } as unknown as DashboardTile
+ jest.spyOn(api, 'create').mockResolvedValueOnce({ tiles: [addedTile] })
+ const groupWrite = jest.spyOn(dashboardGeneratedApi, 'dashboardsPartialUpdate')
+ if (groupWriteFails) {
+ groupWrite.mockRejectedValue(new Error('network'))
+ jest.spyOn(lemonToast, 'error').mockImplementation(() => '')
+ } else {
+ groupWrite.mockResolvedValue({} as any)
+ }
- const firstTile = logic.values.dashboard!.tiles[0]
- const savedLayouts = logic.values.savedTilePlacements[firstTile.id]?.layouts
- logic.actions.updateLayouts({
- ...logic.values.layouts,
- sm: logic.values.layouts.sm?.map((layout) =>
- layout.i === String(firstTile.id) ? { ...layout, x: layout.x + 1 } : layout
- ),
- })
- const draftLayouts = logic.values.dashboard!.tiles[0].layouts
- expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ logic.actions.setAddTargetTileGroupKey(addTarget)
- await expectLogic(logic, () => {
- logic.actions.addWidgetTiles({
- dashboardId: 5,
- widgets: [{ widgetType: 'error_tracking_list', config: { limit: 5 } }],
+ const firstTile = logic.values.dashboard!.tiles[0]
+ const savedLayouts = logic.values.savedTilePlacements[firstTile.id]?.layouts
+ logic.actions.updateLayouts({
+ ...logic.values.layouts,
+ sm: logic.values.layouts.sm?.map((layout) =>
+ layout.i === String(firstTile.id) ? { ...layout, x: layout.x + 1 } : layout
+ ),
})
- }).toFinishAllListeners()
+ const draftLayouts = logic.values.dashboard!.tiles[0].layouts
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
- expect(logic.values.dashboard!.tiles[0].layouts).toEqual(draftLayouts)
- expect(logic.values.savedTilePlacements[firstTile.id]?.layouts).toEqual(savedLayouts)
- expect(logic.values.savedTilePlacements[addedTile.id]?.layouts).toEqual(addedTile.layouts)
- expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
- })
+ await expectLogic(logic, () => {
+ logic.actions.addWidgetTiles({
+ dashboardId: 5,
+ widgets: [{ widgetType: 'error_tracking_list', config: { limit: 5 } }],
+ })
+ }).toFinishAllListeners()
+
+ expect(groupWrite.mock.calls.map(([, dashboardId, body]) => [dashboardId, body])).toEqual(
+ expectedGroupWrites
+ )
+ expect(logic.values.dashboard!.tiles[0].layouts).toEqual(draftLayouts)
+ expect(logic.values.savedTilePlacements[firstTile.id]?.layouts).toEqual(savedLayouts)
+ expect(logic.values.savedTilePlacements[addedTile.id]?.layouts).toEqual(addedTile.layouts)
+ const added = logic.values.dashboard!.tiles.find((tile) => tile.id === addedTile.id)
+ expect(added?.group_key ?? null).toEqual(expectedGroup ?? null)
+ expect(logic.values.savedTilePlacements[addedTile.id]?.group_key ?? null).toEqual(expectedGroup ?? null)
+ expect(logic.values.hasUnsavedLayoutChanges).toBe(true)
+ }
+ )
it('updateWidgetTile persists config and metadata in one patch', async () => {
const updateDashboardWidgetTileMock = jest
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index da1a0a4954a6..a8333d85106d 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -25,8 +25,15 @@ import { ResponsiveLayouts } from 'react-grid-layout'
import type { Layout } from 'react-grid-layout'
import { LemonButton, LemonDialog, lemonToast } from '@posthog/lemon-ui'
-import { dashboardsCopyGroupCreate } from '@posthog/products-dashboards/frontend/generated/api'
-import type { DashboardWidgetRunResultApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'
+import {
+ dashboardsCopyGroupCreate,
+ dashboardsPartialUpdate,
+ dashboardsRetrieve,
+} from '@posthog/products-dashboards/frontend/generated/api'
+import type {
+ DashboardTileGroupApi,
+ DashboardWidgetRunResultApi,
+} from '@posthog/products-dashboards/frontend/generated/api.schemas'
import { isWidgetConfigValidationError, updateDashboardWidgetTile } from '@posthog/products-dashboards/frontend/utils'
import { DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE } from '@posthog/products-dashboards/frontend/widgets/constants'
import {
@@ -113,6 +120,7 @@ import {
DashboardPlacement,
DashboardTemplateEditorType,
DashboardTile,
+ NewDashboardTile,
DashboardTileBasicType,
DashboardTileIdOrNew,
DashboardTileSpacing,
@@ -149,6 +157,7 @@ import {
getCollapsedTileGroupKeys,
getDashboardSections,
getDashboardTabs,
+ getEmptyTileGroupKeys,
getLayoutAfterSectionChange,
getLayoutAfterTileMove,
getSectionGroupKey,
@@ -156,6 +165,7 @@ import {
getTileGroupLabel,
getTileGroupMoveOptions,
UNGROUPED_TILES_TAB_KEY,
+ getTileGroupSectionKey,
} from 'products/dashboards/frontend/dashboardTileSections'
import { dataRetentionBannerLogic } from 'products/product_analytics/frontend/insights/dataRetention/dataRetentionBannerLogic'
import { exceedsRetention } from 'products/product_analytics/frontend/insights/dataRetention/exceedsRetention'
@@ -255,6 +265,13 @@ function reportDashboardTileRefreshed(
const TILE_REFRESH_CONCURRENCY = 4
+// Placements that show the dashboard's editing controls.
+const EDITABLE_PLACEMENTS = [
+ DashboardPlacement.Dashboard,
+ DashboardPlacement.ProjectHomepage,
+ DashboardPlacement.Builtin,
+]
+
/** `deferred` means a tab switch stopped the load, and the tile waits for its tab to open again. */
type InsightTileRefreshOutcome = 'refreshed' | 'cached' | 'errored' | 'aborted' | 'deferred'
@@ -621,16 +638,41 @@ function enqueueEditSave<T>(owner: TileSaveQueueOwner, save: () => Promise<T>):
return enqueueTileSave(owner, start, applied)
}
+/**
+ * Writes the group straight to the API, so it lands even if the dashboard closes while the add runs.
+ * Returns false when the write failed.
+ */
+export async function placeTilesInGroup(
+ teamId: number | null,
+ dashboardId: number,
+ tileIds: number[],
+ groupKey: string | null
+): Promise<boolean> {
+ if (!groupKey || tileIds.length === 0) {
+ return true
+ }
+ try {
+ await dashboardsPartialUpdate(String(teamId), dashboardId, {
+ tiles: tileIds.map((id) => ({ id, group_key: groupKey })),
+ })
+ return true
+ } catch {
+ lemonToast.error("Couldn't add the new tile to its group. Move it there with its Move to option.")
+ return false
+ }
+}
+
const groupKeyUpdate = (tile: DashboardTile, saved: TilePlacement | undefined): { group_key?: string | null } =>
tileGroupChanged(tile, saved) ? { group_key: tile.group_key ?? null } : {}
function calculateDraftLayouts(
tiles: DashboardTile[],
draftLayouts: ResponsiveLayouts | null,
+ groupsShareGrid: boolean,
savedPlacements?: Record<DashboardTile['id'], TilePlacement>
): ResponsiveLayouts {
if (!draftLayouts) {
- return calculateLayouts(tiles)
+ return calculateLayouts(tiles, { groupsShareGrid })
}
const draftSmByTile = new Map(draftLayouts.sm?.map((layout) => [layout.i, layout]))
@@ -643,7 +685,7 @@ function calculateDraftLayouts(
return sm ? ({ ...tile, layouts: { ...tile.layouts, sm } } as DashboardTile) : tile
})
- return calculateLayouts(tilesWithDraft)
+ return calculateLayouts(tilesWithDraft, { groupsShareGrid })
}
function mergeUpdatedWidgetTileIntoDashboard(dashboard: DashboardType, updatedTile: DashboardTile): DashboardType {
@@ -679,6 +721,7 @@ export interface dashboardLogicValues {
variables: Variable[] // variableDataLogic
accessDeniedToDashboard: boolean
activeTileGroupTab: string | null
+ addTargetTileGroupKey: string | null
addWidgetCollapsedGroups: string[]
addWidgetFilteredGroups: string[]
addWidgetModalOpen: boolean
@@ -761,6 +804,7 @@ export interface dashboardLogicValues {
initialDashboardSettingsOverride: DashboardSettings
initialVariablesLoaded: boolean
insightTiles: DashboardTile[]
+ isEditablePlacement: boolean
isPinned: boolean
isRefreshing: (id: string) => boolean
isRefreshingQueued: (id: string) => boolean
@@ -776,6 +820,7 @@ export interface dashboardLogicValues {
loadTimer: Date | null
loadingPreview: boolean
maxContext: MaxContextInput[]
+ newTileGroupKey: string | null
nextAllowedDashboardRefresh: Dayjs | null
nextWidgetStaleAt: number | null
oldestRefreshed: Dayjs | null
@@ -794,6 +839,7 @@ export interface dashboardLogicValues {
}
refreshStatus: Record<string, RefreshStatus>
refreshTilesTotal: number | null
+ renamingTileGroupKey: string | null
revealedTileGroup: RevealedTileGroup | null
savedDashboardSettings: DashboardSettings
savedTilePlacements: Record<DashboardTile['id'], TilePlacement>
@@ -857,6 +903,9 @@ export interface dashboardLogicActions {
queryStartTime: number
shortId: InsightShortId
}
+ addTileGroup: (title?: string) => {
+ title: string
+ }
addWidgetTileFinished: () => {
value: true
}
@@ -969,6 +1018,9 @@ export interface dashboardLogicActions {
toDashboardName: string
}
}
+ createTiles: (tiles: NewDashboardTile[]) => {
+ tiles: NewDashboardTile[]
+ }
dashboardNotFound: () => {
value: true
}
@@ -1182,6 +1234,9 @@ export interface dashboardLogicActions {
error: string
errorObject?: any
}
+ removeTileGroup: (groupKey: string) => {
+ groupKey: string
+ }
removeTileSuccess: (
dashboard: DashboardType | null,
payload?: {
@@ -1243,6 +1298,9 @@ export interface dashboardLogicActions {
themeId: number | null
} | null
}
+ restoreTileGroups: (groups: Record<string, DashboardTileGroupApi>) => {
+ groups: Record<string, DashboardTileGroupApi>
+ }
retryDashboardLoad: () => {
value: true
}
@@ -1298,6 +1356,9 @@ export interface dashboardLogicActions {
saveLayoutChanges: () => {
value: true
}
+ saveTileGroups: (groups: Record<string, DashboardTileGroupApi>) => {
+ groups: Record<string, DashboardTileGroupApi>
+ }
scheduleRefreshDashboardWidgets: (tileId: number) => {
tileId: number
}
@@ -1307,6 +1368,9 @@ export interface dashboardLogicActions {
setAccessDeniedToDashboard: () => {
value: true
}
+ setAddTargetTileGroupKey: (groupKey: string | null) => {
+ groupKey: string | null
+ }
setAddWidgetModalOpen: (open: boolean) => {
open: boolean
}
@@ -1440,6 +1504,9 @@ export interface dashboardLogicActions {
setRefreshTilesTotal: (total: number) => {
total: number
}
+ setRenamingTileGroupKey: (groupKey: string | null) => {
+ groupKey: string | null
+ }
setRevealedTileGroup: (revealedTileGroup: RevealedTileGroup | null) => {
revealedTileGroup: RevealedTileGroup | null
}
@@ -1459,6 +1526,9 @@ export interface dashboardLogicActions {
setTextTileId: (textTileId: DashboardTileIdOrNew) => {
textTileId: DashboardTileIdOrNew
}
+ setTileGroups: (groups: Record<string, DashboardTileGroupApi>) => {
+ groups: Record<string, DashboardTileGroupApi>
+ }
setTileOverride: (tile: DashboardTile) => {
tile: DashboardTile
}
@@ -1725,6 +1795,7 @@ export interface dashboardLogicMeta {
asDashboardTemplate: (dashboard: DashboardType | null) => DashboardTemplateEditorType | undefined
placement: (arg: any) => DashboardPlacement
readOnly: (arg: any) => boolean
+ isEditablePlacement: (placement: DashboardPlacement, readOnly: boolean) => boolean
apiUrl: (
id: number
) => (
@@ -1747,6 +1818,7 @@ export interface dashboardLogicMeta {
highlightedInsightId: any,
searchParams: Record<string, any>
) => string | null
+ newTileGroupKey: (addTargetTileGroupKey: string | null, activeTileGroupTab: string | null) => string | null
collapsedTileGroupKeys: (
tileGroupSectionsEnabled: boolean,
placement: DashboardPlacement,
@@ -1813,7 +1885,11 @@ export interface dashboardLogicMeta {
currentTeam: null | import('~/types').TeamPublicType | import('~/types').TeamType
) => boolean
sizeKey: (columns: number | null) => DashboardLayoutSize | undefined
- layouts: (tiles: DashboardTile[], draftLayouts: Partial<Record<string, Layout>> | null) => ResponsiveLayouts
+ layouts: (
+ tiles: DashboardTile[],
+ draftLayouts: Partial<Record<string, Layout>> | null,
+ tileGroupSectionsEnabled: boolean
+ ) => ResponsiveLayouts
layout: (
layouts: Partial<Record<string, Layout>>,
sizeKey: DashboardLayoutSize | undefined
@@ -1825,7 +1901,9 @@ export interface dashboardLogicMeta {
layouts: Partial<Record<string, Layout>>,
dashboard: DashboardType | null,
placement: DashboardPlacement,
- tileGroupDisplay: TileGroupDisplay
+ tileGroupDisplay: TileGroupDisplay,
+ canEditDashboard: boolean,
+ isEditablePlacement: boolean
) => DashboardSection[]
tileGroupSectionLayouts: (
tileGroupSections: DashboardSection[],
@@ -2048,6 +2126,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
refreshOpenTileGroupsWaiting: true,
changeTileGroupDisplay: (groupDisplay: TileGroupDisplay) => ({ groupDisplay }),
renameTileGroup: (groupKey: string, title: string) => ({ groupKey, title }),
+ setRenamingTileGroupKey: (groupKey: string | null) => ({ groupKey }),
+ /** Null follows the open tab. */
+ setAddTargetTileGroupKey: (groupKey: string | null) => ({ groupKey }),
+ addTileGroup: (title?: string) => ({ title: title ?? '' }),
+ removeTileGroup: (groupKey: string) => ({ groupKey }),
refreshTileGroup: (groupKey: string) => ({ groupKey }),
setWaitingTileRefresh: (waiting: WaitingTileRefresh) => ({ waiting }),
clearWaitingTileRefresh: (tileIds: number[]) => ({ tileIds }),
@@ -2062,6 +2145,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
method: TileGroupMoveMethod
) => ({ tileId, sectionKey, cell, method }),
tilePlacementsSaved: (placements: Record<number, TilePlacement>) => ({ placements }),
+ /** Creates tiles in the add's target group, in the same request. */
+ createTiles: (tiles: NewDashboardTile[]) => ({ tiles }),
/** Debounced run_widgets refresh for a single tile (tile filters). */
scheduleRefreshDashboardWidgets: (tileId: number) => ({ tileId }),
applyWidgetIssueMetadataChange: (payload: {
@@ -2165,6 +2250,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
setAccessDeniedToDashboard: true,
/** Update the dashboard in dashboardsModel with given payload. */
triggerDashboardUpdate: (payload) => ({ payload }),
+ /** Shows a group change before it saves. The API replaces every group on write. */
+ setTileGroups: (groups: Record<string, DashboardTileGroupApi>) => ({ groups }),
+ saveTileGroups: (groups: Record<string, DashboardTileGroupApi>) => ({ groups }),
+ /** Puts back the groups the server holds after a group save fails, leaving tiles and layout drafts alone. */
+ restoreTileGroups: (groups: Record<string, DashboardTileGroupApi>) => ({ groups }),
saveDashboardTileSpacing: (tileSpacing: DashboardTileSpacing) => ({ tileSpacing }),
saveDashboardGridCompaction: (layoutCompaction: DashboardGridCompaction) => ({ layoutCompaction }),
setDashboardCustomizeMenuOpen: (open: boolean) => ({ open }),
@@ -2915,6 +3005,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
tiles: state?.tiles?.map((tile) => (tile.id === tileId ? { ...tile, ...properties } : tile)),
} as DashboardType
},
+ setTileGroups: (state, { groups }) =>
+ state ? { ...state, customization: { ...state.customization, groups } } : state,
+ restoreTileGroups: (state, { groups }) =>
+ state ? { ...state, customization: { ...state.customization, groups } } : state,
setDashboardTileSpacing: (state, { tileSpacing }) =>
state
? {
@@ -3444,6 +3538,22 @@ export const dashboardLogic = kea<dashboardLogicType>([
addWidgetTileFinished: () => false,
},
],
+ addTargetTileGroupKey: [
+ null as string | null,
+ {
+ setAddTargetTileGroupKey: (_, { groupKey }) => groupKey,
+ // Each add ends by closing its modal, so the next add from the dashboard's Add menu follows the open tab.
+ closeTileModal: () => null,
+ setAddWidgetModalOpen: (state, { open }) => (open ? state : null),
+ [addInsightToDashboardLogic.actionTypes.hideAddInsightToDashboardModal]: () => null,
+ },
+ ],
+ renamingTileGroupKey: [
+ null as string | null,
+ {
+ setRenamingTileGroupKey: (_, { groupKey }) => groupKey,
+ },
+ ],
// Incremented on each scroll-to-bottom request; the view effects on the change.
scrollToBottomSignal: [
0,
@@ -3839,6 +3949,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
(placement): DashboardPlacement => placement || DashboardPlacement.Dashboard,
],
readOnly: [() => [(_, props) => props.readOnly], (readOnly: boolean | undefined): boolean => !!readOnly],
+ isEditablePlacement: [
+ (s) => [s.placement, s.readOnly],
+ (placement: DashboardPlacement, readOnly: boolean): boolean =>
+ !readOnly && EDITABLE_PLACEMENTS.includes(placement),
+ ],
apiUrl: [
(_, p) => [p.id],
(id: number) => {
@@ -3927,6 +4042,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
return highlightedTab ?? (tileGroupSections[0] ? getSectionGroupKey(tileGroupSections[0]) : null)
},
],
+ newTileGroupKey: [
+ (s) => [s.addTargetTileGroupKey, s.activeTileGroupTab],
+ (addTargetTileGroupKey: string | null, activeTileGroupTab: string | null): string | null =>
+ addTargetTileGroupKey ??
+ (activeTileGroupTab && activeTileGroupTab !== UNGROUPED_TILES_TAB_KEY ? activeTileGroupTab : null),
+ ],
collapsedTileGroupKeys: [
(s) => [
s.tileGroupSectionsEnabled,
@@ -4155,9 +4276,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
],
layouts: [
- (s) => [s.tiles, s.draftLayouts],
- (tiles: DashboardTile[], draftLayouts: ResponsiveLayouts | null): ResponsiveLayouts =>
- calculateDraftLayouts(tiles, draftLayouts),
+ (s) => [s.tiles, s.draftLayouts, s.tileGroupSectionsEnabled],
+ (
+ tiles: DashboardTile[],
+ draftLayouts: ResponsiveLayouts | null,
+ tileGroupSectionsEnabled: boolean
+ ): ResponsiveLayouts => calculateDraftLayouts(tiles, draftLayouts, !tileGroupSectionsEnabled),
// Tile refreshes replace `tiles` once per insight response without touching geometry;
// keeping the result reference stable stops react-grid-layout re-laying-out every tile
// N times per dashboard refresh cycle.
@@ -4184,23 +4308,39 @@ export const dashboardLogic = kea<dashboardLogicType>([
],
/** Full-width bands, one per tile group, or none when the dashboard shows one grid. */
tileGroupSections: [
- (s) => [s.tileGroupSectionsEnabled, s.tiles, s.layouts, s.dashboard, s.placement, s.tileGroupDisplay],
+ (s) => [
+ s.tileGroupSectionsEnabled,
+ s.tiles,
+ s.layouts,
+ s.dashboard,
+ s.placement,
+ s.tileGroupDisplay,
+ s.canEditDashboard,
+ s.isEditablePlacement,
+ ],
(
tileGroupSectionsEnabled: boolean,
tiles: DashboardTile[],
layouts: ResponsiveLayouts,
dashboard: DashboardType | null,
placement: DashboardPlacement,
- tileGroupDisplay: TileGroupDisplay
+ tileGroupDisplay: TileGroupDisplay,
+ canEditDashboard: boolean,
+ isEditablePlacement: boolean
): DashboardSection[] => {
- if (!tileGroupSectionsEnabled || !tiles.some((tile) => tile.group_key)) {
+ const groups = dashboard?.customization?.groups
+ // Only editors see a group with no tiles, so they can fill it. Viewers would see an empty band.
+ const emptyGroupKeys =
+ canEditDashboard && isEditablePlacement ? getEmptyTileGroupKeys(tiles, groups) : []
+ if (!tileGroupSectionsEnabled || (!tiles.some((tile) => tile.group_key) && !emptyGroupKeys.length)) {
return []
}
const widgetTilesShown = isWidgetTileVisibleOnPlacement(placement)
const sections = getDashboardSections({
tiles: tiles.filter((tile) => !tile.widget || widgetTilesShown),
layout: layouts.sm,
- groups: dashboard?.customization?.groups,
+ groups,
+ emptyGroupKeys,
})
return tileGroupDisplay === 'tabs' ? getDashboardTabs(sections) : sections
},
@@ -4675,11 +4815,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
payload,
}: {
dashboard: DashboardType | null
- payload?: { layoutsPersisted?: boolean }
+ payload?: { layoutsPersisted?: boolean; groups?: Record<string, DashboardTileGroupApi> }
}) => {
if (!dashboard || !values.dashboard || dashboard.id !== props.id || values.dashboard.id !== dashboard.id) {
return
}
+ if (payload?.groups) {
+ cache.savedTileGroups = payload.groups
+ }
const layoutsPersisted = payload?.layoutsPersisted === true
const previousTiles = new Map(values.dashboard.tiles.map((tile) => [tile.id, tile]))
@@ -4687,7 +4830,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
const originalLayouts = layoutsPersisted
? layoutsByTile(
calculateLayouts(
- values.dashboard.tiles.map((tile) => withTilePlacement(tile, savedBefore[tile.id]))
+ values.dashboard.tiles.map((tile) => withTilePlacement(tile, savedBefore[tile.id])),
+ { groupsShareGrid: !values.tileGroupSectionsEnabled }
)
)
: null
@@ -4935,6 +5079,7 @@ export const dashboardLogic = kea<dashboardLogicType>([
calculateDraftLayouts(
dashboard.tiles.filter((tile) => !tile.deleted),
values.draftLayouts,
+ !values.tileGroupSectionsEnabled,
values.savedTilePlacements
)
)
@@ -5702,12 +5847,92 @@ export const dashboardLogic = kea<dashboardLogicType>([
changeTileGroupDisplay: ({ groupDisplay }) => {
actions.triggerDashboardUpdate({ group_display: groupDisplay })
},
+ createTiles: ({ tiles }) => {
+ const groupKey = values.newTileGroupKey
+ dashboardsModel.actions.updateDashboard({
+ id: props.id,
+ tiles: groupKey ? tiles.map((tile) => ({ ...tile, group_key: groupKey })) : tiles,
+ })
+ },
+ setTileGroups: ({ groups }) => {
+ // Each write sends every group, so a second write waits for the first.
+ if (cache.tileGroupsSaving) {
+ cache.pendingTileGroups = groups
+ return
+ }
+ cache.tileGroupsSaving = true
+ actions.saveTileGroups(groups)
+ },
+ saveTileGroups: async ({ groups }) => {
+ // The success listener marks this save as done, and a queued change waits for it, so stay mounted.
+ const releaseMount = dashboardLogic(props).mount()
+ try {
+ cache.savedTileGroups = null
+ // Other dashboard writes share this request's success and failure actions, so await this one.
+ await dashboardsModel.asyncActions.updateDashboard({ id: props.id, groups })
+ cache.tileGroupsSaving = false
+ const pendingTileGroups = cache.pendingTileGroups
+ cache.pendingTileGroups = null
+ if (cache.savedTileGroups !== groups) {
+ lemonToast.error("Couldn't save the group change. Try again.")
+ // A full reload would drop unsaved layout edits, so only the groups go back.
+ try {
+ const saved = await dashboardsRetrieve(String(values.currentTeamId), props.id)
+ actions.restoreTileGroups(saved.customization?.groups ?? {})
+ } catch {
+ if (!values.draftLayouts) {
+ actions.loadDashboard({ action: DashboardLoadAction.Update })
+ }
+ }
+ return
+ }
+ if (pendingTileGroups) {
+ actions.setTileGroups(pendingTileGroups)
+ }
+ } finally {
+ releaseMount()
+ }
+ },
renameTileGroup: ({ groupKey, title }) => {
// The API replaces every group on write, so send the others back unchanged.
const groups = values.dashboard?.customization?.groups ?? {}
- actions.triggerDashboardUpdate({
- groups: { ...groups, [groupKey]: { ...groups[groupKey], title: title.trim() } },
- })
+ actions.setTileGroups({ ...groups, [groupKey]: { ...groups[groupKey], title: title.trim() } })
+ },
+ addTileGroup: ({ title }) => {
+ // Each write sends every group, so a write that starts before the last one saves would drop its change.
+ if (dashboardsModel.values.dashboardLoading) {
+ lemonToast.info('Wait for dashboard changes to save, then add the group again')
+ return
+ }
+ const groups = values.dashboard?.customization?.groups ?? {}
+ const groupKey = uuid()
+ // An untitled group shows its tile count.
+ const trimmedTitle = title.trim()
+ actions.setTileGroups({ ...groups, [groupKey]: trimmedTitle ? { title: trimmedTitle } : {} })
+ actions.setRenamingTileGroupKey(groupKey)
+ if (values.tileGroupDisplay === 'tabs') {
+ actions.selectTileGroupTab(getTileGroupSectionKey(groupKey))
+ } else {
+ // A new group goes last, which can be below the fold.
+ actions.requestScrollToBottom()
+ }
+ posthog.capture('dashboard tile group added', { dashboard_id: props.id })
+ },
+ removeTileGroup: ({ groupKey }) => {
+ // A tile moved in after the menu opened would keep a group key with no settings.
+ // A tile staged out of the group is still in it on the server, and returns to it on Cancel.
+ if (
+ values.layoutEditMode ||
+ values.tiles.some(
+ (tile) =>
+ tile.group_key === groupKey ||
+ savedTilePlacement(values.savedTilePlacements, tile.id).group_key === groupKey
+ )
+ ) {
+ return
+ }
+ const { [groupKey]: _removed, ...groups } = values.dashboard?.customization?.groups ?? {}
+ actions.setTileGroups(groups)
},
refreshTileGroup: async ({ groupKey }) => {
const { waitingTileRefresh: waiting, refreshStatus, widgetRefreshStatus } = values
@@ -5848,6 +6073,8 @@ export const dashboardLogic = kea<dashboardLogicType>([
return
}
+ // Read before the request, because the modal can close and clear the target while it runs.
+ const groupKey = values.newTileGroupKey
try {
const previousWidgetTileIds = new Set(values.widgetTiles.map((tile) => tile.id))
@@ -5858,7 +6085,16 @@ export const dashboardLogic = kea<dashboardLogicType>([
`api/projects/${teamLogic.values.currentTeamId}/dashboards/${dashboardId}/widgets/batch/`,
{ widgets: widgetsPayload }
)
- const createdTiles = findNewlyAddedWidgetTiles(previousWidgetTileIds, response.tiles)
+ const createdTiles = findNewlyAddedWidgetTiles(previousWidgetTileIds, response.tiles).map((tile) =>
+ groupKey ? { ...tile, group_key: groupKey } : tile
+ )
+ // The tiles already show in their group, and a reload would drop an unsaved layout edit.
+ const groupSaved = placeTilesInGroup(
+ values.currentTeamId,
+ dashboardId,
+ createdTiles.map((tile) => tile.id),
+ groupKey
+ )
if (createdTiles.length > 0 && values.dashboard?.id === dashboardId) {
const dashboard = {
...values.dashboard,
@@ -5882,6 +6118,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
if (count > 1) {
lemonToast.success(`Added ${count} widgets`)
}
+
+ if (!(await groupSaved) && values.dashboard?.id === dashboardId) {
+ for (const tile of createdTiles) {
+ actions.setTileProperty(tile.id, { group_key: null })
+ const layouts = values.savedTilePlacements[tile.id]?.layouts ?? tile.layouts
+ actions.tilePlacementsSaved({ [tile.id]: { layouts, group_key: null } })
+ }
+ }
} catch (e) {
lemonToast.error(e instanceof ApiError ? (e.detail ?? e.message) : 'Could not add widgets')
throw e
diff --git a/frontend/src/scenes/dashboard/tileLayouts.test.ts b/frontend/src/scenes/dashboard/tileLayouts.test.ts
index 287b3e19530e..69095bc764ae 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.test.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.test.ts
@@ -172,6 +172,47 @@ describe('calculating tile layouts', () => {
expect(result.xs?.[0]?.h).toBe(expectedXsH)
})
+ it.each([
+ {
+ name: 'the first tile of an empty group goes below every other tile',
+ tiles: [
+ { id: 1, layout: { x: 0, y: 0, w: 6, h: 5 } },
+ { id: 2, group_key: 'empty-group' },
+ ],
+ expected: { x: 0, y: 5 },
+ },
+ {
+ name: 'a tile in a group with tiles stays at or below the top row of its group',
+ tiles: [
+ { id: 1, layout: { x: 0, y: 0, w: 12, h: 5 } },
+ { id: 2, group_key: 'a', layout: { x: 0, y: 5, w: 6, h: 5 } },
+ { id: 3, group_key: 'b', layout: { x: 0, y: 10, w: 6, h: 5 } },
+ { id: 4, group_key: 'b' },
+ ],
+ expected: { x: 6, y: 10 },
+ },
+ {
+ name: 'without sections an ungrouped tile goes below grouped tiles in the shared grid',
+ tiles: [{ id: 1, group_key: 'a', layout: { x: 0, y: 0, w: 12, h: 5 } }, { id: 2 }],
+ groupsShareGrid: true,
+ expected: { x: 0, y: 5 },
+ },
+ ])('places a tile with no layout so its group keeps its order: $name', ({ tiles, groupsShareGrid, expected }) => {
+ const dashboardTiles: DashboardTile[] = tiles.map(({ id, layout, group_key }) => ({
+ ...textTileWithLayout(
+ (layout ? { sm: { i: String(id), ...layout } } : {}) as Record<DashboardLayoutSize, TileLayout>,
+ id
+ ),
+ ...(group_key ? { group_key } : {}),
+ }))
+
+ const placed = calculateLayouts(dashboardTiles, { groupsShareGrid }).sm?.find(
+ (layout) => layout.i === String(tiles.at(-1)!.id)
+ )
+
+ expect(placed).toMatchObject(expected)
+ })
+
it('xs follows final sm row-major order when some tiles have no stored sm layout', () => {
const tiles: DashboardTile[] = [
textTileWithLayout(
diff --git a/frontend/src/scenes/dashboard/tileLayouts.ts b/frontend/src/scenes/dashboard/tileLayouts.ts
index 9567bcf8aa94..25445e38bafa 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.ts
@@ -223,7 +223,10 @@ export const sortTilesByLayout = (tiles: Array<DashboardTile>, col: DashboardLay
return 0
})
}
-export const calculateLayouts = (tiles: DashboardTile[]): Partial<Record<DashboardLayoutSize, Layout>> => {
+export const calculateLayouts = (
+ tiles: DashboardTile[],
+ { groupsShareGrid = false }: { groupsShareGrid?: boolean } = {}
+): Partial<Record<DashboardLayoutSize, Layout>> => {
const allLayouts: Partial<Record<keyof typeof BREAKPOINT_COLUMN_COUNTS, Layout>> = {}
const imageTileIds = new Set(
tiles.filter((tile) => !!tile.text && !!getImageOnlyTextCardImage(tile.text.body)).map((tile) => tile.id)
@@ -338,17 +341,39 @@ export const calculateLayouts = (tiles: DashboardTile[]): Partial<Record<Dashboa
const cleanLayouts = layouts?.filter(({ y }) => y !== Infinity)
const dirtyLayouts = layouts?.filter(({ y }) => y === Infinity)
- // array of -1 for each column
- const lowestPoints = Array.from(Array(columnCount)).map(() => -1)
-
- // set the lowest point for each column
- for (const { x, y, w, h } of cleanLayouts) {
- for (let i = x; i <= x + w - 1; i++) {
- lowestPoints[i] = Math.max(lowestPoints[i], y + h - 1)
+ // Each group lays out on its own, so a new tile fills a gap in its own group.
+ // Without sections every group renders in one grid, so they all count as one group.
+ const groupOf = new Map(
+ tiles.map((tile) => [tile.id?.toString(), groupsShareGrid ? null : (tile.group_key ?? null)])
+ )
+ const lowestPointsByGroup = new Map<string | null, number[]>()
+ const lowestPointsFor = (groupKey: string | null): number[] => {
+ let points = lowestPointsByGroup.get(groupKey)
+ if (!points) {
+ const groupLayouts = cleanLayouts.filter(({ i }) => groupOf.get(i) === groupKey)
+ // Groups sort by their top tile, so a grouped tile never goes above its group's top row.
+ const floor =
+ groupKey === null || groupLayouts.length === 0
+ ? -1
+ : Math.min(...groupLayouts.map(({ y }) => y)) - 1
+ points = Array.from(Array(columnCount)).map(() => floor)
+ for (const { x, y, w, h } of groupLayouts) {
+ for (let column = x; column <= x + w - 1; column++) {
+ points[column] = Math.max(points[column], y + h - 1)
+ }
+ }
+ // The first tile of an empty group goes below every other tile, so the group goes last.
+ if (groupLayouts.length === 0 && groupKey !== null) {
+ const dashboardBottom = Math.max(-1, ...cleanLayouts.map(({ y, h }) => y + h - 1))
+ points = points.map(() => dashboardBottom)
+ }
+ lowestPointsByGroup.set(groupKey, points)
}
+ return points
}
for (const { i, w, h, minW, minH } of dirtyLayouts) {
+ const lowestPoints = lowestPointsFor(groupOf.get(i) ?? null)
// how low are things in "w" consecutive of columns
const segmentCount = columnCount - w + 1
const lowestSegments = Array.from(Array(segmentCount)).map(() => -1)
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index 6193c61cdfe0..98c884a5c412 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -4,6 +4,7 @@ import { router } from 'kea-router'
import { expectLogic, partial } from 'kea-test-utils'
import { LemonDialog } from '@posthog/lemon-ui'
+import * as dashboardsApi from '@posthog/products-dashboards/frontend/generated/api'
import { ApiError } from 'lib/api'
import { FEATURE_FLAGS, OrganizationMembershipLevel } from 'lib/constants'
@@ -3564,10 +3565,30 @@ describe('sqlEditorLogic', () => {
})
it.each([
- { name: 'creates the insight on the dashboard when a dashboardId is set', dashboardId: DASHBOARD_ID },
- { name: 'creates the insight on no dashboard when no dashboardId is set', dashboardId: null },
- ])('$name', async ({ dashboardId }) => {
- const createSpy = jest.spyOn(insightsApi, 'create').mockResolvedValue(MOCK_INSIGHT)
+ {
+ name: 'creates the insight on the dashboard when a dashboardId is set',
+ dashboardId: DASHBOARD_ID,
+ tileGroup: null,
+ expectedGroupWrites: [],
+ },
+ {
+ name: 'creates the insight on no dashboard when no dashboardId is set',
+ dashboardId: null,
+ tileGroup: null,
+ expectedGroupWrites: [],
+ },
+ {
+ name: 'creates the insight in the tile group the add started from',
+ dashboardId: DASHBOARD_ID,
+ tileGroup: 'target',
+ expectedGroupWrites: [[DASHBOARD_ID, { tiles: [{ id: 5, group_key: 'target' }] }]],
+ },
+ ])('$name', async ({ dashboardId, tileGroup, expectedGroupWrites }) => {
+ const createSpy = jest.spyOn(insightsApi, 'create').mockResolvedValue({
+ ...MOCK_INSIGHT,
+ dashboard_tiles: dashboardId !== null ? [{ id: 5, dashboard_id: dashboardId }] : [],
+ })
+ const groupWrite = jest.spyOn(dashboardsApi, 'dashboardsPartialUpdate').mockResolvedValue({} as any)
logic = sqlEditorLogic({
tabId: TAB_ID,
@@ -3580,6 +3601,7 @@ describe('sqlEditorLogic', () => {
await expectLogic(logic).toDispatchActions(['createTab', 'updateTab'])
if (dashboardId !== null) {
logic.actions.setDashboardId(dashboardId)
+ logic.actions.setDashboardTileGroupKey(tileGroup)
}
logic.actions.setQueryInput('SELECT 42 AS unrun_edit')
@@ -3595,6 +3617,7 @@ describe('sqlEditorLogic', () => {
})
expect(createPayload).not.toHaveProperty('dashboards')
expect(createSpy.mock.calls[0][1]).toEqual(dashboardId !== null ? [dashboardId] : [])
+ expect(groupWrite.mock.calls.map(([, id, body]) => [id, body])).toEqual(expectedGroupWrites)
})
it.each([
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
index d97ad0570465..a90b3ac5ccf1 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.tsx
@@ -49,7 +49,7 @@ import { objectsEqual, removeUndefinedAndNull } from 'lib/utils/objects'
import { lazyWithRetry } from 'lib/utils/retryImport'
import { slugify } from 'lib/utils/strings'
import { backLinkParams, withBackLink } from 'scenes/analytics/analyticsBackLink'
-import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { DashboardLoadAction, dashboardLogic, placeTilesInGroup } from 'scenes/dashboard/dashboardLogic'
import {
MANAGED_TRINO_SCHEMA_SCOPE,
databaseTableListLogic,
@@ -676,6 +676,7 @@ export interface sqlEditorLogicValues {
changesToSave: boolean
currentDraft: DataWarehouseSavedQueryDraft | null | undefined
dashboardId: number | null
+ dashboardTileGroupKey: string | null
dataLogicKey: string
diffShowRunButton: boolean | undefined
editingAccessControlObject: DataWarehouseAccessControlModalProps | null
@@ -1143,6 +1144,9 @@ export interface sqlEditorLogicActions {
setDashboardId: (dashboardId: number | null) => {
dashboardId: number | null
}
+ setDashboardTileGroupKey: (groupKey: string | null) => {
+ groupKey: string | null
+ }
setDataError: (error: string | null) => {
error: string | null
}
@@ -1597,6 +1601,7 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
setSendRawQuery: (sendRawQuery: boolean) => ({ sendRawQuery }),
enforceConnectionRawQueryMode: true,
setDashboardId: (dashboardId: number | null) => ({ dashboardId }),
+ setDashboardTileGroupKey: (groupKey: string | null) => ({ groupKey }),
openMaterializationModal: (view?: DataWarehouseSavedQuery) => ({
view,
}),
@@ -1809,6 +1814,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
setDashboardId: (_, { dashboardId }) => dashboardId,
},
],
+ dashboardTileGroupKey: [
+ null as string | null,
+ {
+ setDashboardTileGroupKey: (_, { groupKey }) => groupKey,
+ setDashboardId: (state, { dashboardId }) => (dashboardId === null ? null : state),
+ },
+ ],
materializationModalOpen: [
false,
{
@@ -2978,6 +2990,13 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
cache.timeouts.push(timeoutId)
if (dashboardId) {
+ const tile = insight.dashboard_tiles?.find((t) => t.dashboard_id === dashboardId)
+ await placeTilesInGroup(
+ teamLogic.values.currentTeamId,
+ dashboardId,
+ tile ? [tile.id] : [],
+ values.dashboardTileGroupKey
+ )
dashboardsModel.findMounted()?.actions.updateDashboardInsight(insight)
dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
action: DashboardLoadAction.Update,
@@ -3959,6 +3978,10 @@ export const sqlEditorLogic = kea<sqlEditorLogicType>([
const parsed = parseInt(searchParams.dashboard, 10)
if (!isNaN(parsed)) {
actions.setDashboardId(parsed)
+ const tileGroup = searchParams.tile_group
+ actions.setDashboardTileGroupKey(
+ typeof tileGroup === 'string' || typeof tileGroup === 'number' ? String(tileGroup) : null
+ )
}
}
diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.ts
index be12b44e92b5..acc39a548acc 100644
--- a/frontend/src/scenes/insights/insightLogic.test.ts
+++ b/frontend/src/scenes/insights/insightLogic.test.ts
@@ -645,56 +645,91 @@ describe('insightLogic', () => {
await expectLogic(dashLogic).toDispatchActions(['loadDashboard'])
})
+ const savedInsightProps: InsightLogicProps = {
+ dashboardItemId: Insight42,
+ cachedInsight: {
+ id: 42,
+ short_id: Insight42,
+ query: examples.FunnelsQuery,
+ result: {},
+ dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,
+ },
+ }
+ const newDashboardInsightProps: InsightLogicProps = {
+ dashboardItemId: 'new',
+ cachedInsight: { ...createEmptyInsight('new'), dashboards: [MOCK_DASHBOARD_ID] },
+ }
+
test.each([
{
name: 'a saved insight stays on the dashboards it sits on',
- insightProps: {
- dashboardItemId: Insight42,
- cachedInsight: {
- id: 42,
- short_id: Insight42,
- query: examples.FunnelsQuery,
- result: {},
- dashboard_tiles: TILES_ON_DASHBOARDS_1_2_3,
- },
- },
+ insightProps: savedInsightProps,
+ tileGroup: null,
expectedPlacements: [],
+ expectedGroupWrites: [],
+ },
+ {
+ name: 'a saved insight opened from a tile group link keeps its tiles where they are',
+ insightProps: savedInsightProps,
+ tileGroup: 'target',
+ expectedPlacements: [],
+ expectedGroupWrites: [],
},
{
name: 'a new insight goes on the dashboard it was started from',
- insightProps: {
- dashboardItemId: 'new',
- cachedInsight: { ...createEmptyInsight('new'), dashboards: [MOCK_DASHBOARD_ID] },
- },
+ insightProps: newDashboardInsightProps,
+ tileGroup: null,
expectedPlacements: [[12, MOCK_DASHBOARD_ID]],
+ expectedGroupWrites: [],
},
- ] as { name: string; insightProps: InsightLogicProps; expectedPlacements: number[][] }[])(
- 'saving: $name',
- async ({ insightProps, expectedPlacements }) => {
- const update = jest.spyOn(api, 'update')
- const create = jest.spyOn(api, 'create')
- const addToDashboard = jest
- .spyOn(insightsApi, 'addToDashboard')
- .mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
- logic = insightLogic(insightProps)
- logic.mount()
- insightDataLogic(insightProps).mount()
+ {
+ name: 'a new insight started from a tile group goes into that group',
+ insightProps: newDashboardInsightProps,
+ tileGroup: 'target',
+ expectedPlacements: [[12, MOCK_DASHBOARD_ID]],
+ expectedGroupWrites: [{ tiles: [{ id: 99, group_key: 'target' }] }],
+ },
+ ] as {
+ name: string
+ insightProps: InsightLogicProps
+ tileGroup: string | null
+ expectedPlacements: number[][]
+ expectedGroupWrites: unknown[]
+ }[])('saving: $name', async ({ insightProps, tileGroup, expectedPlacements, expectedGroupWrites }) => {
+ const groupWrites: unknown[] = []
+ useMocks({
+ patch: {
+ [`/api/environments/:team_id/dashboards/${MOCK_DASHBOARD_ID}/`]: async ({ request }) => {
+ groupWrites.push(await request.json())
+ return [200, {}]
+ },
+ },
+ })
+ router.actions.push('/insights/new', tileGroup ? { tile_group: tileGroup } : {})
+ const update = jest.spyOn(api, 'update')
+ const create = jest.spyOn(api, 'create')
+ const addToDashboard = jest
+ .spyOn(insightsApi, 'addToDashboard')
+ .mockImplementation(async (_insightId, dashboardId) => ({ id: 99, dashboard_id: dashboardId }))
+ logic = insightLogic(insightProps)
+ logic.mount()
+ insightDataLogic(insightProps).mount()
- await expectLogic(logic, () => {
- logic.actions.saveInsight()
- }).toFinishAllListeners()
+ await expectLogic(logic, () => {
+ logic.actions.saveInsight()
+ }).toFinishAllListeners()
- const insightWrites = [...update.mock.calls, ...create.mock.calls].filter(([url]) =>
- /\/insights\/?(\d+\/?)?$/.test(url)
- )
- expect(insightWrites).toHaveLength(1)
- expect(insightWrites[0][1]).not.toHaveProperty('dashboards')
- expect(addToDashboard.mock.calls).toEqual(expectedPlacements)
- update.mockRestore()
- create.mockRestore()
- addToDashboard.mockRestore()
- }
- )
+ const insightWrites = [...update.mock.calls, ...create.mock.calls].filter(([url]) =>
+ /\/insights\/?(\d+\/?)?$/.test(url)
+ )
+ expect(insightWrites).toHaveLength(1)
+ expect(insightWrites[0][1]).not.toHaveProperty('dashboards')
+ expect(addToDashboard.mock.calls).toEqual(expectedPlacements)
+ expect(groupWrites).toEqual(expectedGroupWrites)
+ update.mockRestore()
+ create.mockRestore()
+ addToDashboard.mockRestore()
+ })
test('updateInsight updates dashboards', async () => {
savedInsightsLogic().mount()
diff --git a/frontend/src/scenes/insights/insightLogic.tsx b/frontend/src/scenes/insights/insightLogic.tsx
index 09e08aabc619..fe1f6a4dd5b9 100644
--- a/frontend/src/scenes/insights/insightLogic.tsx
+++ b/frontend/src/scenes/insights/insightLogic.tsx
@@ -76,6 +76,7 @@ import {
SetInsightOptions,
} from '~/types'
+import { dashboardsPartialUpdate } from 'products/dashboards/frontend/generated/api'
import {
titleMentionsMCP,
tryShowMCPAnalyticsNudge,
@@ -1365,6 +1366,24 @@ export const insightLogic: LogicWrapper<insightLogicType> = kea<insightLogicType
globalSetupLogic.findMounted()?.actions.markTaskAsCompleted(tasksToComplete)
+ // A new insight started from a dashboard tile group's Add menu goes into that group.
+ const tileGroupParam = router.values.searchParams.tile_group
+ const tileGroupKey =
+ typeof tileGroupParam === 'string' || typeof tileGroupParam === 'number' ? String(tileGroupParam) : ''
+ const newDashboardTile =
+ !insightNumericId && dashboards?.length === 1 && tileGroupKey
+ ? savedInsight.dashboard_tiles?.find(({ dashboard_id }) => dashboard_id === dashboards[0])
+ : undefined
+ if (newDashboardTile) {
+ try {
+ await dashboardsPartialUpdate(String(values.currentTeamId), newDashboardTile.dashboard_id, {
+ tiles: [{ id: newDashboardTile.id, group_key: tileGroupKey }],
+ })
+ } catch {
+ lemonToast.error("Couldn't add the new tile to its group. Move it there with its Move to option.")
+ }
+ }
+
// reload dashboards with updated insight
// since filters on dashboard might be different from filters on insight
// we need to trigger dashboard reload to pick up results for updated insight
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
index bfc43ef52020..340bde0b33e9 100644
--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
@@ -7,7 +7,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { dashboardResult } from 'scenes/dashboard/dashboardLogic.testHelpers'
+import { dashboardResult, tileFromInsight } from 'scenes/dashboard/dashboardLogic.testHelpers'
import { insightsApi } from 'scenes/insights/utils/api'
import { useMocks } from '~/mocks/jest'
@@ -370,21 +370,62 @@ describe('addSavedInsightsModalLogic', () => {
})
})
- it('refreshes the mounted dashboard after adding an insight', async () => {
+ it.each([
+ {
+ name: 'refreshes the mounted dashboard, and leaves a tile added with no target group out of any group',
+ existingTiles: [],
+ addTarget: null,
+ closeDashboard: false,
+ expectedGroupWrites: [],
+ },
+ {
+ name: 'refreshes the mounted dashboard, and leaves a tile that was already on the dashboard in its own group',
+ existingTiles: [tileFromInsight(createInsight(2), 3)],
+ addTarget: 'target',
+ closeDashboard: false,
+ expectedGroupWrites: [],
+ },
+ {
+ name: 'refreshes the mounted dashboard, and keeps the group the add started from when the modal closes during the request',
+ existingTiles: [],
+ addTarget: 'target',
+ closeDashboard: false,
+ expectedGroupWrites: [[1, { tiles: [{ id: 3, group_key: 'target' }] }]],
+ },
+ {
+ name: 'keeps the group the add started from when the dashboard closes during the request',
+ existingTiles: [],
+ addTarget: 'target',
+ closeDashboard: true,
+ expectedGroupWrites: [[1, { tiles: [{ id: 3, group_key: 'target' }] }]],
+ },
+ ])('after adding an insight, $name', async ({ existingTiles, addTarget, closeDashboard, expectedGroupWrites }) => {
initKeaTests()
- const dashboard = dashboardLogic({ id: 1, dashboard: dashboardResult(1, []) })
+ const dashboard = dashboardLogic({ id: 1, dashboard: dashboardResult(1, existingTiles) })
dashboard.mount()
const loadDashboard = jest.spyOn(dashboard.actions, 'loadDashboard').mockImplementation()
- jest.spyOn(insightsApi, 'addToDashboard').mockResolvedValue({ id: 3, dashboard_id: 1 })
+ const groupWrite = jest.spyOn(dashboardsApi, 'dashboardsPartialUpdate').mockResolvedValue({} as any)
+ dashboard.actions.setAddTargetTileGroupKey(addTarget)
+ jest.spyOn(insightsApi, 'addToDashboard').mockImplementation(async () => {
+ dashboard.actions.closeTileModal()
+ if (closeDashboard) {
+ dashboard.unmount()
+ }
+ return { id: 3, dashboard_id: 1 } as any
+ })
const logic = addSavedInsightsModalLogic()
logic.mount()
await expectLogic(logic, () => logic.actions.addInsightToDashboard(createInsight(1), 1)).toFinishAllListeners()
- expect(loadDashboard).toHaveBeenCalledWith({ action: DashboardLoadAction.Update })
-
+ expect(groupWrite.mock.calls.map(([, dashboardId, body]) => [dashboardId, body])).toEqual(expectedGroupWrites)
+ if (closeDashboard) {
+ expect(loadDashboard).not.toHaveBeenCalled()
+ } else {
+ expect(loadDashboard).toHaveBeenCalledWith({ action: DashboardLoadAction.Update })
+ dashboard.unmount()
+ }
logic.unmount()
- dashboard.unmount()
})
})
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
index 61993b60d7d5..13cb8851c11c 100644
--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.ts
@@ -11,7 +11,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { objectsEqual } from 'lib/utils/objects'
import { toParams } from 'lib/utils/url'
-import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+import { DashboardLoadAction, dashboardLogic, placeTilesInGroup } from 'scenes/dashboard/dashboardLogic'
import { insightsApi } from 'scenes/insights/utils/api'
import { teamLogic } from 'scenes/teamLogic'
import { userLogic } from 'scenes/userLogic'
@@ -387,6 +387,10 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([
addInsightToDashboard: async ({ insight, dashboardId }) => {
try {
actions.setDashboardUpdateLoading(insight.id, true)
+ const mountedDashboard = dashboardLogic.findMounted({ id: dashboardId })
+ const tileIdsBefore = new Set(mountedDashboard?.values.tiles.map((dashboardTile) => dashboardTile.id))
+ // Closing the modal clears the add target, so read it before the request.
+ const groupKey = mountedDashboard?.values.newTileGroupKey ?? null
const tile = await insightsApi.addToDashboard(insight.id, dashboardId)
actions.updateInsight({
...insight,
@@ -395,9 +399,17 @@ export const addSavedInsightsModalLogic = kea<addSavedInsightsModalLogicType>([
tile,
],
})
- dashboardLogic.findMounted({ id: dashboardId })?.actions.loadDashboard({
- action: DashboardLoadAction.Update,
- })
+ // A tile that was already on the dashboard stays in its own group.
+ await placeTilesInGroup(
+ values.currentTeamId,
+ dashboardId,
+ tileIdsBefore.has(tile.id) ? [] : [tile.id],
+ groupKey
+ )
+ // The dashboard can close while the requests run, so look it up again.
+ dashboardLogic
+ .findMounted({ id: dashboardId })
+ ?.actions.loadDashboard({ action: DashboardLoadAction.Update })
lemonToast.success('Insight added to dashboard')
} catch (e) {
actions.dashboardUpdateFailed(insight.id)
diff --git a/frontend/src/scenes/urls.ts b/frontend/src/scenes/urls.ts
index 914ed7e273a3..0454290db9a2 100644
--- a/frontend/src/scenes/urls.ts
+++ b/frontend/src/scenes/urls.ts
@@ -94,6 +94,7 @@ export const urls = {
executionTarget,
sendRawQuery,
dashboard,
+ tileGroupKey,
filters,
metricName,
metricPrefill,
@@ -110,6 +111,8 @@ export const urls = {
executionTarget?: HogQLQuery['executionTarget']
sendRawQuery?: boolean
dashboard?: number
+ /** The dashboard tile group the saved insight goes into. Only applies with `dashboard`. */
+ tileGroupKey?: string | null
/** Applied on top of the opened query/insight — carries unsaved view-mode filter edits into the editor */
filters?: HogQLFilters
/** Opens the editor bound to this data catalog metric so its query can be updated in place */
@@ -158,6 +161,9 @@ export const urls = {
if (dashboard) {
params.set('dashboard', String(dashboard))
+ if (tileGroupKey) {
+ params.set('tile_group', tileGroupKey)
+ }
}
const queryString = params.toString()
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 2e074745c8d4..2e19361e421f 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2575,6 +2575,11 @@ export interface Tileable {
export type DashboardTileIdOrNew = number | null
+/** A tile before the API creates it, so it has no id or server-set fields yet. */
+export type NewDashboardTile = Omit<Partial<DashboardTile>, 'text'> & {
+ text?: Partial<NonNullable<DashboardTile['text']>>
+}
+
export interface DashboardTile extends Tileable {
id: number
insight?: InsightModel
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx
index e2e39f63df71..0a566771fae5 100644
--- a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroup.tsx
@@ -9,7 +9,10 @@ import { pluralize } from 'lib/utils/strings'
import type { TileGroupDisplay } from '~/types'
import type { DashboardTileGroupApi } from '../../generated/api.schemas'
+import { DashboardTileGroupContextMenu } from './DashboardTileGroupContextMenu'
import { DashboardTileGroupMenu } from './DashboardTileGroupMenu'
+import { type DashboardTileGroupMenuActions, hasTileGroupMenuActions } from './DashboardTileGroupMenuOverlay'
+import { DashboardTileGroupTitleInput } from './DashboardTileGroupTitleInput'
import { TileGroupColorDot } from './TileGroupColorDot'
interface DashboardTileGroupProps {
@@ -17,7 +20,12 @@ interface DashboardTileGroupProps {
tileCount: number
collapsed: boolean
onToggle: () => void
+ addTileOptions?: DashboardTileGroupMenuActions['addTileOptions']
+ emptyAddAction?: React.ReactNode
onRename?: (title: string) => void
+ renaming?: boolean
+ onRenamingChange?: (renaming: boolean) => void
+ onRemove?: () => void
copyToDestinations?: DashboardWidgetPlacementDestination[]
onCopyToDashboard?: (dashboardId: number, dashboardName: string) => void
copyLoading?: boolean
@@ -30,7 +38,12 @@ export function DashboardTileGroup({
tileCount,
collapsed,
onToggle,
+ addTileOptions,
+ emptyAddAction,
onRename,
+ renaming = false,
+ onRenamingChange,
+ onRemove,
copyToDestinations,
onCopyToDashboard,
copyLoading,
@@ -38,45 +51,85 @@ export function DashboardTileGroup({
children,
}: DashboardTileGroupProps): JSX.Element {
const tileCountLabel = pluralize(tileCount, 'tile')
+ const menuActions: DashboardTileGroupMenuActions = {
+ groupDisplay: 'sections',
+ addTileOptions,
+ onStartRename: onRename && onRenamingChange ? () => onRenamingChange(true) : undefined,
+ onRemove,
+ groupHasTiles: tileCount > 0,
+ onChangeGroupDisplay,
+ copyToDestinations,
+ onCopyToDashboard,
+ copyLoading,
+ }
return (
<section className="DashboardTileGroup" data-attr="dashboard-tile-group">
<div className="flex min-w-0 items-center gap-2 pb-2">
- <LemonButton
- size="small"
- truncate
- // A tertiary button styles aria-expanded as an open menu, which reads as a highlight here.
- className="[&[aria-expanded=true]:not(:hover)]:!bg-transparent"
- tooltip={group.title || undefined}
- icon={
- <IconChevronRight
- className={clsx(
- 'transition-transform motion-reduce:transition-none',
- !collapsed && 'rotate-90'
- )}
- />
- }
- onClick={onToggle}
- aria-expanded={!collapsed}
- data-attr="dashboard-tile-group-toggle"
- >
- {group.color && <TileGroupColorDot color={group.color} className="mr-2" />}
- <span className="font-semibold">{group.title || tileCountLabel}</span>
- </LemonButton>
+ <DashboardTileGroupContextMenu className="flex min-w-0" {...menuActions}>
+ <LemonButton
+ size="small"
+ truncate
+ // A tertiary button styles aria-expanded as an open menu, which reads as a highlight here.
+ className="[&[aria-expanded=true]:not(:hover)]:!bg-transparent"
+ tooltip={renaming ? undefined : group.title || undefined}
+ icon={
+ <IconChevronRight
+ className={clsx(
+ 'transition-transform motion-reduce:transition-none',
+ !collapsed && 'rotate-90'
+ )}
+ />
+ }
+ onClick={renaming ? undefined : onToggle}
+ // The right-click menu wraps this button, which would otherwise add a dropdown arrow.
+ sideIcon={null}
+ aria-expanded={!collapsed}
+ data-attr="dashboard-tile-group-toggle"
+ >
+ {group.color && <TileGroupColorDot color={group.color} className="mr-2" />}
+ {renaming && onRename ? (
+ // Inside the button, so the chevron and padding stay where they are.
+ <DashboardTileGroupTitleInput
+ className="font-semibold"
+ initialTitle={group.title ?? ''}
+ placeholder={tileCountLabel}
+ onSave={onRename}
+ onDone={() => onRenamingChange?.(false)}
+ />
+ ) : (
+ <span className="font-semibold">{group.title || tileCountLabel}</span>
+ )}
+ </LemonButton>
+ </DashboardTileGroupContextMenu>
{group.title && collapsed && <span className="shrink-0 text-secondary text-xs">{tileCountLabel}</span>}
<div className="min-w-4 flex-1 border-t border-primary" />
- {(onRename || onChangeGroupDisplay || onCopyToDashboard) && (
- <DashboardTileGroupMenu
- groupDisplay="sections"
- title={group.title}
- onRename={onRename}
- onChangeGroupDisplay={onChangeGroupDisplay}
- copyToDestinations={copyToDestinations}
- onCopyToDashboard={onCopyToDashboard}
- copyLoading={copyLoading}
- />
- )}
+ {hasTileGroupMenuActions(menuActions) && <DashboardTileGroupMenu {...menuActions} />}
</div>
+ {!collapsed && tileCount === 0 && (
+ <div
+ className="flex flex-col items-center gap-3 rounded-lg border border-dashed px-4 py-6 text-center text-secondary"
+ data-attr="dashboard-tile-group-empty"
+ >
+ No tiles in this group yet. Add one, or move one here with its Move to option.
+ {(emptyAddAction || onRemove) && (
+ <div className="flex flex-wrap justify-center gap-2">
+ {emptyAddAction}
+ {onRemove && (
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ onClick={onRemove}
+ data-attr="dashboard-tile-group-empty-remove"
+ >
+ Delete group
+ </LemonButton>
+ )}
+ </div>
+ )}
+ </div>
+ )}
{!collapsed && children}
</section>
)
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupContextMenu.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupContextMenu.tsx
new file mode 100644
index 000000000000..aa3a03a5cb00
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupContextMenu.tsx
@@ -0,0 +1,57 @@
+import { useActions } from 'kea'
+import { useState } from 'react'
+
+import { LemonDropdown } from 'lib/lemon-ui/LemonDropdown'
+
+import { dashboardsModel } from '~/models/dashboardsModel'
+
+import {
+ type DashboardTileGroupMenuActions,
+ DashboardTileGroupMenuOverlay,
+ hasTileGroupMenuActions,
+} from './DashboardTileGroupMenuOverlay'
+
+interface DashboardTileGroupContextMenuProps extends DashboardTileGroupMenuActions {
+ className?: string
+ onDoubleClick?: () => void
+ children: React.ReactNode
+}
+
+export function DashboardTileGroupContextMenu({
+ className,
+ onDoubleClick,
+ children,
+ ...actions
+}: DashboardTileGroupContextMenuProps): JSX.Element {
+ const { loadDashboardsIfNeeded } = useActions(dashboardsModel)
+ const [visible, setVisible] = useState(false)
+
+ if (!hasTileGroupMenuActions(actions)) {
+ return <span className={className}>{children}</span>
+ }
+
+ return (
+ <LemonDropdown
+ visible={visible}
+ // Only right-click opens the menu. A left click on the header or tab keeps its own action.
+ onVisibilityChange={(nextVisible) => !nextVisible && setVisible(false)}
+ placement="bottom-start"
+ overlay={<DashboardTileGroupMenuOverlay {...actions} />}
+ >
+ <span
+ className={className}
+ onDoubleClick={onDoubleClick}
+ onContextMenu={(event) => {
+ event.preventDefault()
+ setVisible(true)
+ if (actions.onCopyToDashboard) {
+ loadDashboardsIfNeeded()
+ }
+ }}
+ data-attr="dashboard-tile-group-context-menu"
+ >
+ {children}
+ </span>
+ </LemonDropdown>
+ )
+}
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupEmptyTab.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupEmptyTab.tsx
new file mode 100644
index 000000000000..fcb8dd95bebf
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupEmptyTab.tsx
@@ -0,0 +1,47 @@
+import * as peekOverPng from '@posthog/brand/hoggies/png/peek-over'
+
+import { pngHoggie } from 'lib/brand/hoggies'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+const HedgehogPeekOver = pngHoggie(peekOverPng)
+
+interface DashboardTileGroupEmptyTabProps {
+ addAction?: React.ReactNode
+ onRemove?: () => void
+}
+
+export function DashboardTileGroupEmptyTab({ addAction, onRemove }: DashboardTileGroupEmptyTabProps): JSX.Element {
+ return (
+ <div
+ className="flex flex-col items-center gap-1 rounded-lg border border-dashed px-4 py-10 text-center"
+ data-attr="dashboard-tile-group-empty-tab"
+ >
+ {/* The PNG is a square with the hedgehog in its middle, so crop to the drawing (x 180-820, y 300-700 of 1000). */}
+ <div className="relative mb-3 aspect-[1.6] w-30 overflow-hidden">
+ <HedgehogPeekOver
+ style={{ position: 'absolute', width: '156.25%', maxWidth: 'none', left: '-28.125%', top: '-75%' }}
+ />
+ </div>
+ <h3 className="mb-0 text-base font-semibold">Nothing to see here yet</h3>
+ <p className="mb-0 max-w-120 text-secondary">
+ Add a new tile, or move one here from another tab with its Move to option.
+ </p>
+ {(addAction || onRemove) && (
+ <div className="mt-3 flex flex-wrap justify-center gap-2">
+ {addAction}
+ {onRemove && (
+ <LemonButton
+ type="secondary"
+ status="danger"
+ size="small"
+ onClick={onRemove}
+ data-attr="dashboard-tile-group-empty-tab-remove"
+ >
+ Delete tab
+ </LemonButton>
+ )}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupMenu.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupMenu.tsx
index 71efed05091f..5bc6c72cbd6a 100644
--- a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupMenu.tsx
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupMenu.tsx
@@ -1,78 +1,22 @@
-import { useActions, useValues } from 'kea'
+import { useActions } from 'kea'
-import { DashboardWidgetPlacementMenu } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'
-import type { DashboardWidgetPlacementDestination } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'
-import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { More } from 'lib/lemon-ui/LemonButton/More'
-import { LemonDialog } from 'lib/lemon-ui/LemonDialog'
-import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
-import { LemonField } from 'lib/lemon-ui/LemonField'
-import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { dashboardsModel } from '~/models/dashboardsModel'
-import type { TileGroupDisplay } from '~/types'
-const MENU_ITEMS: Record<
- TileGroupDisplay,
- { renameLabel: string; copyLabel: string; copyNoun: string; switchTo: TileGroupDisplay; switchLabel: string }
-> = {
- sections: {
- renameLabel: 'Rename group',
- copyLabel: 'Copy group to dashboard',
- copyNoun: 'group',
- switchTo: 'tabs',
- switchLabel: 'Show all groups as tabs',
- },
- tabs: {
- renameLabel: 'Rename tab',
- copyLabel: 'Copy tab to dashboard',
- copyNoun: 'tab',
- switchTo: 'sections',
- switchLabel: 'Show groups as sections',
- },
-}
+import {
+ type DashboardTileGroupMenuActions,
+ DashboardTileGroupMenuOverlay,
+ TILE_GROUP_MENU_ITEMS,
+} from './DashboardTileGroupMenuOverlay'
-interface DashboardTileGroupMenuProps {
- // Set by the caller to match where this menu renders: "sections" in the group header,
- // "tabs" in the tab bar. Not read from the dashboard's actual display mode.
- groupDisplay: TileGroupDisplay
- title?: string
- onRename?: (title: string) => void
- onChangeGroupDisplay?: (groupDisplay: TileGroupDisplay) => void
- copyToDestinations?: DashboardWidgetPlacementDestination[]
- onCopyToDashboard?: (dashboardId: number, dashboardName: string) => void
+interface DashboardTileGroupMenuProps extends DashboardTileGroupMenuActions {
copyLoading?: boolean
}
-export function DashboardTileGroupMenu({
- groupDisplay,
- title,
- onRename,
- onChangeGroupDisplay,
- copyToDestinations,
- onCopyToDashboard,
- copyLoading,
-}: DashboardTileGroupMenuProps): JSX.Element {
+export function DashboardTileGroupMenu({ copyLoading, ...actions }: DashboardTileGroupMenuProps): JSX.Element {
const { loadDashboardsIfNeeded } = useActions(dashboardsModel)
- // Each rename sends every group, so a second rename before the first saves would undo it.
- const { dashboardLoading: dashboardSaving } = useValues(dashboardsModel)
- const { renameLabel, copyLabel, copyNoun, switchTo, switchLabel } = MENU_ITEMS[groupDisplay]
-
- const openRenameDialog = (): void => {
- if (!onRename) {
- return
- }
- LemonDialog.openForm({
- title: renameLabel,
- initialValues: { title: title ?? '' },
- content: (
- <LemonField name="title">
- <LemonInput placeholder="Leave blank to show the tile count" maxLength={200} autoFocus />
- </LemonField>
- ),
- onSubmit: ({ title: newTitle }) => onRename(newTitle),
- })
- }
+ const { copyNoun } = TILE_GROUP_MENU_ITEMS[actions.groupDisplay]
return (
<More
@@ -80,43 +24,10 @@ export function DashboardTileGroupMenu({
tooltip="Group actions"
loading={copyLoading}
disabledReason={copyLoading ? `Copying ${copyNoun}` : undefined}
- dropdown={{ onVisibilityChange: (visible) => visible && onCopyToDashboard && loadDashboardsIfNeeded() }}
- overlay={
- <div className="min-w-48 p-1">
- {onRename && (
- <>
- <LemonButton
- fullWidth
- onClick={openRenameDialog}
- disabledReason={dashboardSaving ? 'Saving dashboard changes' : undefined}
- data-attr="dashboard-tile-group-menu-rename"
- >
- {renameLabel}
- </LemonButton>
- {(onCopyToDashboard || onChangeGroupDisplay) && <LemonDivider />}
- </>
- )}
- {onCopyToDashboard && (
- <>
- <DashboardWidgetPlacementMenu
- label={copyLabel}
- destinations={copyToDestinations ?? []}
- onSelect={({ id, name }) => onCopyToDashboard(id, name || 'Untitled')}
- />
- {onChangeGroupDisplay && <LemonDivider />}
- </>
- )}
- {onChangeGroupDisplay && (
- <LemonButton
- fullWidth
- onClick={() => onChangeGroupDisplay(switchTo)}
- data-attr={`dashboard-tile-group-menu-group-display-${switchTo}`}
- >
- {switchLabel}
- </LemonButton>
- )}
- </div>
- }
+ dropdown={{
+ onVisibilityChange: (visible) => visible && actions.onCopyToDashboard && loadDashboardsIfNeeded(),
+ }}
+ overlay={<DashboardTileGroupMenuOverlay {...actions} copyLoading={copyLoading} />}
/>
)
}
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupMenuOverlay.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupMenuOverlay.tsx
new file mode 100644
index 000000000000..adb966a64fa3
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupMenuOverlay.tsx
@@ -0,0 +1,160 @@
+import { useValues } from 'kea'
+
+import { IconChevronRight } from '@posthog/icons'
+
+import { DashboardWidgetPlacementMenu } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'
+import type { DashboardWidgetPlacementDestination } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+import { LemonMenu } from 'lib/lemon-ui/LemonMenu'
+
+import { dashboardsModel } from '~/models/dashboardsModel'
+import type { TileGroupDisplay } from '~/types'
+
+export const TILE_GROUP_MENU_ITEMS: Record<
+ TileGroupDisplay,
+ {
+ renameLabel: string
+ removeLabel: string
+ copyLabel: string
+ copyNoun: string
+ switchTo: TileGroupDisplay
+ switchLabel: string
+ }
+> = {
+ sections: {
+ renameLabel: 'Rename group',
+ removeLabel: 'Delete group',
+ copyLabel: 'Copy group to dashboard',
+ copyNoun: 'group',
+ switchTo: 'tabs',
+ switchLabel: 'Show all groups as tabs',
+ },
+ tabs: {
+ renameLabel: 'Rename tab',
+ removeLabel: 'Delete tab',
+ copyLabel: 'Copy tab to dashboard',
+ copyNoun: 'tab',
+ switchTo: 'sections',
+ switchLabel: 'Show groups as sections',
+ },
+}
+
+export interface DashboardTileGroupMenuActions {
+ // Set by the caller to match where this menu renders: "sections" in the group header,
+ // "tabs" in the tab bar. Not read from the dashboard's actual display mode.
+ groupDisplay: TileGroupDisplay
+ addTileOptions?: { key: string; label: string; onClick: () => void }[]
+ onStartRename?: () => void
+ onRemove?: () => void
+ /** Removing a group never takes tiles out of it, so delete stays disabled until the group is empty. */
+ groupHasTiles?: boolean
+ onChangeGroupDisplay?: (groupDisplay: TileGroupDisplay) => void
+ copyToDestinations?: DashboardWidgetPlacementDestination[]
+ onCopyToDashboard?: (dashboardId: number, dashboardName: string) => void
+ copyLoading?: boolean
+}
+
+export function hasTileGroupMenuActions({
+ addTileOptions,
+ onStartRename,
+ onRemove,
+ onChangeGroupDisplay,
+ onCopyToDashboard,
+}: DashboardTileGroupMenuActions): boolean {
+ return !!(addTileOptions?.length || onStartRename || onRemove || onChangeGroupDisplay || onCopyToDashboard)
+}
+
+export function DashboardTileGroupMenuOverlay({
+ groupDisplay,
+ addTileOptions,
+ onStartRename,
+ onRemove,
+ groupHasTiles,
+ onChangeGroupDisplay,
+ copyToDestinations,
+ onCopyToDashboard,
+ copyLoading,
+}: DashboardTileGroupMenuActions): JSX.Element {
+ // Each rename sends every group, so a second rename before the first saves would undo it.
+ const { dashboardLoading: dashboardSaving } = useValues(dashboardsModel)
+ const { renameLabel, removeLabel, copyLabel, copyNoun, switchTo, switchLabel } = TILE_GROUP_MENU_ITEMS[groupDisplay]
+ const savingReason = dashboardSaving ? 'Saving dashboard changes' : undefined
+
+ return (
+ <div className="min-w-48 p-1">
+ {!!addTileOptions?.length && (
+ <>
+ <LemonMenu
+ placement="right-start"
+ items={addTileOptions.map((option) => ({
+ label: option.label,
+ onClick: option.onClick,
+ 'data-attr': `dashboard-tile-group-menu-add-${option.key}`,
+ }))}
+ >
+ <LemonButton
+ fullWidth
+ sideIcon={<IconChevronRight />}
+ data-attr="dashboard-tile-group-menu-add"
+ >
+ Add tile
+ </LemonButton>
+ </LemonMenu>
+ <LemonDivider />
+ </>
+ )}
+ {onStartRename && (
+ <>
+ <LemonButton
+ fullWidth
+ onClick={onStartRename}
+ disabledReason={savingReason}
+ data-attr="dashboard-tile-group-menu-rename"
+ >
+ {renameLabel}
+ </LemonButton>
+ {!onRemove && (onCopyToDashboard || onChangeGroupDisplay) && <LemonDivider />}
+ </>
+ )}
+ {onRemove && (
+ <>
+ <LemonButton
+ fullWidth
+ status="danger"
+ onClick={onRemove}
+ disabledReason={
+ savingReason ??
+ (groupHasTiles ? `Move this ${copyNoun}'s tiles out before deleting it` : undefined)
+ }
+ data-attr="dashboard-tile-group-menu-remove"
+ >
+ {removeLabel}
+ </LemonButton>
+ {(onCopyToDashboard || onChangeGroupDisplay) && <LemonDivider />}
+ </>
+ )}
+ {onCopyToDashboard && (
+ <>
+ <DashboardWidgetPlacementMenu
+ label={copyLabel}
+ destinations={(copyToDestinations ?? []).map((destination) =>
+ copyLoading ? { ...destination, disabledReason: `Copying ${copyNoun}` } : destination
+ )}
+ onSelect={({ id, name }) => onCopyToDashboard(id, name || 'Untitled')}
+ />
+ {onChangeGroupDisplay && <LemonDivider />}
+ </>
+ )}
+ {onChangeGroupDisplay && (
+ <LemonButton
+ fullWidth
+ onClick={() => onChangeGroupDisplay(switchTo)}
+ data-attr={`dashboard-tile-group-menu-group-display-${switchTo}`}
+ >
+ {switchLabel}
+ </LemonButton>
+ )}
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx
index f3478318daf4..7a312e51c07b 100644
--- a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTabs.tsx
@@ -1,10 +1,15 @@
import type { DashboardWidgetPlacementDestination } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu'
import { LemonTabs } from 'lib/lemon-ui/LemonTabs'
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
import type { TileGroupDisplay } from '~/types'
import { type DashboardSection, getTileGroupLabel } from '../../dashboardTileSections'
+import { DashboardTileGroupContextMenu } from './DashboardTileGroupContextMenu'
+import { DashboardTileGroupEmptyTab } from './DashboardTileGroupEmptyTab'
import { DashboardTileGroupMenu } from './DashboardTileGroupMenu'
+import { type DashboardTileGroupMenuActions, hasTileGroupMenuActions } from './DashboardTileGroupMenuOverlay'
+import { DashboardTileGroupTitleInput } from './DashboardTileGroupTitleInput'
import { TileGroupColorDot } from './TileGroupColorDot'
interface DashboardTileGroupTabsProps {
@@ -12,10 +17,15 @@ interface DashboardTileGroupTabsProps {
activeSectionKey: string
onSelect: (sectionKey: string) => void
onRenameGroup?: (groupKey: string, title: string) => void
+ renamingGroupKey?: string | null
+ onRenamingGroupKeyChange?: (groupKey: string | null) => void
+ onRemoveGroup?: (groupKey: string) => void
copyToDestinations?: DashboardWidgetPlacementDestination[]
onCopyGroupToDashboard?: (groupKey: string, dashboardId: number, dashboardName: string) => void
copyLoading?: boolean
onChangeGroupDisplay?: (groupDisplay: TileGroupDisplay) => void
+ getAddTileOptions?: (groupKey: string) => DashboardTileGroupMenuActions['addTileOptions']
+ getEmptyGroupAddAction?: (groupKey: string) => React.ReactNode
children: React.ReactNode
}
@@ -24,14 +34,43 @@ export function DashboardTileGroupTabs({
activeSectionKey,
onSelect,
onRenameGroup,
+ renamingGroupKey = null,
+ onRenamingGroupKeyChange,
+ onRemoveGroup,
copyToDestinations,
onCopyGroupToDashboard,
copyLoading,
onChangeGroupDisplay,
+ getEmptyGroupAddAction,
+ getAddTileOptions,
children,
}: DashboardTileGroupTabsProps): JSX.Element {
const activeSection = sections.find((section) => section.key === activeSectionKey)
+ const getMenuActions = (section: DashboardSection | undefined): DashboardTileGroupMenuActions => {
+ if (section?.kind !== 'group') {
+ return { groupDisplay: 'tabs', onChangeGroupDisplay }
+ }
+ const { groupKey } = section
+ return {
+ groupDisplay: 'tabs',
+ addTileOptions: getAddTileOptions?.(groupKey),
+ onStartRename:
+ onRenameGroup && onRenamingGroupKeyChange ? () => onRenamingGroupKeyChange(groupKey) : undefined,
+ onRemove: onRemoveGroup ? () => onRemoveGroup(groupKey) : undefined,
+ groupHasTiles: section.tiles.length > 0,
+ onChangeGroupDisplay,
+ copyToDestinations,
+ onCopyToDashboard:
+ section.tiles.length > 0 && onCopyGroupToDashboard
+ ? (dashboardId, dashboardName) => onCopyGroupToDashboard(groupKey, dashboardId, dashboardName)
+ : undefined,
+ copyLoading,
+ }
+ }
+
+ const activeMenuActions = getMenuActions(activeSection)
+
return (
<section data-attr="dashboard-tile-group-tabs">
<LemonTabs
@@ -40,40 +79,49 @@ export function DashboardTileGroupTabs({
tabs={sections.map((section) => ({
key: section.key,
label:
- section.kind === 'group' ? (
- <span className="flex items-center gap-2">
+ section.kind === 'group' && section.groupKey === renamingGroupKey && onRenameGroup ? (
+ <DashboardTileGroupTitleInput
+ initialTitle={section.group.title ?? ''}
+ placeholder={getTileGroupLabel({}, section.tiles.length)}
+ onSave={(title) => onRenameGroup(section.groupKey, title)}
+ onDone={() => onRenamingGroupKeyChange?.(null)}
+ />
+ ) : section.kind === 'group' ? (
+ <DashboardTileGroupContextMenu
+ className="flex items-center gap-2"
+ onDoubleClick={
+ onRenameGroup && onRenamingGroupKeyChange
+ ? () => onRenamingGroupKeyChange(section.groupKey)
+ : undefined
+ }
+ {...getMenuActions(section)}
+ >
{section.group.color && <TileGroupColorDot color={section.group.color} />}
- {getTileGroupLabel(section.group, section.tiles.length)}
- </span>
+ {/* Long titles cut off so one tab can't push the others out of the bar. */}
+ <Tooltip title={section.group.title || undefined}>
+ <span className="max-w-50 truncate">
+ {getTileGroupLabel(section.group, section.tiles.length)}
+ </span>
+ </Tooltip>
+ </DashboardTileGroupContextMenu>
) : (
'Overview'
),
}))}
rightSlotClassName="pr-0"
+ trackTabSizes
rightSlot={
- (onRenameGroup || onChangeGroupDisplay || onCopyGroupToDashboard) && (
- <DashboardTileGroupMenu
- groupDisplay="tabs"
- title={activeSection?.kind === 'group' ? activeSection.group.title : undefined}
- onRename={
- activeSection?.kind === 'group' && onRenameGroup
- ? (title) => onRenameGroup(activeSection.groupKey, title)
- : undefined
- }
- onChangeGroupDisplay={onChangeGroupDisplay}
- copyToDestinations={copyToDestinations}
- onCopyToDashboard={
- activeSection?.kind === 'group' && onCopyGroupToDashboard
- ? (dashboardId, dashboardName) =>
- onCopyGroupToDashboard(activeSection.groupKey, dashboardId, dashboardName)
- : undefined
- }
- copyLoading={copyLoading}
- />
- )
+ hasTileGroupMenuActions(activeMenuActions) && <DashboardTileGroupMenu {...activeMenuActions} />
}
/>
- {children}
+ {activeSection?.kind === 'group' && activeSection.tiles.length === 0 ? (
+ <DashboardTileGroupEmptyTab
+ addAction={getEmptyGroupAddAction?.(activeSection.groupKey)}
+ onRemove={activeMenuActions.onRemove}
+ />
+ ) : (
+ children
+ )}
</section>
)
}
diff --git a/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTitleInput.tsx b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTitleInput.tsx
new file mode 100644
index 000000000000..b5c463f35478
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardTileGroup/DashboardTileGroupTitleInput.tsx
@@ -0,0 +1,58 @@
+import clsx from 'clsx'
+import { useRef, useState } from 'react'
+
+import { RawInputAutosize } from 'lib/lemon-ui/LemonInput/RawInputAutosize'
+
+interface DashboardTileGroupTitleInputProps {
+ initialTitle: string
+ placeholder: string
+ onSave: (title: string) => void
+ onDone: () => void
+ className?: string
+}
+
+/** Renames a group or tab in place. Leaving the field saves, Escape cancels. */
+export function DashboardTileGroupTitleInput({
+ initialTitle,
+ placeholder,
+ onSave,
+ onDone,
+ className,
+}: DashboardTileGroupTitleInputProps): JSX.Element {
+ const [value, setValue] = useState(initialTitle)
+ const cancelled = useRef(false)
+
+ return (
+ <RawInputAutosize
+ autoFocus
+ value={value}
+ placeholder={placeholder}
+ maxLength={200}
+ // No padding or border, so the field takes the label's exact size. The outline does not take space.
+ className={clsx(
+ 'm-0 -mr-0.5 rounded border-0 bg-transparent p-0 font-[inherit] text-[length:inherit] leading-[inherit] text-inherit outline outline-1 outline-offset-2 outline-accent placeholder:text-secondary',
+ className
+ )}
+ onChange={(event) => setValue(event.currentTarget.value)}
+ onFocus={(event) => event.currentTarget.select()}
+ // A tab label sits inside the tab button, so keys and clicks must not reach it.
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => {
+ event.stopPropagation()
+ if (event.key === 'Enter') {
+ event.currentTarget.blur()
+ } else if (event.key === 'Escape') {
+ cancelled.current = true
+ event.currentTarget.blur()
+ }
+ }}
+ onBlur={() => {
+ if (!cancelled.current && value.trim() !== initialTitle.trim()) {
+ onSave(value)
+ }
+ onDone()
+ }}
+ data-attr="dashboard-tile-group-title-input"
+ />
+ )
+}
diff --git a/products/dashboards/frontend/components/DashboardTileSectionBand.tsx b/products/dashboards/frontend/components/DashboardTileSectionBand.tsx
index 7ba101936300..de7bed7b574f 100644
--- a/products/dashboards/frontend/components/DashboardTileSectionBand.tsx
+++ b/products/dashboards/frontend/components/DashboardTileSectionBand.tsx
@@ -7,6 +7,7 @@ import type { TileGroupDisplay } from '~/types'
import type { DashboardSection } from '../dashboardTileSections'
import { DashboardTileGroup } from './DashboardTileGroup/DashboardTileGroup'
+import type { DashboardTileGroupMenuActions } from './DashboardTileGroup/DashboardTileGroupMenuOverlay'
interface DashboardTileSectionBandProps {
section: DashboardSection
@@ -15,10 +16,15 @@ interface DashboardTileSectionBandProps {
collapsedTileGroupKeys: string[]
onToggleTileGroup: (groupKey: string) => void
onRenameTileGroup?: (groupKey: string, title: string) => void
+ renamingTileGroupKey?: string | null
+ onRenamingTileGroupKeyChange?: (groupKey: string | null) => void
+ onRemoveTileGroup?: (groupKey: string) => void
copyToDestinations?: DashboardWidgetPlacementDestination[]
onCopyGroupToDashboard?: (groupKey: string, dashboardId: number, dashboardName: string) => void
copyLoading?: boolean
onChangeGroupDisplay?: (groupDisplay: TileGroupDisplay) => void
+ getAddTileOptions?: (groupKey: string) => DashboardTileGroupMenuActions['addTileOptions']
+ getEmptyGroupAddAction?: (groupKey: string) => React.ReactNode
children: React.ReactNode
}
@@ -29,10 +35,15 @@ export function DashboardTileSectionBand({
collapsedTileGroupKeys,
onToggleTileGroup,
onRenameTileGroup,
+ renamingTileGroupKey,
+ onRenamingTileGroupKeyChange,
+ onRemoveTileGroup,
copyToDestinations,
onCopyGroupToDashboard,
copyLoading,
onChangeGroupDisplay,
+ getAddTileOptions,
+ getEmptyGroupAddAction,
children,
}: DashboardTileSectionBandProps): JSX.Element {
return (
@@ -50,15 +61,20 @@ export function DashboardTileSectionBand({
collapsed={collapsedTileGroupKeys.includes(section.groupKey)}
onToggle={() => onToggleTileGroup(section.groupKey)}
onRename={onRenameTileGroup ? (title) => onRenameTileGroup(section.groupKey, title) : undefined}
+ renaming={renamingTileGroupKey === section.groupKey}
+ onRenamingChange={(renaming) => onRenamingTileGroupKeyChange?.(renaming ? section.groupKey : null)}
+ onRemove={onRemoveTileGroup ? () => onRemoveTileGroup(section.groupKey) : undefined}
copyToDestinations={copyToDestinations}
onCopyToDashboard={
- onCopyGroupToDashboard
+ onCopyGroupToDashboard && section.tiles.length > 0
? (dashboardId, dashboardName) =>
onCopyGroupToDashboard(section.groupKey, dashboardId, dashboardName)
: undefined
}
copyLoading={copyLoading}
onChangeGroupDisplay={onChangeGroupDisplay}
+ addTileOptions={getAddTileOptions?.(section.groupKey)}
+ emptyAddAction={getEmptyGroupAddAction?.(section.groupKey)}
>
{children}
</DashboardTileGroup>
diff --git a/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx b/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx
index c0a0c5c4cbfc..5924c7018f6e 100644
--- a/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx
+++ b/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx
@@ -21,7 +21,7 @@ import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { lemonToast } from 'lib/lemon-ui/LemonToast'
import { preflightLogic } from 'lib/logic/preflightLogic'
-import { DashboardTileIdOrNew, DashboardType } from '~/types'
+import { DashboardTileIdOrNew, DashboardType, NewDashboardTile } from '~/types'
import {
DEFAULT_IMAGE_TILE_POSITION,
@@ -60,11 +60,13 @@ export function ImageTileModal({
onClose,
dashboard,
imageTileId,
+ onCreateTile,
}: {
isOpen: boolean
onClose: () => void
dashboard: DashboardType
imageTileId: DashboardTileIdOrNew
+ onCreateTile?: (tile: NewDashboardTile) => void
}): JSX.Element {
const isNewTile = imageTileId === null
const modalLogicProps: TextCardModalProps = {
@@ -72,6 +74,7 @@ export function ImageTileModal({
textTileId: imageTileId,
onClose,
tileType: 'image',
+ onCreateTile,
}
const modalLogic = textCardModalLogic(modalLogicProps)
const { objectStorageAvailable } = useValues(preflightLogic)
diff --git a/products/dashboards/frontend/dashboardTileSections.test.ts b/products/dashboards/frontend/dashboardTileSections.test.ts
index 72bfe59845f7..107bc3a16179 100644
--- a/products/dashboards/frontend/dashboardTileSections.test.ts
+++ b/products/dashboards/frontend/dashboardTileSections.test.ts
@@ -26,9 +26,10 @@ const box = (id: number, x: number, y: number, w = 6, h = 2): Layout[number] =>
const sectionSummary = (
tiles: DashboardTile[],
layout: Layout | undefined,
- groups?: Record<string, DashboardTileGroupApi>
+ groups?: Record<string, DashboardTileGroupApi>,
+ emptyGroupKeys?: string[]
): string[] =>
- getDashboardSections({ tiles, layout, groups }).map((section) =>
+ getDashboardSections({ tiles, layout, groups, emptyGroupKeys }).map((section) =>
section.kind === 'group'
? `${section.groupKey}(${section.group.title ?? ''}): ${section.tiles.map((t) => t.id).join(',')}`
: `tiles: ${section.tiles.map((t) => t.id).join(',')}`
@@ -39,6 +40,7 @@ interface SectionsCase {
tiles: DashboardTile[]
layout: Layout
groups?: Record<string, DashboardTileGroupApi>
+ emptyGroupKeys?: string[]
expected: string[]
}
@@ -47,6 +49,7 @@ interface TileMoveCase {
tiles: DashboardTile[]
targetKey: string | null
cell: { x: number; y: number } | null
+ emptyGroupKeys?: string[]
expectedSections: string[]
expectedTile?: Partial<Layout[number]>
}
@@ -112,8 +115,16 @@ describe('dashboardTileSections', () => {
groups: { plans: { title: 'Pricing plans' } },
expected: ['__proto__(): 1'],
},
- ])('getDashboardSections $name', ({ tiles, layout, groups, expected }) => {
- expect(sectionSummary(tiles, layout, groups)).toEqual(expected)
+ {
+ name: 'puts groups with no tiles last, once each',
+ tiles: [tile(1), tile(2, 'plans')],
+ layout: [box(1, 0, 0), box(2, 0, 2)],
+ groups: { plans: { title: 'Plans' }, empty: { title: 'Empty' } },
+ emptyGroupKeys: ['empty', 'plans'],
+ expected: ['tiles: 1', 'plans(Plans): 2', 'empty(Empty): '],
+ },
+ ])('getDashboardSections $name', ({ tiles, layout, groups, emptyGroupKeys, expected }) => {
+ expect(sectionSummary(tiles, layout, groups, emptyGroupKeys)).toEqual(expected)
})
it.each<Omit<SectionsCase, 'groups'>>([
@@ -265,30 +276,52 @@ describe('dashboardTileSections', () => {
expectedSections: ['ops(): 2,1', 'tiles: 3'],
expectedTile: { x: 6, y: 0 },
},
- ])('getLayoutAfterTileMove: a tile moved $name', ({ tiles, targetKey, cell, expectedSections, expectedTile }) => {
- const layout = [box(1, 0, 0), box(2, 0, 2), box(3, 0, 4)]
- const sections = getDashboardSections({ tiles, layout, groups: undefined })
- const compactor = getDashboardGridCompactor(DashboardGridCompaction.Vertical)
+ {
+ name: 'into an empty group from the menu goes below every tile',
+ tiles: [tile(1), tile(2, 'ops'), tile(3)],
+ targetKey: 'group-new',
+ cell: null,
+ emptyGroupKeys: ['new'],
+ expectedSections: ['ops(): 2', 'tiles: 3', 'new(): 1'],
+ },
+ {
+ name: 'into an empty group by drag lands at the drop cell below every band',
+ tiles: [tile(1), tile(2, 'ops'), tile(3)],
+ targetKey: 'group-new',
+ cell: { x: 6, y: 0 },
+ emptyGroupKeys: ['new'],
+ expectedSections: ['ops(): 2', 'tiles: 3', 'new(): 1'],
+ expectedTile: { x: 6 },
+ },
+ ])(
+ 'getLayoutAfterTileMove: a tile moved $name',
+ ({ tiles, targetKey, cell, emptyGroupKeys, expectedSections, expectedTile }) => {
+ const layout = [box(1, 0, 0), box(2, 0, 2), box(3, 0, 4)]
+ const sections = getDashboardSections({ tiles, layout, groups: undefined, emptyGroupKeys })
+ const compactor = getDashboardGridCompactor(DashboardGridCompaction.Vertical)
- const moved = getLayoutAfterTileMove({
- layout,
- sections,
- sectionLayouts: sections.map((section) => getSectionLayouts({ sm: layout }, section.tiles, compactor).sm!),
- tileId: 1,
- target: sections.find((section) => section.key === targetKey) ?? null,
- cell,
- compactor,
- })
- const targetSection = sections.find((section) => section.key === targetKey)
- const movedTiles = tiles.map((t) =>
- t.id === 1 ? { ...t, group_key: targetSection?.kind === 'group' ? targetSection.groupKey : null } : t
- )
+ const moved = getLayoutAfterTileMove({
+ layout,
+ sections,
+ sectionLayouts: sections.map(
+ (section) => getSectionLayouts({ sm: layout }, section.tiles, compactor).sm!
+ ),
+ tileId: 1,
+ target: sections.find((section) => section.key === targetKey) ?? null,
+ cell,
+ compactor,
+ })
+ const targetSection = sections.find((section) => section.key === targetKey)
+ const movedTiles = tiles.map((t) =>
+ t.id === 1 ? { ...t, group_key: targetSection?.kind === 'group' ? targetSection.groupKey : null } : t
+ )
- expect(sectionSummary(movedTiles, moved)).toEqual(expectedSections)
- if (expectedTile) {
- expect(moved.find((item) => item.i === '1')).toMatchObject(expectedTile)
+ expect(sectionSummary(movedTiles, moved)).toEqual(expectedSections)
+ if (expectedTile) {
+ expect(moved.find((item) => item.i === '1')).toMatchObject(expectedTile)
+ }
}
- })
+ )
it('getTileGroupMoveOptions offers the other groups by their band labels, and taking a grouped tile out', () => {
const sections = getDashboardSections({
diff --git a/products/dashboards/frontend/dashboardTileSections.ts b/products/dashboards/frontend/dashboardTileSections.ts
index 778cbc07552b..bbc0651c43c3 100644
--- a/products/dashboards/frontend/dashboardTileSections.ts
+++ b/products/dashboards/frontend/dashboardTileSections.ts
@@ -32,6 +32,10 @@ export function isTileGroupSectionKey(sectionKey: string): boolean {
return sectionKey.startsWith(TILE_GROUP_SECTION_KEY_PREFIX)
}
+export function getTileGroupSectionKey(groupKey: string): string {
+ return `${TILE_GROUP_SECTION_KEY_PREFIX}${groupKey}`
+}
+
function tilesInLayoutOrder(tiles: DashboardTile[], layout: Layout | undefined): DashboardTile[] {
const positions = new Map((layout ?? []).map((item) => [item.i, item]))
const position = (tile: DashboardTile): [number, number] => {
@@ -45,15 +49,20 @@ function tilesInLayoutOrder(tiles: DashboardTile[], layout: Layout | undefined):
})
}
-/** Splits tiles into full-width bands: each group starts where its top-left tile is, other tiles fill the gaps. */
+/**
+ * Splits tiles into full-width bands: each group starts where its top-left tile is, other tiles fill the gaps.
+ * `emptyGroupKeys` are groups with no tiles yet, which go last so a new group shows at the bottom.
+ */
export function getDashboardSections({
tiles,
layout,
groups,
+ emptyGroupKeys = [],
}: {
tiles: DashboardTile[]
layout: Layout | undefined
groups: Record<string, DashboardTileGroupApi> | undefined
+ emptyGroupKeys?: string[]
}): DashboardSection[] {
const sections: DashboardSection[] = []
const groupSections = new Map<string, DashboardSection>()
@@ -69,7 +78,7 @@ export function getDashboardSections({
const group = groups && Object.hasOwn(groups, groupKey) ? groups[groupKey] : {}
const section: DashboardSection = {
kind: 'group',
- key: `${TILE_GROUP_SECTION_KEY_PREFIX}${groupKey}`,
+ key: getTileGroupSectionKey(groupKey),
groupKey,
group,
tiles: [tile],
@@ -88,9 +97,26 @@ export function getDashboardSections({
}
}
+ for (const groupKey of emptyGroupKeys) {
+ if (groupSections.has(groupKey)) {
+ continue
+ }
+ const group = groups && Object.hasOwn(groups, groupKey) ? groups[groupKey] : {}
+ sections.push({ kind: 'group', key: getTileGroupSectionKey(groupKey), groupKey, group, tiles: [] })
+ }
+
return sections
}
+/** Groups saved on the dashboard that no tile belongs to, such as one just added from the Add menu. */
+export function getEmptyTileGroupKeys(
+ tiles: DashboardTile[],
+ groups: Record<string, DashboardTileGroupApi> | undefined
+): string[] {
+ const usedGroupKeys = new Set(tiles.map((tile) => tile.group_key).filter(Boolean))
+ return Object.keys(groups ?? {}).filter((groupKey) => !usedGroupKeys.has(groupKey))
+}
+
// Group keys can't hold a null character, so no real group shares this key.
export const UNGROUPED_TILES_TAB_KEY = '\u0000ungrouped'
@@ -263,9 +289,9 @@ export function getLayoutAfterTileMove({
}): Layout {
const tileKey = tileId.toString()
if (!cell || !target) {
- const targetTileIds = new Set(
- (target ? target.tiles : sections.flatMap((section) => section.tiles)).map((tile) => tile.id.toString())
- )
+ // An empty group shows after every band, so its first tile goes below every tile too.
+ const targetTiles = target?.tiles.length ? target.tiles : sections.flatMap((section) => section.tiles)
+ const targetTileIds = new Set(targetTiles.map((tile) => tile.id.toString()))
targetTileIds.delete(tileKey)
const bottom = Math.max(0, ...layout.filter((item) => targetTileIds.has(item.i)).map((item) => item.y + item.h))
return layout.map((item) => (item.i === tileKey ? { ...item, y: bottom } : item))
diff --git a/products/product_analytics/manifest.tsx b/products/product_analytics/manifest.tsx
index 7a7225bbb7c3..d0a0a8b62352 100644
--- a/products/product_analytics/manifest.tsx
+++ b/products/product_analytics/manifest.tsx
@@ -45,11 +45,14 @@ export const manifest: ProductManifest = {
insightNew: ({
type,
dashboardId,
+ tileGroupKey,
query,
sceneSource,
}: {
type?: InsightType
dashboardId?: DashboardType['id'] | null
+ /** The dashboard tile group the saved insight goes into. Only applies with `dashboardId`. */
+ tileGroupKey?: string | null
query?: Node
sceneSource?: InsightSceneSource
} = {}): string => {
@@ -69,11 +72,15 @@ export const manifest: ProductManifest = {
return urls.sqlEditor({ query })
}
- return combineUrl('/insights/new', dashboardId ? { dashboard: dashboardId } : {}, {
- ...(type ? { insight: type } : {}),
- ...(query ? { q: typeof query === 'string' ? query : JSON.stringify(query) } : {}),
- ...(sceneSource ? { sceneSource } : {}),
- }).url
+ return combineUrl(
+ '/insights/new',
+ dashboardId ? { dashboard: dashboardId, ...(tileGroupKey ? { tile_group: tileGroupKey } : {}) } : {},
+ {
+ ...(type ? { insight: type } : {}),
+ ...(query ? { q: typeof query === 'string' ? query : JSON.stringify(query) } : {}),
+ ...(sceneSource ? { sceneSource } : {}),
+ }
+ ).url
},
insightNewHogQL: ({ query, filters }: { query: string; filters?: HogQLFilters }): string =>
urls.insightNew({