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.

perf(dashboards): lazy load dashboard destinations (#102278)

Matt Puab72744ed8ffb
diff --git a/frontend/src/layout/panel-layout/ProjectTree/menus/DashboardsMenuItems.tsx b/frontend/src/layout/panel-layout/ProjectTree/menus/DashboardsMenuItems.tsx
index a76e184c67b2..832580e1564e 100644
--- a/frontend/src/layout/panel-layout/ProjectTree/menus/DashboardsMenuItems.tsx
+++ b/frontend/src/layout/panel-layout/ProjectTree/menus/DashboardsMenuItems.tsx
@@ -1,4 +1,4 @@
-import { useValues } from 'kea'
+import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { IconChevronRight } from '@posthog/icons'
@@ -27,21 +27,32 @@ export function DashboardsMenuItems({
onLinkClick,
}: CustomMenuProps): JSX.Element {
const { pinnedDashboards, dashboardsLoading } = useValues(dashboardsModel)
+ const { loadDashboardsIfNeeded } = useActions(dashboardsModel)
return (
<>
- {pinnedDashboards.length > 0 ? (
- <MenuSub>
- <MenuSubTrigger asChild>
- <ButtonPrimitive menuItem>
- Pinned dashboards
- <IconChevronRight className="ml-auto size-3" />
- </ButtonPrimitive>
- </MenuSubTrigger>
+ <MenuSub
+ onOpenChange={(open) => {
+ if (open) {
+ loadDashboardsIfNeeded()
+ }
+ }}
+ >
+ <MenuSubTrigger asChild>
+ <ButtonPrimitive menuItem>
+ Pinned dashboards
+ <IconChevronRight className="ml-auto size-3" />
+ </ButtonPrimitive>
+ </MenuSubTrigger>
- <MenuSubContent>
- <MenuGroup>
- {pinnedDashboards.map((dashboard) => (
+ <MenuSubContent>
+ <MenuGroup>
+ {dashboardsLoading ? (
+ <MenuItem disabled>
+ <ButtonPrimitive menuItem>Loading...</ButtonPrimitive>
+ </MenuItem>
+ ) : pinnedDashboards.length > 0 ? (
+ pinnedDashboards.map((dashboard) => (
<MenuItem asChild key={dashboard.id}>
<Link
buttonProps={{
@@ -64,19 +75,15 @@ export function DashboardsMenuItems({
<span className="truncate">{dashboard.name}</span>
</Link>
</MenuItem>
- ))}
- </MenuGroup>
- </MenuSubContent>
- </MenuSub>
- ) : dashboardsLoading ? (
- <MenuItem disabled>
- <ButtonPrimitive menuItem>Loading...</ButtonPrimitive>
- </MenuItem>
- ) : (
- <MenuItem disabled>
- <ButtonPrimitive menuItem>No pinned dashboards</ButtonPrimitive>
- </MenuItem>
- )}
+ ))
+ ) : (
+ <MenuItem disabled>
+ <ButtonPrimitive menuItem>No pinned dashboards</ButtonPrimitive>
+ </MenuItem>
+ )}
+ </MenuGroup>
+ </MenuSubContent>
+ </MenuSub>
</>
)
}
diff --git a/frontend/src/layout/scenes/ConfigureHomeDashboardPicker.test.tsx b/frontend/src/layout/scenes/ConfigureHomeDashboardPicker.test.tsx
index 435b7081eeba..667ad99e70fe 100644
--- a/frontend/src/layout/scenes/ConfigureHomeDashboardPicker.test.tsx
+++ b/frontend/src/layout/scenes/ConfigureHomeDashboardPicker.test.tsx
@@ -22,7 +22,11 @@ describe('ConfigureHomeDashboardPicker', () => {
beforeEach(() => {
mockedUseValues.mockReturnValueOnce({ nameSortedDashboards: [], dashboardsLoading: true })
mockedUseValues.mockReturnValueOnce({ currentTeam: null })
- mockedUseActions.mockReturnValue({ setHomepage: jest.fn(), updateCurrentTeam: jest.fn() })
+ mockedUseActions.mockReturnValue({
+ loadDashboardsIfNeeded: jest.fn(),
+ setHomepage: jest.fn(),
+ updateCurrentTeam: jest.fn(),
+ })
})
it('disables selection until dashboards finish loading', () => {
diff --git a/frontend/src/layout/scenes/ConfigureHomeModalContent.tsx b/frontend/src/layout/scenes/ConfigureHomeModalContent.tsx
index 65fdd604162c..0e321141d22f 100644
--- a/frontend/src/layout/scenes/ConfigureHomeModalContent.tsx
+++ b/frontend/src/layout/scenes/ConfigureHomeModalContent.tsx
@@ -5,6 +5,7 @@ import { useEffect, useState } from 'react'
import { LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+import { dashboardsModel } from '~/models/dashboardsModel'
import { FileSystemIconType } from '~/queries/schema/schema-general'
import { sceneLogic } from '~/scenes/sceneLogic'
import { emptySceneParams } from '~/scenes/scenes'
@@ -37,6 +38,7 @@ export function ConfigureHomeModalContent(): JSX.Element {
const { homepage } = useValues(sceneLogic)
const { currentTeam } = useValues(teamLogic)
const { setHomepage } = useActions(sceneLogic)
+ const { loadDashboardsIfNeeded } = useActions(dashboardsModel)
const isUsingProjectDefault = !homepage
const isUsingNewTabHomepage = homepage?.sceneId === Scene.NewTab
@@ -92,6 +94,7 @@ export function ConfigureHomeModalContent(): JSX.Element {
setPendingMode(null)
setHomepage(newTabHomepage)
} else if (newValue === 'default_dashboard') {
+ loadDashboardsIfNeeded()
const dashboardId = currentTeam?.primary_dashboard
if (dashboardId) {
setPendingMode(null)
diff --git a/frontend/src/layout/scenes/HomepageConfiguration.tsx b/frontend/src/layout/scenes/HomepageConfiguration.tsx
index b5fba59c47a8..7f98822aa091 100644
--- a/frontend/src/layout/scenes/HomepageConfiguration.tsx
+++ b/frontend/src/layout/scenes/HomepageConfiguration.tsx
@@ -5,6 +5,7 @@ import { useEffect, useState } from 'react'
import { LemonSegmentedButton, LemonTag } from '@posthog/lemon-ui'
import { iconForType } from '~/layout/panel-layout/ProjectTree/defaultTree'
+import { dashboardsModel } from '~/models/dashboardsModel'
import { FileSystemIconType } from '~/queries/schema/schema-general'
import { sceneLogic } from '~/scenes/sceneLogic'
import { emptySceneParams } from '~/scenes/scenes'
@@ -38,6 +39,7 @@ export function HomepageConfiguration(): JSX.Element {
const { homepage } = useValues(sceneLogic)
const { currentTeam } = useValues(teamLogic)
const { setHomepage } = useActions(sceneLogic)
+ const { loadDashboardsIfNeeded } = useActions(dashboardsModel)
const isUsingProjectDefault = !homepage
const isUsingNewTabHomepage = homepage?.sceneId === Scene.NewTab
@@ -102,6 +104,7 @@ export function HomepageConfiguration(): JSX.Element {
setPendingMode(null)
setHomepage(newTabHomepage)
} else if (newValue === 'default_dashboard') {
+ loadDashboardsIfNeeded()
const dashboardId = currentTeam?.primary_dashboard
if (dashboardId) {
setPendingMode(null)
diff --git a/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx b/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx
index 111513b07883..15c02c4f5899 100644
--- a/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx
+++ b/frontend/src/lib/components/AddToDashboard/AddToDashboardModal.tsx
@@ -10,12 +10,14 @@ import { AutoSizer } from 'lib/components/AutoSizer'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonInput } from 'lib/lemon-ui/LemonInput/LemonInput'
import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
import { Link } from 'lib/lemon-ui/Link'
import { Tooltip } from 'lib/lemon-ui/Tooltip'
import { pluralize } from 'lib/utils/strings'
import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
+import { dashboardsModel } from '~/models/dashboardsModel'
import { DashboardBasicType, InsightLogicProps } from '~/types'
interface DashboardRelationRowProps {
@@ -160,6 +162,8 @@ export function AddToDashboardModal({
const { searchQuery, currentDashboards, orderedDashboards, scrollIndex, user } = useValues(logic)
const { setSearchQuery, addNewDashboard } = useActions(logic)
+ const { dashboardsLoading } = useValues(dashboardsModel)
+ const { loadDashboardsIfNeeded } = useActions(dashboardsModel)
const listRef = useListRef(null)
useEffect(() => {
@@ -168,6 +172,12 @@ export function AddToDashboardModal({
}
}, [scrollIndex, listRef.current])
+ useEffect(() => {
+ if (isOpen) {
+ loadDashboardsIfNeeded()
+ }
+ }, [isOpen, loadDashboardsIfNeeded])
+
const rowProps: DashboardRowProps = {
orderedDashboards,
currentDashboards,
@@ -222,21 +232,25 @@ export function AddToDashboardModal({
{pluralize(currentDashboards.length, 'dashboard', 'dashboards', false)}
</div>
<div className="min-h-[420px]">
- <AutoSizer
- renderProp={({ height, width }) =>
- height && width ? (
- <List<DashboardRowProps>
- listRef={listRef}
- style={{ width, height }}
- rowCount={orderedDashboards.length}
- overscanCount={100}
- rowHeight={40}
- rowComponent={DashboardRow}
- rowProps={rowProps}
- />
- ) : null
- }
- />
+ {dashboardsLoading ? (
+ <LemonSkeleton.Row repeat={8} />
+ ) : (
+ <AutoSizer
+ renderProp={({ height, width }) =>
+ height && width ? (
+ <List<DashboardRowProps>
+ listRef={listRef}
+ style={{ width, height }}
+ rowCount={orderedDashboards.length}
+ overscanCount={100}
+ rowHeight={40}
+ rowComponent={DashboardRow}
+ rowProps={rowProps}
+ />
+ ) : null
+ }
+ />
+ )}
</div>
</div>
</LemonModal>
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
index 63b464a1ccef..21176089d65f 100644
--- a/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardWidgetPlacementMenu.tsx
@@ -1,9 +1,12 @@
+import { useActions, useValues } from 'kea'
import { useCallback, useState } from 'react'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonInput } from 'lib/lemon-ui/LemonInput'
import { LemonMenu, LemonMenuItem, LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'
+import { dashboardsModel } from '~/models/dashboardsModel'
import type { DashboardBasicType } from '~/types'
export interface DashboardWidgetPlacementDestination {
@@ -28,6 +31,8 @@ export function DashboardWidgetPlacementMenu({
emptyDisabledReason = 'No other dashboards',
}: DashboardWidgetPlacementMenuProps): JSX.Element {
const [searchTerm, setSearchTermState] = useState('')
+ const { dashboardsLoading } = useValues(dashboardsModel)
+ const { loadDashboardsIfNeeded } = useActions(dashboardsModel)
const handleSearchChange = useCallback((value: string) => {
setSearchTermState(value)
@@ -40,7 +45,6 @@ export function DashboardWidgetPlacementMenu({
: destinations.filter((entry) =>
(entry.dashboard.name || 'Untitled').toLowerCase().includes(searchTerm.toLowerCase())
)
-
const SearchInputLabel = useCallback(() => {
return (
<div className="px-2 pt-2 pb-1">
@@ -52,7 +56,7 @@ export function DashboardWidgetPlacementMenu({
size="small"
fullWidth
allowClear
- onClick={(e) => e.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
autoFocus
/>
</div>
@@ -64,46 +68,45 @@ export function DashboardWidgetPlacementMenu({
label: SearchInputLabel,
}
- const items: LemonMenuItems =
- filteredDestinations.length > 0
- ? [
- { items: [searchItem] },
- {
- items: filteredDestinations.map(({ dashboard, disabledReason }) => ({
- label: disabledReason ? (
- <span className="flex flex-col items-start gap-0.5 text-left">
- <span>{dashboard.name || <i>Untitled</i>}</span>
- <span className="text-xs font-normal text-muted">{disabledReason}</span>
- </span>
- ) : (
- dashboard.name || <i>Untitled</i>
- ),
- key: dashboard.id,
- // Use `disabled` only: `disabledReason` on LemonButton adds a redundant tooltip when the label already explains why.
- disabled: !!disabledReason,
- onClick: () => {
- if (disabledReason) {
- return
- }
- onSelect(dashboard)
- setSearchTermState('')
- },
- })),
- },
- ]
- : [
- {
- items: [
- searchItem,
- {
- label: 'No dashboards match this search',
- key: 'no-results',
- },
- ],
- },
- ]
+ const items: LemonMenuItems = dashboardsLoading
+ ? [{ custom: true, label: () => <LemonSkeleton.Row className="m-2 h-8" repeat={5} fade /> }]
+ : filteredDestinations.length > 0
+ ? [
+ { items: [searchItem] },
+ {
+ items: filteredDestinations.map(({ dashboard, disabledReason }) => ({
+ label: disabledReason ? (
+ <span className="flex flex-col items-start gap-0.5 text-left">
+ <span>{dashboard.name || <i>Untitled</i>}</span>
+ <span className="text-xs font-normal text-muted">{disabledReason}</span>
+ </span>
+ ) : (
+ dashboard.name || <i>Untitled</i>
+ ),
+ key: dashboard.id,
+ disabled: !!disabledReason,
+ onClick: () => {
+ if (!disabledReason) {
+ onSelect(dashboard)
+ setSearchTermState('')
+ }
+ },
+ })),
+ },
+ ]
+ : [
+ {
+ items: [
+ searchItem,
+ {
+ label: 'No dashboards match this search',
+ key: 'no-results',
+ },
+ ],
+ },
+ ]
- if (!destinations.length) {
+ if (!destinations.length && !dashboardsLoading) {
return (
<LemonButton fullWidth disabledReason={emptyDisabledReason}>
{label}
@@ -117,6 +120,13 @@ export function DashboardWidgetPlacementMenu({
placement="right-start"
fallbackPlacements={['left-start']}
closeParentPopoverOnClickInside
+ onVisibilityChange={(visible) => {
+ if (visible) {
+ loadDashboardsIfNeeded()
+ } else {
+ setSearchTermState('')
+ }
+ }}
>
<LemonButton fullWidth>{label}</LemonButton>
</LemonMenu>
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 40e55a7be4a9..d30b976f3fec 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -158,6 +158,7 @@ export interface InsightCardProps extends Resizeable {
insight: QueryBasedInsightModel
/** id of the dashboard the card is on (when the card is being displayed on a dashboard) **/
dashboardId?: DashboardType['id']
+ canEditDashboard?: boolean
/** Whether the insight has been called to load. */
loadingQueued?: boolean
/** Whether the insight is loading. */
@@ -228,6 +229,7 @@ function InsightCardInternal(
tile,
insight,
dashboardId,
+ canEditDashboard,
ribbonColor,
loadingQueued,
loading,
@@ -462,6 +464,7 @@ function InsightCardInternal(
insight={insight}
ribbonColor={ribbonColor}
dashboardId={dashboardId}
+ canEditDashboard={canEditDashboard}
persistDisplayOptions={canPersistDisplayOptions ? persistDisplayOptions : undefined}
refreshAfterDisplayOptionsChange={handleRefreshAfterDisplayOptionsChange}
updateColor={updateColor}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
index 2fbf3b369f92..a8f5f0b39211 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightMeta.tsx
@@ -45,7 +45,6 @@ import { SURVEY_CREATED_SOURCE } from 'scenes/surveys/constants'
import { isSurveyableFunnelInsight, SurveyableFunnelInsight } from 'scenes/surveys/utils/opportunityDetection'
import { urls } from 'scenes/urls'
-import { dashboardsModel } from '~/models/dashboardsModel'
import { insightsModel } from '~/models/insightsModel'
import { QueryScanTileTooltip } from '~/queries/nodes/DataNode/QueryScanTileTooltip'
import { useInsightDisplayOptions } from '~/queries/nodes/InsightViz/insightDisplayOptions'
@@ -95,6 +94,7 @@ interface InsightMetaProps extends Pick<
| 'setOverride'
| 'duplicate'
| 'dashboardId'
+ | 'canEditDashboard'
| 'moveToDashboard'
| 'copyToDashboard'
| 'showEditingControls'
@@ -123,6 +123,7 @@ export function InsightMeta({
insight,
ribbonColor,
dashboardId,
+ canEditDashboard,
updateColor,
toggleShowDescription,
filtersOverride,
@@ -179,15 +180,13 @@ export function InsightMeta({
)
const { samplingFactor, hasDataWarehouseSeries } = useValues(insightVizDataLogic(insightLogicProps))
const { retentionApplies, retentionMonths, retentionPeriodLabel } = useValues(dataRetentionBannerLogic)
- const { nameSortedDashboards } = useValues(dashboardsModel)
- const { copyToDestinations } = useValues(
- dashboardWidgetMenusLogic({
- instanceKey: insight.short_id,
- dashboardId,
- dashboards: insight.dashboards,
- dashboard_tiles: insight.dashboard_tiles,
- })
- )
+ const dashboardWidgetMenusLogicProps = {
+ instanceKey: insight.short_id,
+ dashboardId,
+ dashboards: insight.dashboards,
+ dashboard_tiles: insight.dashboard_tiles,
+ }
+ const { copyToDestinations } = useValues(dashboardWidgetMenusLogic(dashboardWidgetMenusLogicProps))
const { copyImage } = useActions(captureImageLogic)
const { isCapturing: isCapturingImage } = useValues(captureImageLogic)
const { updateInsightDirect } = useActions(insightsModel)
@@ -287,15 +286,7 @@ export function InsightMeta({
const canShowCopyToDashboardTile = showCompactTile && !!copyToDashboard && canViewInsight
const hasDashboardPlacementActions = canShowCopyToDashboardTile || !!moveToDashboard || !!removeFromDashboard
- // For dashboard-specific actions (remove from dashboard, change tile color), check dashboard permissions
- const currentDashboard = dashboardId ? nameSortedDashboards.find((d) => d.id === dashboardId) : null
- const canEditDashboard = currentDashboard?.user_access_level
- ? accessLevelSatisfied(
- AccessControlResourceType.Dashboard,
- currentDashboard.user_access_level,
- AccessControlLevel.Editor
- )
- : true
+ const canEditCurrentDashboard = canEditDashboard ?? !dashboardId
// Feedback buttons for Customer Analytics
const feedbackButtons =
@@ -568,7 +559,7 @@ export function InsightMeta({
/>
)}
- {canShowCopyToDashboardTile && !canEditDashboard && (
+ {canShowCopyToDashboardTile && !canEditCurrentDashboard && (
<>
<LemonDivider />
<h5 className="mx-2 my-1">Dashboard</h5>
@@ -580,7 +571,7 @@ export function InsightMeta({
)}
{/* Dashboard related */}
- {canEditDashboard && (
+ {canEditCurrentDashboard && (
<>
<LemonDivider />
{showCompactTile && toggleShowDescription && !!insight.description && (
diff --git a/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.ts b/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.ts
index 57aa07f358e6..7feb3ca35b49 100644
--- a/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.ts
+++ b/frontend/src/lib/components/Cards/InsightCard/dashboardWidgetMenusLogic.test.ts
@@ -48,7 +48,6 @@ describe('dashboardWidgetMenusLogic', () => {
dashboard_tiles: [{ id: 10, dashboard_id: 1 }],
})
logic.mount()
-
await expectLogic(logic).toMatchValues({
copyToDestinations: [
{
@@ -78,7 +77,6 @@ describe('dashboardWidgetMenusLogic', () => {
dashboard_tiles: [],
})
logic.mount()
-
await expectLogic(logic).toMatchValues({
copyToDestinations: [
{
diff --git a/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.ts b/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.ts
index 63f8f19e6f2f..31cd0d811f36 100644
--- a/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.ts
+++ b/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.ts
@@ -38,6 +38,9 @@ export interface sceneDashboardChoiceModalLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface sceneDashboardChoiceModalLogicActions {
+ loadDashboardsIfNeeded: () => {
+ value: true
+ } // dashboardsModel
updateCurrentTeam: (payload: Partial<TeamType>) => Partial<TeamType> // teamLogic
setUserScenePersonalisation: (
scene: DashboardCompatibleScenes,
@@ -84,7 +87,14 @@ export const sceneDashboardChoiceModalLogic = kea<sceneDashboardChoiceModalLogic
key((props) => `${props.scene}`),
connect(() => ({
logic: [eventUsageLogic],
- actions: [teamLogic, ['updateCurrentTeam'], userLogic, ['setUserScenePersonalisation']],
+ actions: [
+ teamLogic,
+ ['updateCurrentTeam'],
+ userLogic,
+ ['setUserScenePersonalisation'],
+ dashboardsModel,
+ ['loadDashboardsIfNeeded'],
+ ],
values: [teamLogic, ['currentTeam'], userLogic, ['user'], dashboardsModel, ['nameSortedDashboards']],
})),
actions({
@@ -154,6 +164,7 @@ export const sceneDashboardChoiceModalLogic = kea<sceneDashboardChoiceModalLogic
}
},
showSceneDashboardChoiceModal: async () => {
+ actions.loadDashboardsIfNeeded()
if (props.scene === Scene.ProjectHomepage) {
posthog.capture('primary dashboard modal opened')
} else {
diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
index 7d550fbe4095..65c99c7d6da0 100644
--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
@@ -17,6 +17,7 @@ import { dataWarehouseSettingsSceneLogic } from 'scenes/data-warehouse/settings/
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
import { useMocks } from '~/mocks/jest'
import { Mocks } from '~/mocks/utils'
+import { dashboardsModel } from '~/models/dashboardsModel'
import { initKeaTests } from '~/test/init'
import { mockEventDefinitions, mockEventPropertyDefinitions } from '~/test/mocks'
import { AppContext, PropertyDefinition, PropertyFilterType, PropertyOperator, PropertyType } from '~/types'
@@ -101,6 +102,33 @@ describe('infiniteListLogic', () => {
return logicWithProps
}
+ it('shows loading while the dashboard list loads', async () => {
+ let completeDashboardLoad!: () => void
+ const dashboardLoad = new Promise<void>((resolve) => {
+ completeDashboardLoad = resolve
+ })
+ useMocks({
+ get: {
+ '/api/environments/:team/dashboards/': async () => {
+ await dashboardLoad
+ return [200, { count: 0, next: null, previous: null, results: [] }]
+ },
+ },
+ })
+
+ dashboardsModel.mount()
+ const dashboardsList = logicWith({
+ listGroupType: TaxonomicFilterGroupType.Dashboards,
+ taxonomicGroupTypes: [TaxonomicFilterGroupType.Dashboards],
+ })
+
+ expect(dashboardsList.values.showLoadingState).toBe(true)
+ expect(dashboardsList.values.showEmptyState).toBe(false)
+
+ completeDashboardLoad()
+ await expectLogic(dashboardsModel).toDispatchActions(['loadDashboardsSuccess'])
+ })
+
it.each([
{ state: 'initial request pending', initialCompleted: false, previousSearchPending: false, clear: false },
{ state: 'initial request completed', initialCompleted: true, previousSearchPending: false, clear: false },
diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
index dbb2f3ea42fa..176720e3d0be 100644
--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.ts
@@ -68,6 +68,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { createFuse } from 'lib/utils/fuseSearch'
import { mapGroupQueryResponse } from 'lib/utils/groups'
+import { dashboardsModel } from '~/models/dashboardsModel'
import { getCoreFilterDefinition } from '~/taxonomy/helpers'
import { CohortType, EventDefinition, GroupTypeIndex, PropertyType } from '~/types'
@@ -355,6 +356,9 @@ export interface infiniteListLogicValues {
// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface infiniteListLogicActions {
+ loadDashboardsIfNeeded: () => {
+ value: true
+ } // dashboardsModel
infiniteListResultsReceived: (
groupType: TaxonomicFilterGroupType,
results: ListStorage
@@ -586,7 +590,7 @@ export interface infiniteListLogicMeta {
) => boolean
allowNonCapturedEvents: (arg: any) => boolean
isLocalDataLoading: (arg: any) => boolean
- isLoading: (remoteItemsLoading: boolean) => boolean
+ isLoading: (remoteItemsLoading: boolean, isLocalDataLoading: boolean) => boolean
group: (
listGroupType: TaxonomicFilterGroupType,
taxonomicGroups: TaxonomicFilterGroup[]
@@ -847,6 +851,11 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
['setSearchQuery', 'setActiveTab', 'selectItem', 'infiniteListResultsReceived', 'setIncludeStaleEvents'],
],
})),
+ connect((props: InfiniteListLogicProps) =>
+ props.listGroupType === TaxonomicFilterGroupType.Dashboards
+ ? { actions: [dashboardsModel, ['loadDashboardsIfNeeded']] }
+ : {}
+ ),
actions({
selectSelected: true,
moveUp: true,
@@ -1250,7 +1259,10 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
],
(isLocalDataLoading: boolean) => isLocalDataLoading,
],
- isLoading: [(s) => [s.remoteItemsLoading], (remoteItemsLoading: boolean) => remoteItemsLoading],
+ isLoading: [
+ (s) => [s.remoteItemsLoading, s.isLocalDataLoading],
+ (remoteItemsLoading: boolean, isLocalDataLoading: boolean) => remoteItemsLoading || isLocalDataLoading,
+ ],
group: [
(s) => [s.listGroupType, s.taxonomicGroups],
(
@@ -2378,6 +2390,10 @@ export const infiniteListLogic = kea<infiniteListLogicType>([
actions.setIndex(results.findIndex((r) => group?.getValue?.(r) === value))
}
+ if (props.listGroupType === TaxonomicFilterGroupType.Dashboards) {
+ actions.loadDashboardsIfNeeded()
+ }
+
actions.reconcilePinnedRowState()
// Clean up all cache timers to prevent memory leaks. Clearing only the timers would
diff --git a/frontend/src/models/dashboardsModel.test.ts b/frontend/src/models/dashboardsModel.test.ts
index fc045614e73a..234a799a4c8c 100644
--- a/frontend/src/models/dashboardsModel.test.ts
+++ b/frontend/src/models/dashboardsModel.test.ts
@@ -101,6 +101,17 @@ describe('the dashboards model', () => {
logic.mount()
})
+ it('does not load dashboards until a consumer requests them', () => {
+ expect(logic.values.pagedDashboards).toBeNull()
+ expect(logic.values.pagedDashboardsLoading).toBe(false)
+ })
+
+ it('loads dashboards when a consumer requests them', async () => {
+ await expectLogic(logic, () => {
+ logic.actions.loadDashboardsIfNeeded()
+ }).toDispatchActions(['loadDashboardsSuccess'])
+ })
+
describe('sorting dashboards', () => {
it('can sort dashboards correctly', async () => {
await expectLogic(logic, () => {
diff --git a/frontend/src/models/dashboardsModel.tsx b/frontend/src/models/dashboardsModel.tsx
index 3b227ff2300d..3c9a4a515794 100644
--- a/frontend/src/models/dashboardsModel.tsx
+++ b/frontend/src/models/dashboardsModel.tsx
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router } from 'kea-router'
@@ -703,6 +703,11 @@ export const dashboardsModel = kea<dashboardsModelType>([
],
})),
listeners(({ actions, values }) => ({
+ loadDashboardsIfNeeded: () => {
+ if (!values.pagingDashboardsCompleted && !values.pagedDashboardsLoading) {
+ actions.loadDashboards()
+ }
+ },
loadDashboardsSuccess: ({ pagedDashboards }) => {
if (pagedDashboards?.next) {
actions.loadDashboards(pagedDashboards.next)
@@ -767,9 +772,6 @@ export const dashboardsModel = kea<dashboardsModelType>([
)
},
})),
- afterMount(({ actions }) => {
- actions.loadDashboards()
- }),
permanentlyMount(),
])
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index d24b492b41b9..fe80f4723992 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -89,6 +89,7 @@ jest.mock('lib/components/Cards/InsightCard', () => ({
tile: { id: number }
showResizeHandles: boolean
apiErrored?: boolean
+ canEditDashboard?: boolean
queryId?: string
apiError?: Error & {
status?: number
@@ -106,6 +107,7 @@ jest.mock('lib/components/Cards/InsightCard', () => ({
data-tile-id={String(tile.id)}
data-show-resize-handles={String(showResizeHandles)}
data-api-errored={apiErrored ? 'true' : undefined}
+ data-can-edit-dashboard={props.canEditDashboard === false ? 'false' : undefined}
data-api-error-status={apiError?.status}
data-api-error-detail={apiError?.detail ?? undefined}
data-api-error-code={apiError?.code ?? undefined}
@@ -300,6 +302,10 @@ describe('DashboardItems', () => {
'data-show-resize-handles',
'false'
)
+ expect(container.querySelector('[data-attr="insight-card"]')).toHaveAttribute(
+ 'data-can-edit-dashboard',
+ 'false'
+ )
})
it.each([
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 3498da642eb2..4b20e4357fce 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -502,6 +502,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const commonTileProps = {
dashboardId: dashboard?.id,
+ canEditDashboard,
showResizeHandles,
canEnterEditModeFromEdge,
onEnterEditModeFromEdge,
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index b0d0d16ccd3a..bfa2f7190964 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -97,7 +97,9 @@ describe('dashboardsLogic', () => {
initKeaTests()
dashboardsModel.mount()
- await expectLogic(dashboardsModel).toDispatchActions(['loadDashboardsSuccess'])
+ await expectLogic(dashboardsModel, () => dashboardsModel.actions.loadDashboardsIfNeeded()).toDispatchActions([
+ 'loadDashboardsSuccess',
+ ])
sceneLogic({ scenes }).mount()
logic = dashboardsLogic({ tabId: '1' })
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
index 5916745606b2..68d8c36eab17 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.ts
@@ -1,4 +1,4 @@
-import { MakeLogicType, actions, connect, kea, listeners, path, reducers, selectors } from 'kea'
+import { MakeLogicType, actions, afterMount, connect, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { router, urlToAction } from 'kea-router'
@@ -730,4 +730,7 @@ export const dashboardsLogic = kea<dashboardsLogicType>([
}
},
})),
+ afterMount(() => {
+ dashboardsModel.actions.loadDashboardsIfNeeded()
+ }),
])
diff --git a/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx b/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx
index 3bd97214134b..f33a0edcdafb 100644
--- a/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx
+++ b/frontend/src/scenes/dashboard/items/DashboardButtonTileItem.tsx
@@ -38,14 +38,13 @@ function DashboardButtonTileItemInternal(
ref: React.ForwardedRef<HTMLDivElement>
): JSX.Element {
const buttonId = tile.button_tile?.id
- const { copyToDestinations } = useValues(
- dashboardWidgetMenusLogic({
- instanceKey: buttonId != null ? `button-${buttonId}` : `button-tile-${tile.id}`,
- dashboardId,
- dashboards: undefined,
- dashboard_tiles: tile.button_tile?.dashboard_tiles,
- })
- )
+ const dashboardWidgetMenusLogicProps = {
+ instanceKey: buttonId != null ? `button-${buttonId}` : `button-tile-${tile.id}`,
+ dashboardId,
+ dashboards: undefined,
+ dashboard_tiles: tile.button_tile?.dashboard_tiles,
+ }
+ const { copyToDestinations } = useValues(dashboardWidgetMenusLogic(dashboardWidgetMenusLogicProps))
return (
<ButtonTileCard