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 WidgetCard shell and dashboard widget UI glue (7/11) (#60523)

Matt Pua550ea3fae04f
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index cbf794c49c4a..87ae41526557 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -129,13 +129,13 @@ snapshots:
components-bulkupdatetagsbutton--replace-mode--light:
hash: v1.k794b7964.379cf8e29d15c49e9dced0e75d7dc6c25936204286649beef587801633564121.wYCp32fZHjbDeJb5u_l7qYy823rCGHUMZIBfMRYfMYY
components-cards-button-tile-card--template--dark:
- hash: v1.k794b7964.ea8f8f9e593a467027450a8ba4241c3b3160387a41dcbd2a7fa6fc3e3299fffa.AE40xjOLMiJfje4e2EC8Mpc00oXcDCL9gVW8xqGnblQ
+ hash: v1.k794b7964.5c00d2f9e77c78cdd552d6cf96dbcb8b1d7dbe75e17fd082b5b2b17bf71e28ad.iquYtANfIhPoSSL7HkZc7KSDBN7CfaFVah3qN_oxYiA
components-cards-button-tile-card--template--light:
- hash: v1.k794b7964.a86778e36f69e58b94ef945c637882db2b137f3808164d03835c577052641233.U7ID1Y5rA8T0ZryMom2Ptil_3cVKGJbD40HmY9SwXMk
+ hash: v1.k794b7964.77467b6090958453bd5c0ad1fce49642555a49287f615c2e3220deb5cb298818.9oqgdb2D2Lsjcyn1K0ATwch_vZvW_yB2Kinp9oC-Acc
components-cards-button-tile-card--transparent-background--dark:
- hash: v1.k794b7964.eefb6cdbc10cbb32b240e36a8d4826e7e3d7dde9a296965fa1486831ce8154f0.lUTzIoRhG3FOoss5EOZV6yYxHhRBV6imS4QwgDrQXBo
+ hash: v1.k794b7964.b204c14d32246500e5ecc5839821b1741e847904ebb44ee59f58bf7e71d0cebd.6PNT0tZSsBkTJQhKN4OOYBp8vrAxMvBAd3gAHqwOsyc
components-cards-button-tile-card--transparent-background--light:
- hash: v1.k794b7964.78fcc9af23a4701854c872c3d037ed0f353477edd993e574e1965028cad581be.Ldlwd87dJe5vtaLEEDZ4jlWjtBk95fOWHIULkXr2O-4
+ hash: v1.k794b7964.510d6d3ba8844dec15ad98f4f076b5208153cb4738681d78cc28c5fc3eee5ef2.FSi57cM2bmg0pzgUKTQ1ExBBVs3A87RbUL2GE_cQ7Qg
components-cards-button-tile-card--with-more-button--dark:
hash: v1.k794b7964.d1b9018f28a80e9d5f20ad0b4afbb62ad4b34065fc140074e830d9a70206e283.HC7o7m5L0cWof-9FGL8kZZpoXfHj2-WKiOx89OR2rIQ
components-cards-button-tile-card--with-more-button--light:
@@ -1452,6 +1452,26 @@ snapshots:
hash: v1.k794b7964.ec79c434bdd0a29af24dbee3162d74ac2ac927b1431b29eef0246ef0cd9b5820.BUKk_-UGOgJ-1jJ1Yw5FnL1_yp3UP0y5G7wizjZ2aaE
components-verticalnesteddnd--base--light:
hash: v1.k794b7964.253572e7c878adb761595b38b07c93ba529e1bf165d0e67fe79550ef784dcf5d.um0bjxs1ERf6_rMKphvKrO7fE5D7cV_HaikHm5fGsM8
+ dashboards-dashboard-widgets-widgetcard--dashboard-tile-populated--dark:
+ hash: v1.k794b7964.44c19632537a43879cd2fb8196905bf21e18e784b907a6851aa9d49ec7f45ce7.WRJJJH-g5HOJnILNLSsqi-nP04K6dA4KQiUwxLxbiVk
+ dashboards-dashboard-widgets-widgetcard--dashboard-tile-populated--light:
+ hash: v1.k794b7964.6b9d967ad5f62013c74577e0158a80f912db8256aa4f25992bdfe5fd39559bcd.BU8LEUwt0lMAxQAzNv0VGt1tRGzfyA7MgitIq-_bgug
+ dashboards-dashboard-widgets-widgetcard--empty-body-message--dark:
+ hash: v1.k794b7964.fb5502d577f533bf872e1766c23226cbcda80bdbd74452085c80b66f47ba8321.sKixzO_rRkbQr_iwW7eFXB3wacyz3kkk3RTB8lerUp4
+ dashboards-dashboard-widgets-widgetcard--empty-body-message--light:
+ hash: v1.k794b7964.dd73195c1eb7a8b81367b736af0f9f7eb16f6e74ce11d11915484c5c714cad5e.CZI84_ZdLXfmzwpIaVZdmj8bCeSFgmOHkdg3v6z4IH0
+ dashboards-dashboard-widgets-widgetcard--locked--dark:
+ hash: v1.k794b7964.5dba098f0e676516512a97f6783aa7db0d1d690ea655e38174f2692c50c9c7c6.3ngw_BbiP8-FwkNjGia7N7qct9mTs84lu-8KlPeFrVc
+ dashboards-dashboard-widgets-widgetcard--locked--light:
+ hash: v1.k794b7964.e9c99461c55467ec079f53a30b3be0820f65b3636a075d25ad7cccb3c4703d11.U8h7teCTfeWZ6pXgL969YSqyHClaG291LZQLex3ivHQ
+ dashboards-dashboard-widgets-widgetcard--setup-unavailable-pattern--dark:
+ hash: v1.k794b7964.fe2b2039b1f01836e7f4e9e85e7baddfc5436046d6869608d8b87c7a5341f41f.rRdGKkZtuub5fWGjW3NGhy8QwZJQZTHHHt_sSmYaPvU
+ dashboards-dashboard-widgets-widgetcard--setup-unavailable-pattern--light:
+ hash: v1.k794b7964.96a03e3e594bed406ba87a4109ec787c616a5d7e1cf14e87ab9b8ceb3e5d84b1.vkVUiK1Ff2TvfT2TOWlst18v9mwlJXRzVdCqUCt9Uzc
+ dashboards-dashboard-widgets-widgetcard--simple-header-loading--dark:
+ hash: v1.k794b7964.5b157e65b047cb3de5ed4b5220cfda9064ab2cee2afcf19ebfbb3862b7d8a87d.NpCsyJrSQbrbk2i9pO2oRpNTSLZFtY6hPfz122QFKbw
+ dashboards-dashboard-widgets-widgetcard--simple-header-loading--light:
+ hash: v1.k794b7964.5c626cb714f69b201185730439abe84f00d1045d1439db992975dcba34f38a1c.w0dHtsZ71gku0WWyG6xzC9TMDC2WJLN3v83xuBv26zA
data-warehouse-query-history-modal--empty--dark:
hash: v1.k794b7964.4c38283dea0ebc9b3e3e0aa03a05f6e4153bfe3550336ead008a187a43ddab4c.4ArpfVpkJGTdOVoU2PbGNjGH1Kzbq84osask8eFk-BA
data-warehouse-query-history-modal--empty--light:
@@ -4913,7 +4933,7 @@ snapshots:
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--dark:
hash: v1.k794b7964.293297b83994468984576e5c15fa2cbbb2c4c0a7a8234959b9deba539efa383b.O7SwG4Drfr3z02hcLNC1LsLsGWddouhybBp4xZaUE-A
scenes-app-insights-funnels--funnel-left-to-right-edit-viewports--wide--light:
- hash: v1.k794b7964.c63132bb5b13cbe97938ebdb2e59e320ebc338bd12b2d3bfd6af81e56270650a.KSiw8WpvjWXIDh87ExL4cPnopVJlTXvzU8N8ruh6Hi8
+ hash: v1.k794b7964.6c391cbc05b64230fbd8defdbb960b131fd433409817497873fb9ffc705cd360.EIwByuofuT77yP259A9ffqfjSFwW9MrUDOvsZNA_aZM
scenes-app-insights-funnels--funnel-time-to-convert--dark:
hash: v1.k794b7964.d64808d2bfc36017f89b57feeaa373e20188738a622801207fa1beb59d02fdd9.cFuKF_Ow887Z3X3BoNhtTvkUWY2vips9HDBe-B02eQE
scenes-app-insights-funnels--funnel-time-to-convert--light:
diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.stories.tsx b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.stories.tsx
index b3452b921ed7..ad9972428967 100644
--- a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.stories.tsx
+++ b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.stories.tsx
@@ -1,9 +1,14 @@
+import '~/scenes/dashboard/DashboardItems.scss'
+
import type { Meta, StoryObj } from '@storybook/react'
import { DashboardPlacement, DashboardTile, InsightColor, QueryBasedInsightModel } from '~/types'
import { ButtonTileCard } from './ButtonTileCard'
+const gridItemStoryClassName =
+ 'relative react-grid-item react-draggable cssTransforms react-resizable min-h-60 min-w-[15rem]'
+
const meta: Meta = {
title: 'Components/Cards/Button Tile Card',
component: ButtonTileCard,
@@ -61,9 +66,10 @@ export const Template: Story = {
placement={DashboardPlacement.Dashboard}
/>
</div>
- <div className="relative w-fit">
+ <div>
<h5>With resize handles</h5>
<ButtonTileCard
+ className={gridItemStoryClassName}
showResizeHandles={true}
buttonTile={makeButtonTile('https://posthog.com', 'Visit PostHog')}
placement={DashboardPlacement.Dashboard}
@@ -87,9 +93,10 @@ export const TransparentBackground: Story = {
placement={DashboardPlacement.Dashboard}
/>
</div>
- <div className="relative w-fit">
+ <div>
<h5>Transparent background (edit mode — dashed border)</h5>
<ButtonTileCard
+ className={gridItemStoryClassName}
showResizeHandles={true}
buttonTile={makeButtonTile('https://posthog.com', 'Visit PostHog', {
transparentBackground: true,
diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx
index aa9660d4c0d1..189ada36146c 100644
--- a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx
+++ b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx
@@ -76,7 +76,7 @@ function ButtonTileCardInternal(
return (
<div
className={clsx(
- 'ButtonTileCard rounded flex flex-col',
+ 'DashboardTileCard ButtonTileCard rounded flex flex-col',
!isTransparent && 'bg-surface-primary border',
isTransparent && showResizeHandles && 'border border-dashed border-border',
className
diff --git a/frontend/src/lib/components/Cards/CardMeta.scss b/frontend/src/lib/components/Cards/CardMeta.scss
index 890cdfc897f3..f2bcb8506d8c 100644
--- a/frontend/src/lib/components/Cards/CardMeta.scss
+++ b/frontend/src/lib/components/Cards/CardMeta.scss
@@ -1,91 +1,5 @@
-.TextCard,
-.InsightCard,
-.ButtonTileCard {
- .handle {
- position: absolute;
- z-index: var(--z-raised);
- display: flex;
- align-items: flex-end;
- justify-content: center;
- width: 100%;
- height: 100%;
- pointer-events: none;
-
- &.horizontal {
- svg {
- transform: rotate(90deg) translateX(0.75rem);
- }
-
- &.top {
- align-items: flex-start;
-
- svg {
- transform: rotate(90deg) translateX(-0.75rem);
- }
- }
- }
-
- &.vertical {
- flex-direction: column;
-
- &.right {
- align-items: flex-end;
- justify-content: center;
-
- svg {
- transform: translateX(0.5rem);
- }
- }
-
- &.left {
- align-items: flex-start;
- justify-content: center;
-
- svg {
- transform: translateX(-0.5rem);
- }
- }
- }
-
- &.corner {
- align-items: flex-end;
-
- // default bottom-right positioning
- justify-content: flex-end;
-
- svg {
- transform: translate(0.5rem, 0.5rem);
- }
-
- /* Mirror the corner handle graphic while keeping the same anchor point */
- &.bottom-left {
- align-items: flex-end;
- justify-content: flex-start;
-
- svg {
- transform: translate(-0.5rem, 0.5rem) rotateY(180deg);
- }
- }
-
- &.top-right {
- align-items: flex-start;
- justify-content: flex-end;
-
- svg {
- transform: translate(0.5rem, -0.5rem) rotateX(180deg);
- }
- }
-
- &.top-left {
- align-items: flex-start;
- justify-content: flex-start;
-
- svg {
- transform: translate(-0.5rem, -0.5rem) rotateX(180deg) rotateY(180deg);
- }
- }
- }
- }
+.DashboardTileCard {
+ min-height: 0;
}
.CardMeta {
@@ -121,6 +35,7 @@
.CardMeta__primary {
display: flex;
width: 100%;
+ min-width: 0;
padding: 1rem;
}
@@ -203,7 +118,8 @@
@container (min-width: 14rem) {
.CardMeta__heading {
- display: block;
+ // Let the top-heading row participate in CardMeta__top flex layout without an extra wrapper box.
+ display: contents;
}
}
}
@@ -255,6 +171,7 @@
flex-direction: column;
align-items: flex-start;
width: 100%;
+ min-width: 0;
height: fit-content;
min-height: 2rem;
diff --git a/frontend/src/lib/components/Cards/CardMeta.tsx b/frontend/src/lib/components/Cards/CardMeta.tsx
index 720119a24ff4..9fd6aed5b9f7 100644
--- a/frontend/src/lib/components/Cards/CardMeta.tsx
+++ b/frontend/src/lib/components/Cards/CardMeta.tsx
@@ -123,7 +123,7 @@ export function CardMeta({
{compact ? (
<>
<div className="CardMeta__top">
- <h5 className="CardMeta__heading">{topHeading}</h5>
+ <div className="CardMeta__heading">{topHeading}</div>
<div className="CardMeta__controls">
{showEditingControls &&
(moreTooltip ? (
diff --git a/frontend/src/lib/components/Cards/CardTopHeadingRow.tsx b/frontend/src/lib/components/Cards/CardTopHeadingRow.tsx
new file mode 100644
index 000000000000..524a6191ba39
--- /dev/null
+++ b/frontend/src/lib/components/Cards/CardTopHeadingRow.tsx
@@ -0,0 +1,36 @@
+import { Tooltip } from 'lib/lemon-ui/Tooltip'
+
+export function CardTopHeadingRow({
+ typeLabel,
+ typeTitle,
+ showTypeLabel = true,
+ dateText,
+ dateTooltip,
+ children,
+}: {
+ typeLabel?: string | null
+ typeTitle?: string
+ showTypeLabel?: boolean
+ dateText?: string | null
+ dateTooltip?: string | null
+ children?: React.ReactNode
+}): JSX.Element {
+ return (
+ <div className="flex items-center gap-1">
+ {showTypeLabel && typeLabel ? <span title={typeTitle ?? typeLabel}>{typeLabel}</span> : null}
+ {dateText ? (
+ <>
+ {showTypeLabel && typeLabel ? <span>•</span> : null}
+ {dateTooltip ? (
+ <Tooltip title={dateTooltip}>
+ <span className="whitespace-nowrap">{dateText}</span>
+ </Tooltip>
+ ) : (
+ <span className="whitespace-nowrap">{dateText}</span>
+ )}
+ </>
+ ) : null}
+ {children}
+ </div>
+ )
+}
diff --git a/frontend/src/lib/components/Cards/InsightCard/DashboardTileRefreshDataButton.tsx b/frontend/src/lib/components/Cards/InsightCard/DashboardTileRefreshDataButton.tsx
new file mode 100644
index 000000000000..a50d471f7d0e
--- /dev/null
+++ b/frontend/src/lib/components/Cards/InsightCard/DashboardTileRefreshDataButton.tsx
@@ -0,0 +1,36 @@
+import { TZLabel } from 'lib/components/TZLabel'
+import { dayjs, type Dayjs } from 'lib/dayjs'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+
+export function DashboardTileRefreshDataButton({
+ onRefresh,
+ disabledReason,
+ lastRefresh,
+}: {
+ onRefresh: () => void
+ disabledReason?: string | null
+ lastRefresh?: string | number | Dayjs | null
+}): JSX.Element {
+ const lastRefreshTime = lastRefresh != null ? dayjs(lastRefresh) : null
+
+ return (
+ <LemonButton
+ onClick={onRefresh}
+ disabledReason={disabledReason}
+ fullWidth
+ data-attr="dashboard-tile-refresh-data"
+ >
+ {lastRefreshTime ? (
+ <div className="block my-1">
+ Refresh data
+ <p className="text-xs text-muted mt-0.5">
+ Last computed{' '}
+ <TZLabel time={lastRefreshTime} noStyles className="whitespace-nowrap border-dotted border-b" />
+ </p>
+ </div>
+ ) : (
+ <>Refresh data</>
+ )}
+ </LemonButton>
+ )
+}
diff --git a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
index 8ee92337e1c2..591b25dc9437 100644
--- a/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/InsightCard.tsx
@@ -242,7 +242,7 @@ function InsightCardInternal(
return (
<div
className={clsx(
- 'InsightCard border',
+ 'DashboardTileCard InsightCard border',
highlighted && 'InsightCard--highlighted',
areDetailsShown && 'InsightCard--details-shown',
className
@@ -305,12 +305,12 @@ function InsightCardInternal(
</div>
) : null}
</BindLogic>
- {showResizeHandles && <DashboardResizeHandles />}
- {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
- <EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
- )}
- {children /* Extras injected by the parent layout (not ReactGridLayout resize handles) */}
</ErrorBoundary>
+ {showResizeHandles && <DashboardResizeHandles />}
+ {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
+ <EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
+ )}
+ {children /* RGL react-resizable-handle nodes injected by react-grid-layout */}
</div>
)
}
diff --git a/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx b/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx
index 358f2d04c70b..c21d7d42e46b 100644
--- a/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx
+++ b/frontend/src/lib/components/Cards/InsightCard/TopHeading.tsx
@@ -1,4 +1,4 @@
-import { Tooltip } from 'lib/lemon-ui/Tooltip'
+import { CardTopHeadingRow } from 'lib/components/Cards/CardTopHeadingRow'
import { dateFilterToText } from 'lib/utils'
import { alignResolvedDateRangeToInterval, formatResolvedDateRange } from 'lib/utils/dateTimeUtils'
import { InsightTypeMetadata, QUERY_TYPES_METADATA } from 'scenes/saved-insights/SavedInsights'
@@ -72,22 +72,15 @@ export function TopHeading({
const resolvedDateTooltip = formatResolvedDateRange(alignResolvedDateRangeToInterval(resolvedDateRange, interval))
return (
- <div className="flex items-center gap-1">
- {showInsightType && <span title={insightType?.description}>{insightType?.name}</span>}
- {dateText ? (
- <>
- {showInsightType && <span>•</span>}
- {resolvedDateTooltip ? (
- <Tooltip title={resolvedDateTooltip}>
- <span className="whitespace-nowrap">{dateText}</span>
- </Tooltip>
- ) : (
- <span className="whitespace-nowrap">{dateText}</span>
- )}
- </>
- ) : null}
+ <CardTopHeadingRow
+ typeLabel={insightType?.name}
+ typeTitle={insightType?.description}
+ showTypeLabel={showInsightType}
+ dateText={dateText}
+ dateTooltip={resolvedDateTooltip}
+ >
{lastRefresh ? <InsightFreshness lastRefresh={lastRefresh} /> : null}
{hasTileOverrides ? <TileOverridesWarning /> : null}
- </div>
+ </CardTopHeadingRow>
)
}
diff --git a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
index c580f948a291..7b4b769e30c8 100644
--- a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
+++ b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
@@ -4,6 +4,7 @@ import { EditorContent } from '@tiptap/react'
import clsx from 'clsx'
import React, { memo, useEffect, useMemo } from 'react'
+import 'lib/components/Cards/CardMeta.scss'
import 'lib/components/MarkdownEditor/shared/RichMarkdownEditor.scss'
import { Resizeable } from 'lib/components/Cards/CardMeta'
import { DashboardResizeHandles } from 'lib/components/Cards/handles'
@@ -98,7 +99,7 @@ function TextCardInternal(
return (
<div
className={clsx(
- 'TextCard rounded flex flex-col',
+ 'DashboardTileCard TextCard rounded flex flex-col',
!isTransparent && 'bg-surface-primary border',
isTransparent && showResizeHandles && 'border border-dashed border-border',
className
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsx
index e6d57c94eef2..17decafaa8de 100644
--- a/frontend/src/lib/constants.tsx
+++ b/frontend/src/lib/constants.tsx
@@ -260,6 +260,7 @@ export const FEATURE_FLAGS = {
DASHBOARD_LAYOUT_DISCARD_PROMPT: 'dashboard-layout-discard-prompt', // owner: @cory.s #team-analytics-platform
DASHBOARD_QUICK_FILTERS_EXPERIMENT: 'dashboard-quick-filters-experiment', // owner: @vdekrijger #team-product-analytics multivariate=control,test
DASHBOARD_TEMPLATE_CHOOSER_EXPERIMENT: 'dashboard-template-chooser-experiment', // owner: @mattp #team-analytics-platform multivariate=control,simple,new
+ DASHBOARD_WIDGETS: 'dashboard-widgets', // owner: @mattp #team-analytics-platform
DATA_MODELING_BACKEND_V2: 'data-modeling-backend-v2', // owner: #team-data-modeling
DATA_MODELING_MULTI_DAG: 'data-modeling-multi-dag', // owner: #team-data-modeling
DATA_MODELING_TAB: 'data-modeling-tab', // owner: #team-data-modeling
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index ec56a0f8d258..1e6c8eb66478 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -1240,6 +1240,12 @@ export const eventUsageLogic = kea<eventUsageLogicType>([
properties[key] += 1
}
properties.sample_items_count += item.insight.is_sample ? 1 : 0
+ } else if (item.widget) {
+ if (!properties['widget_tiles_count']) {
+ properties['widget_tiles_count'] = 1
+ } else {
+ properties['widget_tiles_count'] += 1
+ }
} else {
if (!properties['text_tiles_count']) {
properties['text_tiles_count'] = 1
diff --git a/frontend/src/models/notebooksModel.ts b/frontend/src/models/notebooksModel.ts
index 35a7f0d8cf78..5836296d4475 100644
--- a/frontend/src/models/notebooksModel.ts
+++ b/frontend/src/models/notebooksModel.ts
@@ -175,6 +175,8 @@ export const notebooksModel = kea<notebooksModelType>([
listeners(({ asyncActions }) => ({
createNotebookFromDashboard: async ({ dashboard }) => {
+ // TODO(widgets): Dashboard widget tiles are intentionally skipped: notebook query nodes only support
+ // insight-backed HogQL queries today, not run_widgets widget types/config.
const queries = dashboard.tiles.reduce(
(acc, tile) => {
if (!tile.insight) {
diff --git a/frontend/src/queries/nodes/InsightViz/utils.ts b/frontend/src/queries/nodes/InsightViz/utils.ts
index 7194e5f617d9..0799314c5c39 100644
--- a/frontend/src/queries/nodes/InsightViz/utils.ts
+++ b/frontend/src/queries/nodes/InsightViz/utils.ts
@@ -164,7 +164,7 @@ export const getDefaultQuery = (
/** Get a dashboard where eventual `filters` based tiles are converted to `query` based ones. */
export const getQueryBasedDashboard = (
- dashboard: DashboardType<InsightModel> | null
+ dashboard: DashboardType<InsightModel> | DashboardType<QueryBasedInsightModel> | null
): DashboardType<QueryBasedInsightModel> | null => {
if (dashboard == null) {
return null
diff --git a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
index 62d58d6ff9ba..3a1502a7e8a5 100644
--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
@@ -20,8 +20,8 @@ import { addInsightToDashboardLogic } from './addInsightToDashboardModalLogic'
import { DashboardLoadAction, dashboardLogic } from './dashboardLogic'
export function DashboardAddTileButton(): JSX.Element | null {
- const { dashboard } = useValues(dashboardLogic)
- const { loadDashboard } = useActions(dashboardLogic)
+ const { dashboard, dashboardWidgetsEnabled } = useValues(dashboardLogic)
+ const { loadDashboard, setAddWidgetModalOpen } = useActions(dashboardLogic)
const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
const { push } = useActions(router)
@@ -71,6 +71,16 @@ export function DashboardAddTileButton(): JSX.Element | null {
onClick: () => push(urls.dashboardButtonTile(dashboard.id, 'new')),
'data-attr': 'dashboard-add-button-tile',
},
+ ...(dashboardWidgetsEnabled
+ ? [
+ {
+ label: 'Widget',
+ tag: 'new' as const,
+ onClick: () => setAddWidgetModalOpen(true),
+ 'data-attr': 'dashboard-add-widget',
+ },
+ ]
+ : []),
]}
>
<LemonButton type="primary" data-attr="dashboard-add-tile" size="small" icon={<IconPlusSmall />}>
diff --git a/frontend/src/scenes/dashboard/DashboardItems.scss b/frontend/src/scenes/dashboard/DashboardItems.scss
index 6b9a26d1cd24..6994ab55e95b 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.scss
+++ b/frontend/src/scenes/dashboard/DashboardItems.scss
@@ -35,12 +35,15 @@
will-change: width, height;
}
-.react-grid-item.react-draggable .CardMeta,
-.react-grid-item.react-draggable .TextCard__body,
-.react-grid-item.react-draggable .ButtonTileCard__body {
- // .CardMeta is the draggable handle of insight cards. Text/button cards are draggable as a whole
- cursor: grab;
- user-select: none; // Prevent accidental text selection while dragging
+.react-grid-item.react-draggable.DashboardTileCard {
+ .CardMeta,
+ .TextCard__body,
+ .ButtonTileCard__body,
+ .WidgetCard__header {
+ // CardMeta: insight + widget (dashboard_tile layout). Bodies: text/button tiles. Header: widget (simple layout).
+ cursor: grab;
+ user-select: none; // Prevent accidental text selection while dragging
+ }
}
.react-grid-item.react-draggable-dragging {
@@ -70,9 +73,98 @@
}
.react-grid-item {
+ box-sizing: border-box;
transition: all 100ms ease;
transition-property: left, top;
+ // Drop InsightCard's fixed 30rem so RGL's inline height is the only constraint.
+ &.DashboardTileCard.InsightCard {
+ height: unset;
+ }
+
+ // Decorative resize overlays: anchor to the grid cell, not an inner wrapper.
+ & > .handle {
+ position: absolute;
+ inset: 0;
+ z-index: var(--z-raised);
+ display: flex;
+ align-items: flex-end;
+ justify-content: center;
+ pointer-events: none;
+
+ &.horizontal {
+ svg {
+ transform: rotate(90deg) translateX(0.75rem);
+ }
+
+ &.top {
+ align-items: flex-start;
+
+ svg {
+ transform: rotate(90deg) translateX(-0.75rem);
+ }
+ }
+ }
+
+ &.vertical {
+ flex-direction: column;
+
+ &.right {
+ align-items: flex-end;
+ justify-content: center;
+
+ svg {
+ transform: translateX(0.5rem);
+ }
+ }
+
+ &.left {
+ align-items: flex-start;
+ justify-content: center;
+
+ svg {
+ transform: translateX(-0.5rem);
+ }
+ }
+ }
+
+ &.corner {
+ align-items: flex-end;
+ justify-content: flex-end;
+
+ svg {
+ transform: translate(0.5rem, 0.5rem);
+ }
+
+ &.bottom-left {
+ align-items: flex-end;
+ justify-content: flex-start;
+
+ svg {
+ transform: translate(-0.5rem, 0.5rem) rotateY(180deg);
+ }
+ }
+
+ &.top-right {
+ align-items: flex-start;
+ justify-content: flex-end;
+
+ svg {
+ transform: translate(0.5rem, -0.5rem) rotateX(180deg);
+ }
+ }
+
+ &.top-left {
+ align-items: flex-start;
+ justify-content: flex-start;
+
+ svg {
+ transform: translate(-0.5rem, -0.5rem) rotateX(180deg) rotateY(180deg);
+ }
+ }
+ }
+ }
+
& > .react-resizable-handle {
position: absolute;
right: -0.5rem;
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index 9be003b4993b..f6277807f612 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -134,6 +134,10 @@ jest.mock('react-grid-layout/extras', () => ({
),
}))
+jest.mock('@posthog/products-dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem', () => ({
+ DashboardWidgetItem: () => <div data-attr="widget-card" />,
+}))
+
const mockedUseValues = useValues as jest.Mock
const mockedUseActions = useActions as jest.Mock
@@ -190,6 +194,8 @@ describe('DashboardItems', () => {
removeTile: jest.fn(),
duplicateTile: jest.fn(),
refreshDashboardItem: jest.fn(),
+ refreshDashboardWidgets: jest.fn(),
+ updateWidgetTileMetadata: jest.fn(),
moveToDashboard: jest.fn(),
copyToDashboard: jest.fn(),
setTileOverride: jest.fn(),
@@ -223,4 +229,48 @@ describe('DashboardItems', () => {
const { container } = render(<DashboardItems />)
expect(container.firstChild).toMatchSnapshot()
})
+
+ it('hides widget tiles on public dashboards', () => {
+ const widgetTile = {
+ id: 2,
+ widget: { id: 1, widget_type: 'error_tracking_list', config: {} },
+ layouts: { sm: [{ i: '2', x: 0, y: 0, w: 6, h: 5 }] },
+ }
+
+ mockedUseValues.mockImplementation((logic) => {
+ if (logic === dashboardLogic) {
+ return {
+ dashboard: { id: 5 },
+ tiles: [widgetTile],
+ layouts: widgetTile.layouts,
+ dashboardMode: null,
+ placement: DashboardPlacement.Public,
+ isRefreshingQueued: () => false,
+ isRefreshing: () => false,
+ highlightedInsightId: null,
+ refreshStatus: {},
+ itemsLoading: false,
+ dashboardStreaming: false,
+ effectiveEditBarFilters: {},
+ effectiveDashboardVariableOverrides: {},
+ temporaryBreakdownColors: [],
+ dataColorThemeId: null,
+ canEditDashboard: false,
+ layoutZoom: 1,
+ dashboardWidgetsEnabled: true,
+ widgetResultsByTileId: {},
+ widgetRefreshStatus: {},
+ }
+ }
+
+ if (logic === dashboardsModel) {
+ return { nameSortedDashboards: [] }
+ }
+
+ return {}
+ })
+
+ const { queryByTestId } = render(<DashboardItems />)
+ expect(queryByTestId('widget-card')).not.toBeInTheDocument()
+ })
})
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 27807ca03fed..e6f89746f612 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -7,11 +7,14 @@ import { RefObject, useCallback, useEffect, useMemo, useRef, useState } from 're
import { Layout, Responsive as ReactGridLayout, useContainerWidth } from 'react-grid-layout'
import { GridBackground } from 'react-grid-layout/extras'
+import { DashboardWidgetItem } from '@posthog/products-dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem'
+import { getDashboardWidgetFetchDisplayError } from '@posthog/products-dashboards/frontend/widgets/constants'
+
import { InsightCard } from 'lib/components/Cards/InsightCard'
import { LemonBanner } from 'lib/lemon-ui/LemonBanner'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
-import { BREAKPOINTS, BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'
+import { BREAKPOINTS, BREAKPOINT_COLUMN_COUNTS, isWidgetTileVisibleOnPlacement } from 'scenes/dashboard/dashboardUtils'
import { useSurveyLinkedInsights } from 'scenes/surveys/hooks/useSurveyLinkedInsights'
import { getBestSurveyOpportunityFunnel } from 'scenes/surveys/utils/opportunityDetection'
import { urls } from 'scenes/urls'
@@ -48,6 +51,9 @@ export function DashboardItems(): JSX.Element {
temporaryBreakdownColors,
dataColorThemeId,
canEditDashboard,
+ dashboardWidgetsEnabled,
+ widgetResultsByTileId,
+ widgetRefreshStatus,
} = useValues(dashboardLogic)
const { layoutZoom = 1 } = useValues(dashboardLogic)
const {
@@ -58,6 +64,9 @@ export function DashboardItems(): JSX.Element {
removeTile,
duplicateTile,
refreshDashboardItem,
+ refreshDashboardWidgets,
+ updateWidgetTileMetadata,
+ updateWidgetTileConfig,
moveToDashboard,
copyToDashboard,
setTileOverride,
@@ -159,7 +168,7 @@ export function DashboardItems(): JSX.Element {
const dragConfig = useMemo(
() => ({
enabled: dashboardMode === DashboardMode.Edit && !isMobileView,
- handle: '.CardMeta,.TextCard__body,.ButtonTileCard__body',
+ handle: '.CardMeta,.TextCard__body,.ButtonTileCard__body,.WidgetCard__header,.drag-handle',
cancel: 'a,table,button,input,.Popover',
bounded: true,
}),
@@ -359,7 +368,7 @@ export function DashboardItems(): JSX.Element {
onDragStop={handleDragStop}
>
{tiles?.map((tile) => {
- const { insight, text, button_tile } = tile
+ const { insight, text, button_tile, widget } = tile
const smLayout = layouts['sm']?.find((l) => {
return l.i == tile.id.toString()
})
@@ -471,6 +480,41 @@ export function DashboardItems(): JSX.Element {
/>
)
}
+
+ if (widget && dashboardWidgetsEnabled && isWidgetTileVisibleOnPlacement(placement)) {
+ const runResult = widgetResultsByTileId[tile.id]
+ const refreshState = widgetRefreshStatus[tile.id]
+
+ return (
+ <DashboardWidgetItem
+ key={tile.id}
+ tile={tile}
+ placement={placement}
+ dashboardId={dashboard?.id}
+ result={runResult?.result}
+ error={getDashboardWidgetFetchDisplayError(
+ runResult?.error ?? refreshState?.error
+ )}
+ loading={!!refreshState?.loading}
+ lastFetchedAt={refreshState?.fetchedAt}
+ onRefresh={() =>
+ refreshDashboardWidgets({ tileIds: [tile.id], forceRefresh: true })
+ }
+ onUpdateConfig={(config) => updateWidgetTileConfig({ tile, config })}
+ onUpdateMetadata={(metadata) => updateWidgetTileMetadata({ tile, ...metadata })}
+ toggleShowDescription={() => toggleTileDescription(tile.id)}
+ onDuplicate={() => duplicateTile(tile)}
+ onRemove={commonTileProps.removeFromDashboard}
+ onMoveToDashboard={commonTileProps.moveToDashboard}
+ onCopyToDashboard={commonTileProps.copyToDashboard}
+ showResizeHandles={commonTileProps.showResizeHandles}
+ showEditingControls={commonTileProps.showEditingControls}
+ canEnterEditModeFromEdge={commonTileProps.canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={commonTileProps.onEnterEditModeFromEdge}
+ onDragHandleMouseDown={commonTileProps.onDragHandleMouseDown}
+ />
+ )
+ }
})}
</ReactGridLayout>
</div>
diff --git a/frontend/src/scenes/dashboard/DashboardModals.tsx b/frontend/src/scenes/dashboard/DashboardModals.tsx
index 5fecbbe0cc3d..a9865cbeaffc 100644
--- a/frontend/src/scenes/dashboard/DashboardModals.tsx
+++ b/frontend/src/scenes/dashboard/DashboardModals.tsx
@@ -1,6 +1,8 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
+import { AddWidgetModal } from '@posthog/products-dashboards/frontend/widgets/AddWidgetModal'
+
import { ButtonTileCardModal } from 'lib/components/Cards/ButtonTileCard/ButtonTileCardModal'
import { TextCardModal } from 'lib/components/Cards/TextCard/TextCardModal'
import { SharingModal } from 'lib/components/Sharing/SharingModal'
@@ -29,8 +31,11 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType<QueryB
showButtonTileModal,
buttonTileId,
terraformModalOpen,
+ addWidgetModalOpen,
+ dashboardWidgetsEnabled,
+ addWidgetTileLoading,
} = useValues(dashboardLogic)
- const { setTerraformModalOpen } = useActions(dashboardLogic)
+ const { setTerraformModalOpen, setAddWidgetModalOpen, addWidgetTiles } = useActions(dashboardLogic)
const { updateDashboardSuccess } = useActions(dashboardsModel)
const { push } = useActions(router)
const { user } = useValues(userLogic)
@@ -65,6 +70,19 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType<QueryB
dashboard={dashboard}
buttonTileId={buttonTileId}
/>
+ {dashboardWidgetsEnabled && (
+ <AddWidgetModal
+ isOpen={addWidgetModalOpen}
+ onClose={() => setAddWidgetModalOpen(false)}
+ loading={addWidgetTileLoading}
+ onAdd={async (widgets) => {
+ await addWidgetTiles({
+ dashboardId: dashboard.id,
+ widgets,
+ })
+ }}
+ />
+ )}
<DeleteDashboardModal />
<DuplicateDashboardModal />
<DashboardInsightColorsModal />
diff --git a/frontend/src/scenes/dashboard/EmptyDashboardComponent.test.tsx b/frontend/src/scenes/dashboard/EmptyDashboardComponent.test.tsx
new file mode 100644
index 000000000000..3434c271443f
--- /dev/null
+++ b/frontend/src/scenes/dashboard/EmptyDashboardComponent.test.tsx
@@ -0,0 +1,122 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { BindLogic } from 'kea'
+
+import { FEATURE_FLAGS } from 'lib/constants'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+import { maxGlobalLogic } from 'scenes/max/maxGlobalLogic'
+
+import { useMocks } from '~/mocks/jest'
+import { initKeaTests } from '~/test/init'
+import { AccessControlLevel, DashboardType, QueryBasedInsightModel } from '~/types'
+
+import { dashboardLogic } from './dashboardLogic'
+import { EmptyDashboardComponent } from './EmptyDashboardComponent'
+
+jest.mock('./emptyDashboardAiStarterPrompts', () => ({
+ EmptyDashboardAiStarterPrompts: () => null,
+}))
+
+const MOCK_DASHBOARD: DashboardType<QueryBasedInsightModel> = {
+ id: 5,
+ name: 'Test Dashboard',
+ description: 'A test dashboard',
+ pinned: false,
+ tiles: [],
+ tags: [],
+ created_at: '2020-01-01T00:00:00Z',
+ created_by: {
+ id: 1,
+ first_name: 'Test',
+ last_name: 'User',
+ email: '[email protected]',
+ uuid: 'abc',
+ distinct_id: 'test-distinct-id',
+ },
+ last_accessed_at: '2020-01-01T00:00:00Z',
+ is_shared: false,
+ deleted: false,
+ creation_mode: 'default',
+ user_access_level: AccessControlLevel.Editor,
+ filters: {},
+ variables: {},
+}
+
+describe('EmptyDashboardComponent', () => {
+ beforeEach(() => {
+ localStorage.clear()
+ sessionStorage.clear()
+ useMocks({
+ post: {
+ '/api/environments/:team_id/query/': () => [200, { results: [] }],
+ },
+ })
+ initKeaTests()
+ featureFlagLogic.mount()
+ maxGlobalLogic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ function renderEmptyState(opts: { widgetsEnabled?: boolean } = {}): {
+ logic: ReturnType<typeof dashboardLogic.build>
+ } {
+ const { widgetsEnabled = false } = opts
+
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.DASHBOARD_WIDGETS], {
+ [FEATURE_FLAGS.DASHBOARD_WIDGETS]: widgetsEnabled,
+ })
+
+ const logic = dashboardLogic({ id: MOCK_DASHBOARD.id, dashboard: MOCK_DASHBOARD })
+ logic.mount()
+
+ render(
+ <BindLogic logic={dashboardLogic} props={{ id: MOCK_DASHBOARD.id, dashboard: MOCK_DASHBOARD }}>
+ <EmptyDashboardComponent loading={false} canEdit={true} />
+ </BindLogic>
+ )
+
+ return { logic }
+ }
+
+ async function openGetStartedDropdown(): Promise<void> {
+ await userEvent.click(document.querySelector('[data-attr="dashboard-add-dropdown"]')!)
+ }
+
+ it('shows Add text card in Get started dropdown', async () => {
+ const { logic } = renderEmptyState()
+
+ await openGetStartedDropdown()
+
+ expect(screen.getByText('Add text card')).toBeInTheDocument()
+ expect(screen.queryByText('Add widget')).not.toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it('shows Add widget in Get started dropdown when dashboard widgets flag is enabled', async () => {
+ const { logic } = renderEmptyState({ widgetsEnabled: true })
+
+ await openGetStartedDropdown()
+
+ expect(screen.getByText('Add widget')).toBeInTheDocument()
+ expect(screen.getByText('NEW')).toBeInTheDocument()
+
+ logic.unmount()
+ })
+
+ it('opens add widget modal when Add widget is clicked', async () => {
+ const { logic } = renderEmptyState({ widgetsEnabled: true })
+
+ await openGetStartedDropdown()
+ await userEvent.click(screen.getByText('Add widget'))
+
+ expect(logic.values.addWidgetModalOpen).toBe(true)
+
+ logic.unmount()
+ })
+})
diff --git a/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx b/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx
index 766ad0a9c83e..a67c20709873 100644
--- a/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx
+++ b/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx
@@ -2,7 +2,7 @@ import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
import { IconPlus } from '@posthog/icons'
-import { Spinner } from '@posthog/lemon-ui'
+import { LemonTag, Spinner } from '@posthog/lemon-ui'
import { AccessControlAction } from 'lib/components/AccessControlAction'
import { GraphsHog } from 'lib/components/hedgehogs'
@@ -34,14 +34,18 @@ function DashboardEmptyActions({
canEdit,
dashboard,
aiDisabledReason,
+ dashboardWidgetsEnabled,
onAddInsight,
+ onAddWidget,
push,
onOpenAiWithPrompt,
}: {
canEdit: boolean
dashboard: DashboardType<QueryBasedInsightModel> | null | undefined
aiDisabledReason: string | false
+ dashboardWidgetsEnabled: boolean
onAddInsight: () => void
+ onAddWidget: () => void
push: (path: string) => void
onOpenAiWithPrompt: (prompt: string) => void
}): JSX.Element {
@@ -60,21 +64,41 @@ function DashboardEmptyActions({
dropdown: {
placement: 'bottom-end',
overlay: (
- <AccessControlAction
- resourceType={AccessControlResourceType.Dashboard}
- minAccessLevel={AccessControlLevel.Editor}
- userAccessLevel={dashboard.user_access_level}
- >
- <LemonButton
- fullWidth
- onClick={() => {
- push(urls.dashboardTextTile(dashboard.id, 'new'))
- }}
- data-attr="add-text-tile-to-dashboard"
+ <>
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Dashboard}
+ minAccessLevel={AccessControlLevel.Editor}
+ userAccessLevel={dashboard.user_access_level}
>
- Add text card
- </LemonButton>
- </AccessControlAction>
+ <LemonButton
+ fullWidth
+ onClick={() => {
+ push(urls.dashboardTextTile(dashboard.id, 'new'))
+ }}
+ data-attr="add-text-tile-to-dashboard"
+ >
+ Add text card
+ </LemonButton>
+ </AccessControlAction>
+ {dashboardWidgetsEnabled ? (
+ <AccessControlAction
+ resourceType={AccessControlResourceType.Dashboard}
+ minAccessLevel={AccessControlLevel.Editor}
+ userAccessLevel={dashboard.user_access_level}
+ >
+ <LemonButton
+ fullWidth
+ onClick={onAddWidget}
+ data-attr="dashboard-add-widget"
+ >
+ Add widget
+ <LemonTag type="success" size="small" className="ml-2">
+ NEW
+ </LemonTag>
+ </LemonButton>
+ </AccessControlAction>
+ ) : null}
+ </>
),
},
disabled: false,
@@ -103,7 +127,8 @@ function DashboardEmptyActions({
function EmptyDashboardContent({ canEdit }: { canEdit: boolean }): JSX.Element {
const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
- const { dashboard } = useValues(dashboardLogic)
+ const { dashboard, dashboardWidgetsEnabled } = useValues(dashboardLogic)
+ const { setAddWidgetModalOpen } = useActions(dashboardLogic)
const { push } = useActions(router)
const { openSidePanel } = useActions(sidePanelStateLogic)
const { dataProcessingAccepted, dataProcessingApprovalDisabledReason } = useValues(maxGlobalLogic)
@@ -140,7 +165,9 @@ function EmptyDashboardContent({ canEdit }: { canEdit: boolean }): JSX.Element {
canEdit={canEdit}
dashboard={dashboard}
aiDisabledReason={aiDisabledReason}
+ dashboardWidgetsEnabled={dashboardWidgetsEnabled}
onAddInsight={showAddInsightToDashboardModal}
+ onAddWidget={() => setAddWidgetModalOpen(true)}
push={push}
onOpenAiWithPrompt={onOpenAiWithPrompt}
/>
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index e8893f812e30..a1c88ee56b48 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -4,6 +4,9 @@ import { MOCK_TEAM_ID } from 'lib/api.mock'
import { router } from 'kea-router'
import { expectLogic, truth } from 'kea-test-utils'
+import { lemonToast } from '@posthog/lemon-ui'
+import { DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE } from '@posthog/products-dashboards/frontend/widgets/constants'
+
import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { dayjs, now } from 'lib/dayjs'
@@ -11,6 +14,7 @@ import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
import { DashboardLoadAction, dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import * as dashboardUtils from 'scenes/dashboard/dashboardUtils'
+import * as widgetFetchUtils from 'scenes/dashboard/widgetFetchUtils'
import { teamLogic } from 'scenes/teamLogic'
import { resumeKeaLoadersErrors, silenceKeaLoadersErrors } from '~/initKea'
@@ -56,6 +60,20 @@ const TEXT_TILE: DashboardTile<QueryBasedInsightModel> = {
color: InsightColor.Blue,
}
+const WIDGET_TILE: DashboardTile<QueryBasedInsightModel> = {
+ id: 7,
+ widget: { id: '1', widget_type: 'error_tracking_list', config: {} },
+ layouts: {},
+ color: null,
+}
+
+const WIDGET_TILE_WITH_CUSTOM_NAME: DashboardTile<QueryBasedInsightModel> = {
+ id: 8,
+ widget: { id: '2', widget_type: 'error_tracking_list', config: {}, name: 'Critical errors' },
+ layouts: {},
+ color: null,
+}
+
let tileId = 0
export const tileFromInsight = (
insight: QueryBasedInsightModel,
@@ -1339,12 +1357,19 @@ describe('dashboardLogic', () => {
})
describe('text tiles', () => {
+ let lemonToastInfoSpy: jest.SpiedFunction<typeof lemonToast.info>
+
beforeEach(async () => {
+ lemonToastInfoSpy = jest.spyOn(lemonToast, 'info').mockImplementation(() => 'toast-id')
logic = dashboardLogic({ id: 5 })
logic.mount()
await expectLogic(logic).toFinishAllListeners()
})
+ afterEach(() => {
+ lemonToastInfoSpy.mockRestore()
+ })
+
it('can remove text tiles', async () => {
await expectLogic(logic, () => {
logic.actions.removeTile(TEXT_TILE)
@@ -1357,6 +1382,73 @@ describe('dashboardLogic', () => {
expect(logic.values.textTiles).toEqual([])
})
+
+ it('shows undo toast when removing a text tile', async () => {
+ const { render } = await import('@testing-library/react')
+
+ await expectLogic(logic, () => {
+ logic.actions.removeTile(TEXT_TILE)
+ }).toFinishAllListeners()
+
+ expect(lemonToastInfoSpy).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ toastId: `remove-tile-${TEXT_TILE.id}`,
+ button: expect.objectContaining({ label: 'Undo' }),
+ })
+ )
+
+ const toastContent = lemonToastInfoSpy.mock.calls.at(-1)?.[0]
+ const { container } = render(toastContent)
+ expect(container.textContent).toBe('Text card has been removed from the dashboard')
+ })
+ })
+
+ describe('widget tiles', () => {
+ let lemonToastInfoSpy: jest.SpiedFunction<typeof lemonToast.info>
+
+ beforeEach(async () => {
+ lemonToastInfoSpy = jest.spyOn(lemonToast, 'info').mockImplementation(() => 'toast-id')
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+ })
+
+ afterEach(() => {
+ lemonToastInfoSpy.mockRestore()
+ })
+
+ it('shows undo toast with widget name when removing a widget tile', async () => {
+ const { render } = await import('@testing-library/react')
+
+ await expectLogic(logic, () => {
+ logic.actions.removeTile(WIDGET_TILE)
+ }).toFinishAllListeners()
+
+ expect(lemonToastInfoSpy).toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({
+ toastId: `remove-tile-${WIDGET_TILE.id}`,
+ button: expect.objectContaining({ label: 'Undo' }),
+ })
+ )
+
+ const toastContent = lemonToastInfoSpy.mock.calls.at(-1)?.[0]
+ const { container } = render(toastContent)
+ expect(container.textContent).toBe('error_tracking_list widget removed')
+ })
+
+ it('uses custom widget name in undo toast when set', async () => {
+ const { render } = await import('@testing-library/react')
+
+ await expectLogic(logic, () => {
+ logic.actions.removeTile(WIDGET_TILE_WITH_CUSTOM_NAME)
+ }).toFinishAllListeners()
+
+ const toastContent = lemonToastInfoSpy.mock.calls.at(-1)?.[0]
+ const { container } = render(toastContent)
+ expect(container.textContent).toBe('Critical errors widget removed')
+ })
})
describe('layout zoom', () => {
@@ -1456,4 +1548,175 @@ describe('dashboardLogic', () => {
// Ensuring we do go back to the API for 800, which was added to dashboard 5
expectLogic(fiveLogic).toDispatchActions(['loadDashboard']).toFinishAllListeners()
})
+
+ describe('widget orchestration', () => {
+ let fetchRunWidgetsMock: jest.SpiedFunction<typeof widgetFetchUtils.fetchRunWidgets>
+
+ beforeEach(() => {
+ featureFlagLogic.mount()
+ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.DASHBOARD_WIDGETS], {
+ [FEATURE_FLAGS.DASHBOARD_WIDGETS]: true,
+ })
+ fetchRunWidgetsMock = jest.spyOn(widgetFetchUtils, 'fetchRunWidgets').mockResolvedValue([
+ {
+ tile_id: WIDGET_TILE.id,
+ widget_type: 'error_tracking_list',
+ result: { results: [], hasMore: false },
+ error: null,
+ },
+ ])
+
+ useMocks({
+ get: {
+ '/api/environments/:team_id/dashboards/5/': () => [
+ 200,
+ { ...dashboards[5], tiles: [...dashboards[5].tiles, WIDGET_TILE] },
+ ],
+ },
+ })
+ })
+
+ afterEach(() => {
+ fetchRunWidgetsMock.mockRestore()
+ })
+
+ it('refreshDashboardWidgets fetches run_widgets for widget tiles', async () => {
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshDashboardWidgets({ tileIds: [WIDGET_TILE.id], forceRefresh: true })
+ }).toFinishAllListeners()
+
+ expect(fetchRunWidgetsMock).toHaveBeenCalledWith(
+ String(MOCK_TEAM_ID),
+ 5,
+ [WIDGET_TILE.id],
+ expect.anything()
+ )
+ expect(logic.values.widgetResultsByTileId[WIDGET_TILE.id]?.result).toEqual({
+ results: [],
+ hasMore: false,
+ })
+ })
+
+ it('refreshDashboardWidgets sets friendly error when run_widgets fails', async () => {
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ fetchRunWidgetsMock.mockRejectedValueOnce(new Error('Network error'))
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshDashboardWidgets({ tileIds: [WIDGET_TILE.id], forceRefresh: true })
+ }).toFinishAllListeners()
+
+ expect(logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.error).toBe(DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)
+ })
+
+ it('refreshDashboardWidgets sets friendly error when run_widgets returns per-tile error', async () => {
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ fetchRunWidgetsMock.mockResolvedValueOnce([
+ {
+ tile_id: WIDGET_TILE.id,
+ widget_type: 'error_tracking_list',
+ result: null,
+ error: 'Query timeout',
+ },
+ ])
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshDashboardWidgets({ tileIds: [WIDGET_TILE.id], forceRefresh: true })
+ }).toFinishAllListeners()
+
+ expect(logic.values.widgetRefreshStatus[WIDGET_TILE.id]?.error).toBe(DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)
+ expect(logic.values.widgetResultsByTileId[WIDGET_TILE.id]?.error).toBe('Query timeout')
+ })
+
+ it('refreshDashboardWidgets only marks failed tiles when a chunk has mixed results', async () => {
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ fetchRunWidgetsMock.mockResolvedValueOnce([
+ {
+ tile_id: 10,
+ widget_type: 'error_tracking_list',
+ result: { results: [], hasMore: false },
+ error: null,
+ },
+ {
+ tile_id: 11,
+ widget_type: 'session_replay_list',
+ result: null,
+ error: 'Query timeout',
+ },
+ ])
+
+ await expectLogic(logic, () => {
+ logic.actions.refreshDashboardWidgets({ tileIds: [10, 11], forceRefresh: true })
+ }).toFinishAllListeners()
+
+ expect(logic.values.widgetRefreshStatus[10]?.error).toBeNull()
+ expect(logic.values.widgetRefreshStatus[11]?.error).toBe(DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)
+ })
+
+ it('addWidgetTiles refreshes newly created widget tiles', 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<QueryBasedInsightModel>
+
+ jest.spyOn(api, 'create').mockResolvedValueOnce({
+ tiles: [addedTile],
+ })
+
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ fetchRunWidgetsMock.mockResolvedValueOnce([
+ {
+ tile_id: addedTile.id,
+ widget_type: 'error_tracking_list',
+ result: { results: [], hasMore: false },
+ error: null,
+ },
+ ])
+
+ await expectLogic(logic, () => {
+ logic.actions.addWidgetTiles({
+ dashboardId: 5,
+ widgets: [{ widgetType: 'error_tracking_list', config: { limit: 5 } }],
+ })
+ })
+ .toDispatchActions(['refreshDashboardWidgets'])
+ .toFinishAllListeners()
+
+ expect(fetchRunWidgetsMock).toHaveBeenCalledWith(String(MOCK_TEAM_ID), 5, [addedTile.id], expect.anything())
+ })
+
+ it('copyToDashboard calls copy_tile for widget tiles', async () => {
+ jest.spyOn(api, 'create').mockResolvedValueOnce({})
+
+ logic = dashboardLogic({ id: 5 })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ await expectLogic(logic, () => {
+ logic.actions.copyToDashboard(WIDGET_TILE, 5, 8, 'Target dashboard')
+ }).toFinishAllListeners()
+
+ expect(api.create).toHaveBeenCalledWith(`api/environments/${MOCK_TEAM_ID}/dashboards/8/copy_tile`, {
+ fromDashboardId: 5,
+ tileId: WIDGET_TILE.id,
+ })
+ })
+ })
})
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index 164ce2e37b7b..0b6a1f56313e 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -20,8 +20,12 @@ import posthog from 'posthog-js'
import { ResponsiveLayouts } from 'react-grid-layout'
import { LemonDialog, lemonToast } from '@posthog/lemon-ui'
+import type { 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 api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
+import { ApiError } from 'lib/api-error'
import { DataColorTheme } from 'lib/colors'
import { quickFiltersSectionLogic } from 'lib/components/QuickFilters'
import { OrganizationMembershipLevel } from 'lib/constants'
@@ -32,8 +36,14 @@ import { featureFlagLogic, getFeatureFlagPayload } from 'lib/logic/featureFlagLo
import { clearDOMTextSelection, getJSHeapMemory, shouldCancelQuery, toParams, uuid } from 'lib/utils'
import { accessLevelSatisfied } from 'lib/utils/accessControlUtils'
import { DashboardEventSource, eventUsageLogic } from 'lib/utils/eventUsageLogic'
-import { BREAKPOINTS, dashboardToSaveableTemplate } from 'scenes/dashboard/dashboardUtils'
+import { BREAKPOINTS, dashboardToSaveableTemplate, getDashboardTileDisplayName } from 'scenes/dashboard/dashboardUtils'
import { calculateDuplicateLayout, calculateLayouts } from 'scenes/dashboard/tileLayouts'
+import {
+ chunkTileIds,
+ fetchRunWidgets,
+ findNewlyAddedWidgetTiles,
+ WIDGET_CLIENT_TTL_MS,
+} from 'scenes/dashboard/widgetFetchUtils'
import { dataThemeLogic } from 'scenes/dataThemeLogic'
import { MaxContextInput, createMaxContextHelpers } from 'scenes/max/maxTypes'
import { Scene } from 'scenes/sceneTypes'
@@ -231,6 +241,30 @@ export const dashboardLogic = kea<dashboardLogicType>([
action: RefreshDashboardItemsAction | DashboardLoadAction
forceRefresh?: boolean
}) => payload,
+ refreshDashboardWidgets: (payload: { tileIds: number[]; forceRefresh?: boolean }) => payload,
+ setWidgetRunResults: (results: Record<number, DashboardWidgetRunResultApi>) => ({ results }),
+ setWidgetRefreshStatuses: (tileIds: number[], loading: boolean, error?: string | null) => ({
+ tileIds,
+ loading,
+ error,
+ }),
+ addWidgetTiles: (payload: {
+ dashboardId: number
+ widgets: { widgetType: string; config: Record<string, unknown> }[]
+ }) => payload,
+ updateWidgetTileConfig: (payload: {
+ tile: DashboardTile<QueryBasedInsightModel>
+ config: Record<string, unknown>
+ }) => payload,
+ updateWidgetTileMetadata: (payload: {
+ tile: DashboardTile<QueryBasedInsightModel>
+ name?: string
+ description?: string
+ }) => payload,
+ setAddWidgetModalOpen: (open: boolean) => ({ open }),
+ toggleAddWidgetSelectedType: (widgetType: string) => ({ widgetType }),
+ clearAddWidgetSelectedTypes: true,
+ addWidgetTileFinished: true,
/** Update a single refresh status. */
setRefreshStatus: (shortId: InsightShortId, loading = false, queued = false) => ({ shortId, loading, queued }),
/** Update multiple refresh statuses. */
@@ -578,10 +612,10 @@ export const dashboardLogic = kea<dashboardLogicType>([
return getQueryBasedDashboard(dashboard)
},
copyToDashboard: async ({ tile, fromDashboard, toDashboard, toDashboardName }) => {
- if (!tile?.insight && !tile?.text && !tile?.button_tile) {
+ if (!tile?.insight && !tile?.text && !tile?.button_tile && !tile?.widget) {
return values.dashboard
}
- if (tile.button_tile && !tile.insight && !tile.text) {
+ if (tile.button_tile && !tile.insight && !tile.text && !tile.widget) {
lemonToast.error('Copying button tiles to another dashboard is not supported')
return values.dashboard
}
@@ -599,11 +633,13 @@ export const dashboardLogic = kea<dashboardLogicType>([
insight: 'Insight',
text: 'Text card',
button_tile: 'Button',
+ widget: 'Widget',
}
const copyErrorPrefix: Record<DashboardWidgetType, string> = {
insight: 'Could not copy insight',
text: 'Could not copy text card',
button_tile: 'Could not copy button tile',
+ widget: 'Could not copy widget',
}
try {
@@ -1143,6 +1179,63 @@ export const dashboardLogic = kea<dashboardLogicType>([
[dashboardsModel.actionTypes.updateDashboardFailure]: () => false,
},
],
+ widgetResultsByTileId: [
+ {} as Record<number, DashboardWidgetRunResultApi>,
+ {
+ setWidgetRunResults: (state, { results }) => ({ ...state, ...results }),
+ },
+ ],
+ widgetRefreshStatus: [
+ {} as Record<number, { loading?: boolean; error?: string | null; fetchedAt?: number }>,
+ {
+ setWidgetRefreshStatuses: (state, { tileIds, loading, error }) => ({
+ ...state,
+ ...Object.fromEntries(
+ tileIds.map((tileId) => [
+ tileId,
+ loading
+ ? { loading: true, error: null }
+ : { loading: false, error: error ?? null, fetchedAt: Date.now() },
+ ])
+ ),
+ }),
+ setWidgetRunResults: (state, { results }) => {
+ const next = { ...state }
+ for (const tileId of Object.keys(results).map(Number)) {
+ next[tileId] = { ...next[tileId], loading: false, fetchedAt: Date.now() }
+ }
+ return next
+ },
+ },
+ ],
+ addWidgetTileLoading: [
+ false,
+ {
+ addWidgetTiles: () => true,
+ addWidgetTileFinished: () => false,
+ },
+ ],
+ addWidgetModalOpen: [
+ false,
+ {
+ setAddWidgetModalOpen: (_, { open }) => open,
+ },
+ ],
+ addWidgetSelectedTypes: [
+ [] as string[],
+ {
+ toggleAddWidgetSelectedType: (state, { widgetType }) => {
+ const selected = new Set(state)
+ if (selected.has(widgetType)) {
+ selected.delete(widgetType)
+ } else {
+ selected.add(widgetType)
+ }
+ return Array.from(selected)
+ },
+ clearAddWidgetSelectedTypes: () => [],
+ },
+ ],
})),
selectors(() => ({
shouldUseStreaming: [
@@ -1403,6 +1496,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
],
tiles: [(s) => [s.dashboard], (dashboard) => dashboard?.tiles?.filter((t) => !t.deleted) || []],
+ widgetTiles: [(s) => [s.tiles], (tiles) => tiles.filter((t) => !!t.widget)],
+ dashboardWidgetsEnabled: [
+ (s) => [s.featureFlags],
+ (featureFlags): boolean => !!featureFlags[FEATURE_FLAGS.DASHBOARD_WIDGETS],
+ ],
insightTiles: [
(s) => [s.tiles],
(tiles) => tiles.filter((t) => !!t.insight).filter((i) => !i.insight?.deleted),
@@ -1731,8 +1829,6 @@ export const dashboardLogic = kea<dashboardLogicType>([
handleDashboardLoadComplete: () => {
// Shared logic for refreshing dashboard items after load (used by both regular and streaming loads)
if (values.placement !== DashboardPlacement.Export) {
- // access stored values from dashboardLoadData
- // as we can't pass them down to this listener
const loadAction = values.dashboardLoadData.action!
actions.refreshDashboardItems({ action: loadAction, forceRefresh: false })
}
@@ -1744,6 +1840,11 @@ export const dashboardLogic = kea<dashboardLogicType>([
},
})),
listeners(({ actions, values, cache, props, sharedListeners }) => ({
+ setAddWidgetModalOpen: ({ open }) => {
+ if (open) {
+ actions.clearAddWidgetSelectedTypes()
+ }
+ },
togglePinned: () => {
if (values.dashboard) {
// Reducers have already run, so values.isPinned reflects the desired new state.
@@ -1869,6 +1970,63 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.loadDashboard({ action: DashboardLoadAction.Update })
}
},
+ removeTile: ({ tile }) => {
+ cache.removedTileForUndo = tile
+ },
+ removeTileSuccess: () => {
+ const tile = cache.removedTileForUndo as DashboardTile<QueryBasedInsightModel> | undefined
+ cache.removedTileForUndo = undefined
+ if (!tile) {
+ return
+ }
+
+ const tileName = getDashboardTileDisplayName(tile)
+ const isWidgetTile = !!tile.widget
+ const removedMessage = isWidgetTile ? 'widget removed' : 'has been removed from the dashboard'
+ const toastId = `remove-tile-${tile.id}`
+
+ lemonToast.info(
+ <>
+ <b>{tileName}</b> {removedMessage}
+ </>,
+ {
+ toastId,
+ button: {
+ label: 'Undo',
+ dataAttr: 'undo-remove-tile-from-dashboard',
+ action: async () => {
+ try {
+ await api.update(`api/environments/${values.currentTeamId}/dashboards/${props.id}`, {
+ tiles: [{ id: tile.id, deleted: false }],
+ })
+
+ if (tile.insight) {
+ const insight = tile.insight
+ const nextDashboards = insight.dashboards?.includes(props.id)
+ ? insight.dashboards
+ : [...(insight.dashboards || []), props.id]
+ dashboardsModel.actions.updateDashboardInsight(
+ { ...insight, dashboards: nextDashboards },
+ [props.id]
+ )
+ }
+
+ actions.loadDashboard({ action: DashboardLoadAction.Update })
+
+ lemonToast.success(
+ <>
+ <b>{tileName}</b> {isWidgetTile ? 'widget restored' : 'has been restored'}
+ </>,
+ { toastId }
+ )
+ } catch (e) {
+ lemonToast.error('Could not restore tile: ' + String(e))
+ }
+ },
+ },
+ }
+ )
+ },
moveToDashboardSuccess: ({ payload }) => {
if (payload?.toDashboard === undefined || payload?.tile === undefined) {
return
@@ -1912,11 +2070,27 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
}
+ if (updatedTile.widget) {
+ const widget = updatedTile.widget
+ updatedTile.widget = {
+ ...widget,
+ dashboard_tiles: nextTilePlacement(widget.dashboard_tiles ?? undefined),
+ }
+ }
+
dashboardsModel.actions.tileMovedToDashboard(updatedTile, toDashboard)
+ const moveToastLabel: Record<DashboardWidgetType, string> = {
+ insight: 'Insight',
+ text: 'Text card',
+ button_tile: 'Button',
+ widget: 'Widget',
+ }
+ const movedWidgetType = getDashboardWidgetType(updatedTile)
+
lemonToast.success(
<>
- Insight moved to{' '}
+ {moveToastLabel[movedWidgetType]} moved to{' '}
<b>
<Link to={urls.dashboard(toDashboard)}>{toDashboardName}</Link>
</b>
@@ -1988,6 +2162,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
}
actions.refreshDashboardItems({ action: RefreshDashboardItemsAction.Refresh, forceRefresh: true })
+ if (values.dashboardWidgetsEnabled) {
+ const widgetTileIds = values.widgetTiles.map((tile) => tile.id)
+ if (widgetTileIds.length > 0) {
+ actions.refreshDashboardWidgets({ tileIds: widgetTileIds, forceRefresh: true })
+ }
+ }
},
/** Called when a single insight is refreshed manually on the dashboard */
refreshDashboardItem: async ({ tile }, breakpoint) => {
@@ -2232,6 +2412,165 @@ export const dashboardLogic = kea<dashboardLogicType>([
) {
actions.forceRefreshIfStale()
}
+
+ if (
+ values.dashboardWidgetsEnabled &&
+ values.placement !== DashboardPlacement.Export &&
+ values.placement !== DashboardPlacement.Public
+ ) {
+ const widgetTileIds = values.widgetTiles.map((tile) => tile.id)
+ if (widgetTileIds.length > 0) {
+ actions.refreshDashboardWidgets({ tileIds: widgetTileIds, forceRefresh: !!forceRefresh })
+ }
+ }
+ },
+ refreshDashboardWidgets: async ({ tileIds, forceRefresh }, breakpoint) => {
+ if (
+ values.placement === DashboardPlacement.Export ||
+ values.placement === DashboardPlacement.Public ||
+ !values.dashboardWidgetsEnabled
+ ) {
+ return
+ }
+
+ const staleTileIds = tileIds.filter((tileId) => {
+ if (forceRefresh) {
+ return true
+ }
+ const fetchedAt = values.widgetRefreshStatus[tileId]?.fetchedAt
+ return !fetchedAt || Date.now() - fetchedAt > WIDGET_CLIENT_TTL_MS
+ })
+
+ if (staleTileIds.length === 0) {
+ return
+ }
+
+ actions.setWidgetRefreshStatuses(staleTileIds, true)
+ await breakpoint()
+
+ const projectId = String(values.currentTeamId)
+ const dashboardId = props.id
+ const fetchFunctions = chunkTileIds(staleTileIds, 4).map((chunk) => async () => {
+ try {
+ const results = await fetchRunWidgets(projectId, dashboardId, chunk, {
+ signal: cache.abortController?.signal,
+ })
+ const resultsByTileId = Object.fromEntries(results.map((result) => [result.tile_id, result]))
+ actions.setWidgetRunResults(resultsByTileId)
+ for (const result of results) {
+ actions.setWidgetRefreshStatuses(
+ [result.tile_id],
+ false,
+ result.error ? DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE : null
+ )
+ }
+ } catch {
+ actions.setWidgetRefreshStatuses(chunk, false, DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE)
+ }
+ })
+
+ await runWithLimit(fetchFunctions, 4)
+ },
+ addWidgetTiles: async ({ dashboardId, widgets }) => {
+ if (widgets.length === 0) {
+ return
+ }
+
+ try {
+ const previousWidgetTileIds = new Set(values.widgetTiles.map((tile) => tile.id))
+
+ const response = await api.create(
+ `api/environments/${teamLogic.values.currentTeamId}/dashboards/${dashboardId}/widgets/batch/`,
+ {
+ widgets: widgets.map(({ widgetType, config }) => ({
+ widget_type: widgetType,
+ config,
+ })),
+ }
+ )
+ const createdTiles = findNewlyAddedWidgetTiles(previousWidgetTileIds, response.tiles)
+ if (createdTiles.length > 0 && values.dashboard?.id === dashboardId) {
+ const dashboard = getQueryBasedDashboard({
+ ...values.dashboard,
+ tiles: [...values.dashboard.tiles, ...createdTiles],
+ } as DashboardType<InsightModel>)
+ if (dashboard) {
+ dashboardsModel.actions.updateDashboardSuccess(dashboard)
+ }
+ }
+
+ if (createdTiles.length > 0) {
+ actions.refreshDashboardWidgets({
+ tileIds: createdTiles.map((tile) => tile.id),
+ forceRefresh: true,
+ })
+ }
+
+ const count = createdTiles.length
+ if (count > 1) {
+ lemonToast.success(`Added ${count} widgets`)
+ }
+ } catch (e) {
+ lemonToast.error(e instanceof ApiError ? (e.detail ?? e.message) : 'Could not add widgets')
+ throw e
+ } finally {
+ actions.addWidgetTileFinished()
+ }
+ },
+ updateWidgetTileConfig: async ({ tile, config }) => {
+ if (!values.dashboard?.id || !tile.widget) {
+ return
+ }
+ try {
+ const updatedTile = await updateDashboardWidgetTile({
+ teamId: teamLogic.values.currentTeamId!,
+ dashboardId: values.dashboard.id,
+ tile,
+ config,
+ })
+ const dashboard = getQueryBasedDashboard({
+ ...values.dashboard,
+ tiles: values.dashboard.tiles.map((existingTile) =>
+ existingTile.id === tile.id ? { ...existingTile, ...updatedTile } : existingTile
+ ),
+ } as DashboardType<InsightModel>)
+ if (dashboard) {
+ dashboardsModel.actions.updateDashboardSuccess(dashboard)
+ }
+ actions.refreshDashboardWidgets({ tileIds: [tile.id], forceRefresh: true })
+ } catch (e) {
+ if (isWidgetConfigValidationError(e)) {
+ throw e
+ }
+ lemonToast.error(e instanceof ApiError ? (e.detail ?? e.message) : 'Could not update widget')
+ throw e
+ }
+ },
+ updateWidgetTileMetadata: async ({ tile, name, description }) => {
+ if (!values.dashboard?.id || !tile.widget) {
+ return
+ }
+ try {
+ const updatedTile = await updateDashboardWidgetTile({
+ teamId: teamLogic.values.currentTeamId!,
+ dashboardId: values.dashboard.id,
+ tile,
+ name,
+ description,
+ })
+ const dashboard = getQueryBasedDashboard({
+ ...values.dashboard,
+ tiles: values.dashboard.tiles.map((existingTile) =>
+ existingTile.id === tile.id ? { ...existingTile, ...updatedTile } : existingTile
+ ),
+ } as DashboardType<InsightModel>)
+ if (dashboard) {
+ dashboardsModel.actions.updateDashboardSuccess(dashboard)
+ }
+ } catch (e) {
+ lemonToast.error(e instanceof ApiError ? (e.detail ?? e.message) : 'Could not update widget')
+ throw e
+ }
},
saveEditModeChanges: () => {
if (
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
index d486bf2daf5c..678599feb383 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
@@ -1,6 +1,10 @@
import { dayjs } from 'lib/dayjs'
+import { DashboardPlacement, DashboardTile, QueryBasedInsightModel } from '~/types'
+
import {
+ getDashboardTileDisplayName,
+ isWidgetTileVisibleOnPlacement,
parseURLFilters,
parseURLVariables,
SEARCH_PARAM_FILTERS_KEY,
@@ -8,6 +12,40 @@ import {
shouldSharedDashboardAutoForceForStaleTime,
} from './dashboardUtils'
+describe('getDashboardTileDisplayName', () => {
+ it('uses widget header title when no custom name is set', () => {
+ const tile: DashboardTile<QueryBasedInsightModel> = {
+ id: 1,
+ widget: { id: '1', widget_type: 'error_tracking_list', config: {} },
+ layouts: {},
+ color: null,
+ }
+
+ expect(getDashboardTileDisplayName(tile)).toBe('error_tracking_list')
+ })
+
+ it('uses custom widget name when set', () => {
+ const tile: DashboardTile<QueryBasedInsightModel> = {
+ id: 1,
+ widget: { id: '1', widget_type: 'error_tracking_list', config: {}, name: 'Critical errors' },
+ layouts: {},
+ color: null,
+ }
+
+ expect(getDashboardTileDisplayName(tile)).toBe('Critical errors')
+ })
+})
+
+describe('isWidgetTileVisibleOnPlacement', () => {
+ it.each([
+ [DashboardPlacement.Dashboard, true],
+ [DashboardPlacement.Public, false],
+ [DashboardPlacement.Export, false],
+ ])('placement=%s → %s', (placement, expected) => {
+ expect(isWidgetTileVisibleOnPlacement(placement)).toBe(expected)
+ })
+})
+
describe('parseURLVariables', () => {
it.each([
['a JSON string value', '{"card_name":"Polukranos, Unchained"}', { card_name: 'Polukranos, Unchained' }],
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index 76338e68c051..5c9ea21f63b4 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -1,6 +1,7 @@
import { ResponsiveLayouts } from 'react-grid-layout'
import { lemonToast } from '@posthog/lemon-ui'
+import { getDashboardWidgetCatalogEntry } from '@posthog/products-dashboards/frontend/widget_types/catalog'
import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
import type { Dayjs } from 'lib/dayjs'
@@ -15,6 +16,7 @@ import {
AccessControlLevel,
AccessControlResourceType,
DashboardLayoutSize,
+ DashboardPlacement,
DashboardTemplateEditorType,
DashboardTile,
DashboardType,
@@ -71,19 +73,53 @@ export function dashboardToSaveableTemplate(
color: tile.color,
}
}
+ if (tile.widget) {
+ return {
+ type: 'WIDGET' as const,
+ widget_type: tile.widget.widget_type,
+ config: tile.widget.config,
+ layouts: tile.layouts,
+ color: tile.color,
+ }
+ }
throw new Error('Unknown tile type')
}),
variables: [],
}
}
+export function getDashboardTileDisplayName(tile: DashboardTile<QueryBasedInsightModel>): string {
+ if (tile.insight) {
+ return tile.insight.name || tile.insight.derived_name || 'Unnamed insight'
+ }
+ if (tile.widget) {
+ const customName = tile.widget.name?.trim()
+ if (customName) {
+ return customName
+ }
+ const catalogEntry = getDashboardWidgetCatalogEntry(tile.widget.widget_type)
+ return catalogEntry?.headerTitle ?? catalogEntry?.label ?? tile.widget.widget_type
+ }
+ if (tile.text) {
+ return 'Text card'
+ }
+ if (tile.button_tile) {
+ return tile.button_tile.text || 'Button'
+ }
+
+ return 'Tile'
+}
+
/** Which widget payload is set on a dashboard tile row. Add a branch per `DashboardWidgetType` when new tile kinds ship. */
export function getDashboardWidgetType(
- tile: Pick<DashboardTile<InsightModel | QueryBasedInsightModel>, 'insight' | 'text' | 'button_tile'>
+ tile: Pick<DashboardTile<InsightModel | QueryBasedInsightModel>, 'insight' | 'text' | 'button_tile' | 'widget'>
): DashboardWidgetType {
if (tile.insight) {
return 'insight'
}
+ if (tile.widget) {
+ return 'widget'
+ }
if (tile.text) {
return 'text'
}
@@ -96,6 +132,11 @@ export function getDashboardWidgetType(
)
}
+/** Widget tiles are not shown on shared/public/export dashboard views. */
+export function isWidgetTileVisibleOnPlacement(placement: DashboardPlacement): boolean {
+ return placement !== DashboardPlacement.Public && placement !== DashboardPlacement.Export
+}
+
export const BREAKPOINTS: Record<DashboardLayoutSize, number> = {
sm: 768,
xs: 0,
diff --git a/frontend/src/scenes/dashboard/docs/troubleshooting/README.md b/frontend/src/scenes/dashboard/docs/troubleshooting/README.md
new file mode 100644
index 000000000000..00875f5e4ca0
--- /dev/null
+++ b/frontend/src/scenes/dashboard/docs/troubleshooting/README.md
@@ -0,0 +1,9 @@
+# Dashboard scene troubleshooting
+
+Symptom-driven notes for the dashboard scene (`frontend/src/scenes/dashboard/`).
+
+## Edit mode / react-grid-layout
+
+| Symptom | Doc |
+| ----------------------------------------- | ------------------------------------------------------------ |
+| Resize preview renders under tile content | [rgl-edit-mode-tile-resize.md](rgl-edit-mode-tile-resize.md) |
diff --git a/frontend/src/scenes/dashboard/docs/troubleshooting/rgl-edit-mode-tile-resize.md b/frontend/src/scenes/dashboard/docs/troubleshooting/rgl-edit-mode-tile-resize.md
new file mode 100644
index 000000000000..8b18d149d57e
--- /dev/null
+++ b/frontend/src/scenes/dashboard/docs/troubleshooting/rgl-edit-mode-tile-resize.md
@@ -0,0 +1,81 @@
+# RGL edit-mode resize preview under tile content
+
+In dashboard **edit mode**, dragging a tile resize handle shows the orange preview **under** the tile body instead of on top. View mode is unaffected — this is CSS/DOM glue in the dashboard scene fighting react-grid-layout, not stored layout JSON.
+
+## How PostHog wires RGL
+
+```text
+ReactGridLayout (DashboardItems.tsx)
+ └─ tile root = .react-grid-item ← InsightCard / TextCard / ButtonTileCard / WidgetCard (same node)
+ inline: position:absolute, transform, width, height (RGL v2)
+ children: tile content, DashboardResizeHandles (.handle), RGL .react-resizable-handle
+```
+
+Rules:
+
+1. **Tile card root = RGL child** — one `div`, `forwardRef`. Scene wrappers must pass `ref`, `className`, `style`, and `children` (RGL resize handles) to that root unchanged.
+2. **Decorative handles ≠ RGL handles** — `DashboardResizeHandles` (`.handle`) vs injected `.react-resizable-handle`. Both must be **direct children** of `.react-grid-item` (see `InsightCard`: handles outside `ErrorBoundary`).
+
+## Cause
+
+The white/orange resize preview is painted by RGL on `.react-resizable-handle`. PostHog also renders decorative `DashboardResizeHandles` (`.handle`) on the grid item. If `.handle` is not anchored to the full grid cell, its SVG overlays sit above the preview and look like content covering the resize ghost.
+
+Common triggers:
+
+- `.handle` missing `inset: 0` on `.react-grid-item > .handle`
+- Handle markup placed on an inner wrapper instead of the tile root
+- `DashboardResizeHandles` inside `ErrorBoundary` (viz errors can drop handles off the grid item)
+
+## Files (check in this order)
+
+1. `DashboardItems.scss` — `.react-grid-item > .handle`, placeholder z-index
+2. `lib/components/Cards/handles.tsx` — decorative handle markup
+3. Tile roots: `InsightCard.tsx`, `TextCard.tsx`, `ButtonTileCard.tsx`, product tile shells (e.g. `WidgetCard.tsx` + scene wrapper)
+4. `DashboardItems.tsx` — tile render branches if a new wrapper broke `ref`/`style`/`children` forwarding
+
+## Fix
+
+### Decorative handles on the grid item
+
+In `DashboardItems.scss`:
+
+```scss
+.react-grid-item > .handle {
+ position: absolute;
+ inset: 0;
+ pointer-events: none;
+}
+```
+
+### Tile root prop order
+
+```tsx
+<div className={clsx('DashboardTileCard …', className)} {...divProps} style={style} ref={ref}>
+ {/* content */}
+ {showResizeHandles && <DashboardResizeHandles />}
+ {children /* RGL .react-resizable-handle nodes */}
+</div>
+```
+
+### Placeholder above grid background
+
+```scss
+.react-grid-item.react-grid-placeholder {
+ position: relative;
+ z-index: 2;
+}
+```
+
+## Anti-patterns
+
+| Do not | Why |
+| ------------------------------------------------------------------------------- | -------------------------------------------------------- |
+| `.react-grid-item.resizing { z-index: 105 }` | Masks symptoms; breaks interaction |
+| Handle CSS on inner wrappers without `inset: 0` on `.react-grid-item > .handle` | SVG overlays cover the orange preview |
+| `DashboardResizeHandles` inside `ErrorBoundary` | Handles must stay on the grid item root with RGL handles |
+
+## Verify
+
+1. Dashboard with mixed tile types (insight + text + button/widget if present).
+2. Edit mode (E). Resize from the SE handle on each type.
+3. Orange preview renders on top of tile content, aligned to the gray grid.
diff --git a/frontend/src/scenes/dashboard/tileLayouts.test.ts b/frontend/src/scenes/dashboard/tileLayouts.test.ts
index 92a1a3e9848e..97b049ec0a63 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.test.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.test.ts
@@ -115,6 +115,30 @@ describe('calculating tile layouts', () => {
expect(ys.every((y, i) => i === 0 || y > ys[i - 1])).toBe(true)
})
+ it.each([
+ {
+ name: 'uses default widget minH when catalog omits minH',
+ widgetType: 'unknown_widget',
+ expectedMinH: 4,
+ expectedMinW: 6,
+ },
+ ])('$name', ({ widgetType, expectedMinH, expectedMinW }) => {
+ const tiles: DashboardTile<QueryBasedInsightModel>[] = [
+ {
+ id: 1,
+ widget: { widget_type: widgetType, config: {} },
+ layouts: { sm: { i: '1', x: 0, y: 0, w: 6, h: 5 } },
+ } as unknown as DashboardTile<QueryBasedInsightModel>,
+ ]
+
+ const result = calculateLayouts(tiles)
+
+ expect(result.sm?.[0]?.minH).toBe(expectedMinH)
+ expect(result.xs?.[0]?.minH).toBe(expectedMinH)
+ expect(result.sm?.[0]?.minW).toBe(expectedMinW)
+ expect(result.xs?.[0]?.minW).toBe(expectedMinW)
+ })
+
it('xs follows sm dirty-placement order when no tiles have stored sm layouts', () => {
const tiles: DashboardTile<QueryBasedInsightModel>[] = [
textTileWithLayout({} as Record<DashboardLayoutSize, TileLayout>, 1),
diff --git a/frontend/src/scenes/dashboard/tileLayouts.ts b/frontend/src/scenes/dashboard/tileLayouts.ts
index a08e8033ef66..00239866b62a 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.ts
@@ -1,5 +1,10 @@
import { Layout } from 'react-grid-layout'
+import {
+ getDashboardWidgetCatalogEntry,
+ type DashboardWidgetCatalogEntry,
+} from '@posthog/products-dashboards/frontend/widget_types/catalog'
+
import { BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
@@ -15,6 +20,45 @@ export interface TileLayout {
const MIN_TILE_HEIGHT_ROWS = 2
const MIN_TEXT_TILE_HEIGHT_ROWS = 1
+const MIN_WIDGET_TILE_WIDTH_COLS = 6
+const MIN_WIDGET_TILE_HEIGHT_ROWS = 4
+
+type WidgetCatalogLayout = DashboardWidgetCatalogEntry['defaultLayout']
+
+/**
+ * Widget tile sizing from `DASHBOARD_WIDGET_CATALOG[].defaultLayout` (w, h, minW, minH).
+ * Returns undefined when `widget_type` is missing or unknown; callers use scene fallbacks
+ * (default size 6×5, mins `MIN_WIDGET_TILE_WIDTH_COLS` / `MIN_WIDGET_TILE_HEIGHT_ROWS`).
+ */
+function getWidgetCatalogLayout(widgetType: string | undefined): WidgetCatalogLayout | undefined {
+ if (!widgetType) {
+ return undefined
+ }
+ return getDashboardWidgetCatalogEntry(widgetType)?.defaultLayout
+}
+
+function getTileMinDimensions({
+ isTextTile,
+ isButtonTile,
+ isWidgetTile,
+ widgetCatalogLayout,
+}: {
+ isTextTile: boolean
+ isButtonTile: boolean
+ isWidgetTile: boolean
+ widgetCatalogLayout: WidgetCatalogLayout | undefined
+}): { minW: number; minH: number } {
+ if (isTextTile || isButtonTile) {
+ return { minW: 1, minH: MIN_TEXT_TILE_HEIGHT_ROWS }
+ }
+ if (isWidgetTile) {
+ return {
+ minW: widgetCatalogLayout?.minW ?? MIN_WIDGET_TILE_WIDTH_COLS,
+ minH: widgetCatalogLayout?.minH ?? MIN_WIDGET_TILE_HEIGHT_ROWS,
+ }
+ }
+ return { minW: 2, minH: MIN_TILE_HEIGHT_ROWS }
+}
export interface DuplicateLayoutResult {
duplicateLayouts: { sm?: TileLayout }
@@ -92,6 +136,15 @@ function canPlaceToRight(
})
}
+export function defaultSmLayoutAtBottom(smLayout: Layout | undefined, w: number, h: number): TileLayout {
+ let maxBottom = 0
+ for (const layout of smLayout ?? []) {
+ maxBottom = Math.max(maxBottom, (layout.y ?? 0) + (layout.h ?? 0))
+ }
+
+ return { x: 0, y: maxBottom, w, h }
+}
+
export const sortTilesByLayout = (
tiles: Array<DashboardTile<QueryBasedInsightModel>>,
col: DashboardLayoutSize
@@ -165,15 +218,24 @@ export const calculateLayouts = (
const isTextTile = !!tile.text
const isButtonTile = !!tile.button_tile
+ const isWidgetTile = !!tile.widget
+ const widgetCatalogLayout = isWidgetTile ? getWidgetCatalogLayout(tile.widget?.widget_type) : undefined
if (isButtonTile) {
defaultW = 3
defaultH = 1
+ } else if (isWidgetTile) {
+ defaultW = widgetCatalogLayout?.w ?? 6
+ defaultH = widgetCatalogLayout?.h ?? 5
}
const xsSmH = breakpoint === 'xs' ? tile.layouts?.sm?.h : undefined
const realW = Math.min(w || defaultW, columnCount)
const realH = h || (typeof xsSmH === 'number' && xsSmH > 0 ? xsSmH : undefined) || defaultH
- const minH = isTextTile || isButtonTile ? MIN_TEXT_TILE_HEIGHT_ROWS : MIN_TILE_HEIGHT_ROWS
- const minW = isTextTile || isButtonTile ? 1 : 2
+ const { minW, minH } = getTileMinDimensions({
+ isTextTile,
+ isButtonTile,
+ isWidgetTile,
+ widgetCatalogLayout,
+ })
return {
i: tile.id?.toString(),
diff --git a/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts b/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts
new file mode 100644
index 000000000000..440d4eb251d3
--- /dev/null
+++ b/frontend/src/scenes/dashboard/widgetFetchUtils.test.ts
@@ -0,0 +1,54 @@
+import type { DashboardTile, QueryBasedInsightModel } from '~/types'
+
+import { chunkTileIds, findNewlyAddedWidgetTiles } from './widgetFetchUtils'
+
+describe('widgetFetchUtils', () => {
+ const widgetTile = (id: number): DashboardTile<QueryBasedInsightModel> => ({
+ id,
+ widget: { id: String(id), widget_type: 'error_tracking_list', config: {} },
+ layouts: {},
+ color: null,
+ })
+
+ describe('findNewlyAddedWidgetTiles', () => {
+ it('returns all tile ids that were not in the previous set', () => {
+ const previousTileIds = new Set([7])
+ const tiles = [widgetTile(7), widgetTile(9), widgetTile(10)]
+
+ expect(findNewlyAddedWidgetTiles(previousTileIds, tiles).map((tile) => tile.id)).toEqual([9, 10])
+ })
+
+ it('does not match an existing tile when multiple widgets share the same type', () => {
+ const previousTileIds = new Set([7, 8])
+ const tiles = [widgetTile(7), widgetTile(8), widgetTile(9)]
+
+ expect(findNewlyAddedWidgetTiles(previousTileIds, tiles).map((tile) => tile.id)).toEqual([9])
+ })
+
+ it('ignores deleted widget tiles', () => {
+ const previousTileIds = new Set([7])
+ const tiles = [widgetTile(7), { ...widgetTile(9), deleted: true }]
+
+ expect(findNewlyAddedWidgetTiles(previousTileIds, tiles)).toEqual([])
+ })
+
+ it('returns empty when no new widget tile exists', () => {
+ const previousTileIds = new Set([7])
+ expect(findNewlyAddedWidgetTiles(previousTileIds, [widgetTile(7)])).toEqual([])
+ })
+ })
+
+ describe('chunkTileIds', () => {
+ it('returns empty array for empty input', () => {
+ expect(chunkTileIds([])).toEqual([])
+ })
+
+ it('chunks tile ids with default size 4', () => {
+ expect(chunkTileIds([1, 2, 3, 4, 5])).toEqual([[1, 2, 3, 4], [5]])
+ })
+
+ it('respects custom chunk size', () => {
+ expect(chunkTileIds([1, 2, 3, 4, 5], 2)).toEqual([[1, 2], [3, 4], [5]])
+ })
+ })
+})
diff --git a/frontend/src/scenes/dashboard/widgetFetchUtils.ts b/frontend/src/scenes/dashboard/widgetFetchUtils.ts
new file mode 100644
index 000000000000..aa620cbb0b6c
--- /dev/null
+++ b/frontend/src/scenes/dashboard/widgetFetchUtils.ts
@@ -0,0 +1,49 @@
+import { dashboardsRunWidgetsRetrieve } from '@posthog/products-dashboards/frontend/generated/api'
+import type { DashboardWidgetRunResultApi } from '@posthog/products-dashboards/frontend/generated/api.schemas'
+
+import type { DashboardTile, QueryBasedInsightModel } from '~/types'
+
+export const WIDGET_CLIENT_TTL_MS = 15 * 60 * 1000
+
+export function findNewlyAddedWidgetTiles(
+ previousTileIds: ReadonlySet<number>,
+ tiles: DashboardTile<QueryBasedInsightModel>[] | undefined | null
+): DashboardTile<QueryBasedInsightModel>[] {
+ if (!tiles?.length) {
+ return []
+ }
+
+ return tiles.filter((tile) => !!tile.widget && !tile.deleted && !previousTileIds.has(tile.id))
+}
+
+export function chunkTileIds(tileIds: number[], chunkSize = 4): number[][] {
+ const chunks: number[][] = []
+ for (let i = 0; i < tileIds.length; i += chunkSize) {
+ chunks.push(tileIds.slice(i, i + chunkSize))
+ }
+ return chunks
+}
+
+export type FetchRunWidgetsOptions = {
+ signal?: AbortSignal
+}
+
+export async function fetchRunWidgets(
+ projectId: string,
+ dashboardId: number,
+ tileIds: number[],
+ options?: FetchRunWidgetsOptions
+): Promise<DashboardWidgetRunResultApi[]> {
+ if (tileIds.length === 0) {
+ return []
+ }
+
+ const response = await dashboardsRunWidgetsRetrieve(
+ projectId,
+ dashboardId,
+ { tile_ids: tileIds.join(',') },
+ { signal: options?.signal }
+ )
+
+ return response.results
+}
diff --git a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx
index fecedd0b05da..3476160f04ad 100644
--- a/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx
+++ b/frontend/src/scenes/session-recordings/playlist/SessionRecordingPreview.tsx
@@ -50,6 +50,11 @@ export interface SessionRecordingPreviewProps {
* @default false
*/
selectable?: boolean
+ /**
+ * Sort column for duration/error/TTL display. When set, playlist logic is not required
+ * (e.g. dashboard widgets that pass order from widget config).
+ */
+ order?: RecordingsQuery['order']
}
function RecordingDuration({ recordingDuration }: { recordingDuration: number | undefined }): JSX.Element {
@@ -317,15 +322,15 @@ const RecordingSummaryIcon = memo(function RecordingSummaryIcon({
)
})
-export const SessionRecordingPreview = memo(
- function SessionRecordingPreview({
+const SessionRecordingPreviewBase = memo(
+ function SessionRecordingPreviewBase({
recording,
isActive,
selectable = false,
- }: SessionRecordingPreviewProps): JSX.Element {
+ order,
+ }: SessionRecordingPreviewProps & { order: RecordingsQuery['order'] }): JSX.Element {
const { playlistTimestampFormat } = useValues(playerSettingsLogic)
- const { filters } = useValues(sessionRecordingsPlaylistLogic)
const { recordingPropertiesById, recordingPropertiesLoading } = useValues(sessionRecordingsListPropertiesLogic)
const { featureFlags } = useValues(featureFlagLogic)
@@ -399,12 +404,12 @@ export const SessionRecordingPreview = memo(
</div>
</div>
- {filters.order === 'console_error_count' ? (
+ {order === 'console_error_count' ? (
<ErrorCount
iconClassNames={iconClassNames}
errorCount={recording.console_error_count}
/>
- ) : filters.order === 'recording_ttl' ? (
+ ) : order === 'recording_ttl' ? (
<RecordingExpiry
iconClassNames={iconClassNames}
recordingTtl={recording.recording_ttl}
@@ -413,7 +418,7 @@ export const SessionRecordingPreview = memo(
<RecordingDuration
recordingDuration={durationToShow(
recording,
- filters.order || DEFAULT_RECORDING_FILTERS_ORDER_BY
+ order || DEFAULT_RECORDING_FILTERS_ORDER_BY
)}
/>
)}
@@ -443,7 +448,28 @@ export const SessionRecordingPreview = memo(
(prevProps, nextProps) =>
prevProps.recording.id === nextProps.recording.id &&
prevProps.isActive === nextProps.isActive &&
- prevProps.selectable === nextProps.selectable
+ prevProps.selectable === nextProps.selectable &&
+ prevProps.order === nextProps.order
+)
+
+function SessionRecordingPreviewFromPlaylist(props: Omit<SessionRecordingPreviewProps, 'order'>): JSX.Element {
+ const { filters } = useValues(sessionRecordingsPlaylistLogic)
+ const order = filters.order || DEFAULT_RECORDING_FILTERS_ORDER_BY
+ return <SessionRecordingPreviewBase {...props} order={order} />
+}
+
+export const SessionRecordingPreview = memo(
+ function SessionRecordingPreview({ order, ...props }: SessionRecordingPreviewProps): JSX.Element {
+ if (order !== undefined) {
+ return <SessionRecordingPreviewBase {...props} order={order} />
+ }
+ return <SessionRecordingPreviewFromPlaylist {...props} />
+ },
+ (prevProps, nextProps) =>
+ prevProps.recording.id === nextProps.recording.id &&
+ prevProps.isActive === nextProps.isActive &&
+ prevProps.selectable === nextProps.selectable &&
+ prevProps.order === nextProps.order
)
export function SessionRecordingPreviewSkeleton(): JSX.Element {
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index dbdabd065ed8..a91af8a4fbe2 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2317,6 +2317,7 @@ export interface DashboardTile<T = InsightModel> extends Tileable {
insight?: T
text?: TextModel
button_tile?: ButtonTileModel
+ widget?: DashboardWidgetModel
deleted?: boolean
is_cached?: boolean
order?: number
@@ -2329,7 +2330,20 @@ export interface DashboardTile<T = InsightModel> extends Tileable {
transparent_background?: boolean | null
}
-export type DashboardWidgetType = 'insight' | 'text' | 'button_tile'
+export type DashboardWidgetType = 'insight' | 'text' | 'button_tile' | 'widget'
+
+export interface DashboardWidgetModel {
+ id: string
+ widget_type: string
+ name?: string | null
+ description?: string
+ config: Record<string, unknown>
+ created_by?: UserBasicType
+ last_modified_by?: UserBasicType
+ last_modified_at?: string
+ team?: number
+ dashboard_tiles?: DashboardTileBasicType[] | null
+}
export interface DashboardTileBasicType {
id: number
@@ -2535,10 +2549,19 @@ export type DashboardTemplateStoredButtonTile = {
color?: InsightColor | null
}
+export type DashboardTemplateStoredWidgetTile = {
+ type: 'WIDGET'
+ widget_type: string
+ config?: Record<string, unknown>
+ layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
+ color?: InsightColor | null
+}
+
export type DashboardTemplateStoredTile =
| DashboardTemplateStoredInsightTile
| DashboardTemplateStoredTextTile
| DashboardTemplateStoredButtonTile
+ | DashboardTemplateStoredWidgetTile
export interface DashboardTemplateType {
id: string
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a0548859309f..083de1f82154 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -496,7 +496,7 @@ importers:
version: 7.6.21([email protected])
storybook-addon-pseudo-states:
specifier: 2.1.2
style-loader:
specifier: ^2.0.0
version: 2.0.0([email protected])
@@ -1839,7 +1839,7 @@ importers:
version: 7.6.21([email protected])
storybook-addon-pseudo-states:
specifier: 2.1.2
storybook-dark-mode:
specifier: 3.0.3
@@ -2392,6 +2392,9 @@ importers:
'@types/react':
specifier: 18.3.27
version: 18.3.27
+ '@types/react-dom':
+ specifier: 18.3.7
+ version: 18.3.7(@types/[email protected])
clsx:
specifier: '*'
version: 1.2.1
@@ -2407,9 +2410,31 @@ importers:
kea-router:
specifier: 'catalog:'
+ posthog-js:
+ specifier: 'catalog:'
+ version: 1.378.1
react:
specifier: 18.3.1
version: 18.3.1
+ react-dom:
+ specifier: 18.3.1
+ version: 18.3.1([email protected])
+ devDependencies:
+ '@storybook/react':
+ specifier: ^8.6.14
+ '@testing-library/jest-dom':
+ specifier: ^5.17.0
+ version: 5.17.0
+ '@testing-library/react':
+ specifier: ^14.3.1
+ '@testing-library/user-event':
+ specifier: ^14.6.1
+ version: 14.6.1(@testing-library/[email protected])
+ jest:
+ specifier: ^29.7.0
products/data_modeling:
dependencies:
@@ -10976,6 +11001,11 @@ packages:
react: 18.3.1
react-dom: 18.3.1
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-55yViiZzPS/cPBuOeW4QGxGqrusjXVyxuknmbYCIwDtFyyvI/CgbjXRHdxNBaIjz+IlftxvBmmSaOqFG5+/dkA==}
+ peerDependencies:
+ storybook: ^8.2.0 || ^8.3.0-0 || ^8.4.0-0 || ^8.5.0-0 || ^8.6.0-0
+
'@storybook/[email protected]':
resolution: {integrity: sha512-1UHiA+h//U0iIm7GAhGG5hN8GaD4rhoqm4ZjUQaCPUemBtEOPMWJk1sQLyGrhlLYDEAp69Sbi4BP/J0LD0nrjQ==}
@@ -11045,6 +11075,11 @@ packages:
'@storybook/[email protected]':
resolution: {integrity: sha512-RFb/iaBJfXygSgXkINPRq8dXu7AxBicTGX7MxqKXbz5FU7ANwV7abH6ONBYURkSDOH9//TQhRlVkF5u8zWg3bw==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-BjIp12gEMgzFkEsgKpDIbZdnSWTZpm2dlws8WiPJCpgJtG+HWSxZ0/Ms30Au9yfwzQEKRSbV/5zpsKMGc2SIJw==}
+ peerDependencies:
+ storybook: ^8.2.0 || ^8.3.0-0 || ^8.4.0-0 || ^8.5.0-0 || ^8.6.0-0
+
'@storybook/[email protected]':
resolution: {integrity: sha512-kwtG7HfxYQIZeGwDg7xFkORhNf0PH+4jRLf/9M6amR537Hctay+Vlv2MGHO6LFzw6IwT4qCtO8xNgzcV9TxZtg==}
@@ -11089,6 +11124,11 @@ packages:
'@storybook/[email protected]':
resolution: {integrity: sha512-KhisNdQX5NdfAln+spLU4B82d804GJQp/CnI5M1mm/taTnjvMgs/wTH9AmR89OPoq+tFZVW0vhy2zgPS3ar71A==}
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-joXRXh3GdVvzhbfIgmix1xs90p8Q/nja7AhEAC2egn5Pl7SKsIYZUCYI6UdrQANb2myg9P552LKXfPect8llKg==}
+ peerDependencies:
+ storybook: ^8.2.0 || ^8.3.0-0 || ^8.4.0-0 || ^8.5.0-0 || ^8.6.0-0
+
'@storybook/[email protected]':
resolution: {integrity: sha512-8qa9OFD1XKrX0Ts7vZFSd0ugIHoQt4rBGZNG7gE17laFxMTMiNAaTEqBF44f6vslx0z8VjIPtQ8qKeurU0IQdg==}
@@ -11113,6 +11153,13 @@ packages:
react: 18.3.1
react-dom: 18.3.1
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-N4xULcAWZQTUv4jy1/d346Tyb4gufuC3UaLCuU/iVSZ1brYF4OW3ANr+096btbMxY8pR/65lmtoqr5CTGwnBvA==}
+ peerDependencies:
+ react: 18.3.1
+ react-dom: 18.3.1
+ storybook: ^8.6.18
+
'@storybook/[email protected]':
resolution: {integrity: sha512-0cvvXe9lrxzC50GPDWbJ4tXr3A07CURTv0ryJ9mSeT0YCNMdpX1B20ibxgy6gYgcAa/4fFPCAX6HuOn1Ec6E+g==}
engines: {node: '>=16'}
@@ -11157,6 +11204,21 @@ packages:
typescript:
optional: true
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-BuLpzMkKtF+UCQCbi+lYVX9cdcAMG86Lu2dDn7UFkPi5HRNFq/zHPSvlz1XDgL0OYMtcqB1aoVzFzcyzUBhhjw==}
+ engines: {node: '>=18.0.0'}
+ peerDependencies:
+ '@storybook/test': 8.6.18
+ react: 18.3.1
+ react-dom: 18.3.1
+ storybook: ^8.6.18
+ typescript: 6.0.3
+ peerDependenciesMeta:
+ '@storybook/test':
+ optional: true
+ typescript:
+ optional: true
+
'@storybook/[email protected]':
resolution: {integrity: sha512-mCzsWe6GrH47Xb1++foL98Zdek7uM5GhaSlrI7blWVohGa0qIUYbfJngqR4ZsrXmJeeEvqowobh+jlxg3IJh+w==}
@@ -11186,6 +11248,11 @@ packages:
react: 18.3.1
react-dom: 18.3.1
+ '@storybook/[email protected]':
+ resolution: {integrity: sha512-n6OEjEtHupa2PdTwWzRepr7cO8NkDd4rgF6BKLitRbujOspLxzMBEqdphs+QLcuiCIgf33SqmEA64QWnbSMhPw==}
+ peerDependencies:
+ storybook: ^8.2.0 || ^8.3.0-0 || ^8.4.0-0 || ^8.5.0-0 || ^8.6.0-0
+
'@storybook/[email protected]':
resolution: {integrity: sha512-GncdY3x0LpbhmUAAJwXYtJDUQEwfF175gsjH0/fxPkxPoV7Sef9TM41jQLJW/5+6TnZoCZP/+aJZTJtq3ni23Q==}
@@ -33779,6 +33846,10 @@ snapshots:
- '@types/react'
- '@types/react-dom'
+ dependencies:
+ storybook: 7.6.21([email protected])
+
'@storybook/[email protected]':
dependencies:
'@storybook/client-logger': 7.6.24
@@ -34082,6 +34153,10 @@ snapshots:
- react
- react-dom
+ dependencies:
+ storybook: 7.6.21([email protected])
+
'@storybook/[email protected]': {}
'@storybook/[email protected]': {}
@@ -34209,6 +34284,10 @@ snapshots:
ts-dedent: 2.2.0
util-deprecate: 1.0.2
+ dependencies:
+ storybook: 7.6.21([email protected])
+
'@storybook/[email protected]': {}
'@storybook/[email protected]': {}
@@ -34237,6 +34316,12 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ storybook: 7.6.21([email protected])
+
dependencies:
@@ -34354,6 +34439,20 @@ snapshots:
- encoding
- supports-color
+ dependencies:
+ '@storybook/components': 8.6.18([email protected]([email protected]))
+ '@storybook/global': 5.0.0
+ '@storybook/manager-api': 8.6.18([email protected]([email protected]))
+ '@storybook/preview-api': 8.6.18([email protected]([email protected]))
+ '@storybook/theming': 8.6.18([email protected]([email protected]))
+ react: 18.3.1
+ react-dom: 18.3.1([email protected])
+ storybook: 7.6.21([email protected])
+ optionalDependencies:
+ typescript: 6.0.3
+
'@storybook/[email protected]':
dependencies:
'@storybook/client-logger': 7.6.20
@@ -34486,6 +34585,10 @@ snapshots:
react: 18.3.1
react-dom: 18.3.1([email protected])
+ dependencies:
+ storybook: 7.6.21([email protected])
+
'@storybook/[email protected]':
dependencies:
'@storybook/channels': 7.6.20
@@ -48150,23 +48253,23 @@ snapshots:
dependencies:
'@storybook/core-events': 7.6.20
- '@storybook/manager-api': 7.6.20([email protected]([email protected]))([email protected])
- '@storybook/preview-api': 7.6.24
+ '@storybook/manager-api': 8.6.18([email protected]([email protected]))
+ '@storybook/preview-api': 8.6.18([email protected]([email protected]))
optionalDependencies:
react: 18.3.1
react-dom: 18.3.1([email protected])
dependencies:
+ '@storybook/components': 8.6.18([email protected]([email protected]))
'@storybook/core-events': 7.6.24
- '@storybook/manager-api': 7.6.20([email protected]([email protected]))([email protected])
- '@storybook/preview-api': 7.6.24
+ '@storybook/manager-api': 8.6.18([email protected]([email protected]))
+ '@storybook/preview-api': 8.6.18([email protected]([email protected]))
optionalDependencies:
react: 18.3.1
diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx
new file mode 100644
index 000000000000..0afd5ed34864
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.test.tsx
@@ -0,0 +1,273 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen, waitFor, within } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+
+import { dashboardWidgetMenusLogic } from 'lib/components/Cards/InsightCard/dashboardWidgetMenusLogic'
+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
+
+import { initKeaTests } from '~/test/init'
+import {
+ DashboardPlacement,
+ DashboardTile,
+ PropertyFilterType,
+ PropertyOperator,
+ QueryBasedInsightModel,
+} from '~/types'
+
+import { DashboardWidgetItem } from './DashboardWidgetItem'
+
+jest.mock('lib/utils/accessControlUtils', () => ({
+ userHasAccess: () => true,
+}))
+
+jest.mock('../../widgets/registry', () => ({
+ getDashboardWidgetDefinition: () => ({
+ Component: () => <div>Widget body</div>,
+ EditModal: ({
+ isOpen,
+ name,
+ defaultTitle,
+ description,
+ onSaveMetadata: _onSaveMetadata,
+ }: {
+ isOpen: boolean
+ name?: string
+ defaultTitle?: string
+ description?: string
+ onSaveMetadata?: (metadata: { name?: string; description?: string }) => void
+ }) =>
+ isOpen ? (
+ <div role="dialog" aria-label="Widget settings">
+ <input defaultValue={name} placeholder={defaultTitle} aria-label="Title" />
+ <textarea
+ defaultValue={description}
+ placeholder="Enter description (optional)"
+ onChange={() => undefined}
+ />
+ </div>
+ ) : null,
+ productAccess: 'error_tracking',
+ }),
+}))
+
+jest.mock('../../widget_types/catalog', () => ({
+ getDashboardWidgetCatalogEntry: () => ({
+ titleHref: '/error_tracking',
+ headerLayout: 'dashboard_tile',
+ groupLabel: 'Error tracking',
+ label: 'Top issues',
+ headerTitle: 'Top issues',
+ }),
+}))
+
+const tile = {
+ id: 1,
+ show_description: true,
+ widget: {
+ id: '10',
+ widget_type: 'error_tracking_list',
+ name: 'My issues',
+ description: 'Top errors this week',
+ config: { limit: 10, dateRange: { date_from: '-7d' } },
+ dashboard_tiles: [],
+ },
+} as unknown as DashboardTile<QueryBasedInsightModel>
+
+const tileWithoutDescription = {
+ ...tile,
+ widget: {
+ ...tile.widget!,
+ description: '',
+ },
+} as DashboardTile<QueryBasedInsightModel>
+
+describe('DashboardWidgetItem', () => {
+ beforeEach(() => {
+ initKeaTests(true, {
+ ...MOCK_DEFAULT_TEAM,
+ test_account_filters: [
+ {
+ key: 'email',
+ value: '@posthog.com',
+ operator: PropertyOperator.NotIContains,
+ type: PropertyFilterType.Person,
+ },
+ ],
+ })
+ featureFlagLogic.mount()
+ dashboardWidgetMenusLogic({
+ instanceKey: 'widget-10',
+ dashboardId: 99,
+ dashboards: undefined,
+ dashboard_tiles: [],
+ }).mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ dashboardWidgetMenusLogic({
+ instanceKey: 'widget-10',
+ dashboardId: 99,
+ dashboards: undefined,
+ dashboard_tiles: [],
+ }).unmount()
+ })
+
+ it('renders insight-style more menu with view, dashboard section, and refresh data', async () => {
+ const onRefresh = jest.fn()
+ render(
+ <DashboardWidgetItem
+ tile={tile}
+ placement={DashboardPlacement.Dashboard}
+ dashboardId={99}
+ result={null}
+ loading={false}
+ lastFetchedAt={Date.now()}
+ onRefresh={onRefresh}
+ onUpdateConfig={jest.fn()}
+ onUpdateMetadata={jest.fn()}
+ toggleShowDescription={jest.fn()}
+ showEditingControls
+ onDuplicate={jest.fn()}
+ onRemove={jest.fn()}
+ onMoveToDashboard={jest.fn()}
+ onCopyToDashboard={jest.fn()}
+ />
+ )
+
+ await userEvent.click(screen.getByRole('button', { name: /more/i }))
+
+ expect(screen.getByRole('link', { name: 'View' })).toHaveAttribute('href', '/project/997/error_tracking')
+ expect(
+ screen
+ .getAllByRole('button', { name: 'Edit' })
+ .find((button: HTMLElement) => button.classList.contains('LemonButton--full-width'))
+ ).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'Duplicate' })).toBeInTheDocument()
+ expect(screen.getByText('Dashboard')).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Hide description' })).toBeInTheDocument()
+ expect(screen.getByRole('button', { name: 'Remove from dashboard' })).toBeInTheDocument()
+ const refreshTrigger = screen.getByRole('button', { name: /Refresh data/i })
+ expect(refreshTrigger).toBeInTheDocument()
+ expect(screen.getByText(/Last computed/i)).toBeInTheDocument()
+
+ await userEvent.click(refreshTrigger)
+ expect(onRefresh).toHaveBeenCalledTimes(1)
+ })
+
+ it('removes widget immediately without a confirmation dialog', async () => {
+ const onRemove = jest.fn()
+ const { container } = render(
+ <DashboardWidgetItem
+ tile={tile}
+ placement={DashboardPlacement.Dashboard}
+ dashboardId={99}
+ result={null}
+ loading={false}
+ onRefresh={jest.fn()}
+ onUpdateConfig={jest.fn()}
+ onUpdateMetadata={jest.fn()}
+ showEditingControls
+ onRemove={onRemove}
+ />
+ )
+
+ await userEvent.click(within(container).getByRole('button', { name: /more/i }))
+ await userEvent.click(await screen.findByRole('button', { name: 'Remove from dashboard' }))
+
+ expect(onRemove).toHaveBeenCalledTimes(1)
+ expect(
+ screen.queryByText('Are you sure you want to remove this widget from the dashboard?')
+ ).not.toBeInTheDocument()
+ })
+
+ it('does not show inline description editor in edit mode when description is empty', () => {
+ const { container } = render(
+ <DashboardWidgetItem
+ tile={tileWithoutDescription}
+ placement={DashboardPlacement.Dashboard}
+ dashboardId={99}
+ result={null}
+ loading={false}
+ onRefresh={jest.fn()}
+ onUpdateConfig={jest.fn()}
+ onUpdateMetadata={jest.fn()}
+ showEditingControls
+ />
+ )
+
+ expect(container.querySelector('[data-attr="widget-card-description"]')).toBeNull()
+ })
+
+ it('opens widget settings from add description menu item', async () => {
+ const toggleShowDescription = jest.fn()
+ const { container } = render(
+ <DashboardWidgetItem
+ tile={{ ...tileWithoutDescription, show_description: false }}
+ placement={DashboardPlacement.Dashboard}
+ dashboardId={99}
+ result={null}
+ loading={false}
+ onRefresh={jest.fn()}
+ onUpdateConfig={jest.fn()}
+ onUpdateMetadata={jest.fn()}
+ toggleShowDescription={toggleShowDescription}
+ showEditingControls
+ />
+ )
+
+ await userEvent.click(within(container).getByRole('button', { name: /more/i }))
+ await userEvent.click(screen.getByRole('button', { name: 'Add description' }))
+
+ expect(toggleShowDescription).toHaveBeenCalledTimes(1)
+ expect(await screen.findByRole('dialog', { name: 'Widget settings' })).toBeInTheDocument()
+ })
+
+ it('opens widget settings with title and description fields from edit menu', async () => {
+ const { container } = render(
+ <DashboardWidgetItem
+ tile={tileWithoutDescription}
+ placement={DashboardPlacement.Dashboard}
+ dashboardId={99}
+ result={null}
+ loading={false}
+ onRefresh={jest.fn()}
+ onUpdateConfig={jest.fn()}
+ onUpdateMetadata={jest.fn()}
+ showEditingControls
+ />
+ )
+
+ await userEvent.click(within(container).getByRole('button', { name: /more/i }))
+ await waitFor(() => {
+ expect(document.querySelector('[data-attr="dashboard-widget-edit"]')).toBeInTheDocument()
+ })
+ await userEvent.click(document.querySelector('[data-attr="dashboard-widget-edit"]') as HTMLElement)
+
+ const dialog = await screen.findByRole('dialog', { name: 'Widget settings' })
+ expect(within(dialog).getByPlaceholderText('Top issues')).toBeInTheDocument()
+ expect(within(dialog).getByPlaceholderText('Enter description (optional)')).toBeInTheDocument()
+ })
+
+ it('does not render inline title editor in edit mode', () => {
+ const { container } = render(
+ <DashboardWidgetItem
+ tile={tile}
+ placement={DashboardPlacement.Dashboard}
+ dashboardId={99}
+ result={null}
+ loading={false}
+ onRefresh={jest.fn()}
+ onUpdateConfig={jest.fn()}
+ onUpdateMetadata={jest.fn()}
+ showEditingControls
+ />
+ )
+
+ expect(container.querySelector('[data-attr="widget-card-title"] .EditableField')).toBeNull()
+ expect(container.querySelector('[data-attr="widget-card-title"]')).toHaveTextContent('My issues')
+ })
+})
diff --git a/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
new file mode 100644
index 000000000000..77f03687df74
--- /dev/null
+++ b/products/dashboards/frontend/components/DashboardWidgetItem/DashboardWidgetItem.tsx
@@ -0,0 +1,293 @@
+import clsx from 'clsx'
+import { useValues } from 'kea'
+import React, { useState } from 'react'
+import { createPortal } from 'react-dom'
+
+import { DashboardTileRefreshDataButton } from 'lib/components/Cards/InsightCard/DashboardTileRefreshDataButton'
+import { dashboardWidgetMenusLogic } from 'lib/components/Cards/InsightCard/dashboardWidgetMenusLogic'
+import { DashboardWidgetPlacementMenus } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+
+import { ErrorBoundary } from '~/layout/ErrorBoundary'
+import { DashboardPlacement, DashboardTile, DashboardType, QueryBasedInsightModel } from '~/types'
+
+import { getDashboardWidgetCatalogEntry } from '../../widget_types/catalog'
+import { userHasDashboardWidgetProductAccess } from '../../widgetProductAccess'
+import { getDashboardWidgetDefinition, type DashboardWidgetComponentProps } from '../../widgets/registry'
+import { WidgetCard } from '../WidgetCard/WidgetCard'
+import { WidgetCardBody } from '../WidgetCard/WidgetCardBody'
+import { WidgetCardHeader, widgetCardShouldHideMoreButton } from '../WidgetCard/WidgetCardHeader'
+import { WidgetRuntimeAvailabilityGuard } from '../WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard'
+
+type DashboardWidgetItemProps = {
+ tile: DashboardTile<QueryBasedInsightModel>
+ placement: DashboardPlacement
+ dashboardId?: number | null
+ result: unknown
+ loading: boolean
+ error?: string | null
+ lastFetchedAt?: number
+ onRefresh: () => void
+ onUpdateConfig: (config: Record<string, unknown>) => void | Promise<void>
+ onUpdateMetadata?: (metadata: { name?: string; description?: string }) => void
+ toggleShowDescription?: () => void
+ showResizeHandles?: boolean
+ canEnterEditModeFromEdge?: boolean
+ onEnterEditModeFromEdge?: () => void
+ onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
+ showEditingControls?: boolean
+ onDuplicate?: () => void
+ onRemove?: () => void
+ onMoveToDashboard?: (target: Pick<DashboardType, 'id' | 'name'>) => void
+ onCopyToDashboard?: (target: Pick<DashboardType, 'id' | 'name'>) => void
+ /** Injected by react-grid-layout / react-resizable — must render inside the card root. */
+ children?: React.ReactNode
+} & Omit<React.HTMLAttributes<HTMLDivElement>, 'children'>
+
+export const DashboardWidgetItem = React.forwardRef<HTMLDivElement, DashboardWidgetItemProps>(
+ function DashboardWidgetItem(
+ {
+ tile,
+ placement,
+ dashboardId,
+ result,
+ loading,
+ error,
+ lastFetchedAt,
+ onRefresh,
+ onUpdateConfig,
+ onUpdateMetadata,
+ toggleShowDescription,
+ showResizeHandles,
+ canEnterEditModeFromEdge,
+ onEnterEditModeFromEdge,
+ onDragHandleMouseDown,
+ showEditingControls,
+ onDuplicate,
+ onRemove,
+ onMoveToDashboard,
+ onCopyToDashboard,
+ children,
+ className,
+ style,
+ ...divProps
+ },
+ ref
+ ): JSX.Element | null {
+ const widget = tile.widget
+ const [editOpen, setEditOpen] = useState(false)
+
+ const { copyToDestinations } = useValues(
+ dashboardWidgetMenusLogic({
+ instanceKey: widget ? `widget-${widget.id}` : `widget-tile-${tile.id}`,
+ dashboardId,
+ dashboards: undefined,
+ dashboard_tiles: widget?.dashboard_tiles,
+ })
+ )
+
+ if (!widget) {
+ return null
+ }
+
+ const definition = getDashboardWidgetDefinition(widget.widget_type, {
+ tileId: tile.id,
+ dashboardId: dashboardId ?? undefined,
+ })
+ const catalogEntry = getDashboardWidgetCatalogEntry(widget.widget_type)
+ const widgetTypeLabel = catalogEntry?.groupLabel ?? catalogEntry?.label ?? widget.widget_type
+ const defaultTitle = catalogEntry?.headerTitle ?? widgetTypeLabel
+ const title = widget.name?.trim() || ''
+ const description = widget.description?.trim() || ''
+ const showDescription = tile.show_description !== false
+ const headerLayout = catalogEntry?.headerLayout ?? 'dashboard_tile'
+ const WidgetComponent = definition?.Component
+
+ const handleDescriptionSave = (nextDescription: string): void => {
+ onUpdateMetadata?.({ description: nextDescription })
+ if (nextDescription.trim() && tile.show_description === false && toggleShowDescription) {
+ toggleShowDescription()
+ }
+ }
+
+ const hasProductAccess = userHasDashboardWidgetProductAccess(definition?.productAccess)
+
+ const titleHref =
+ hasProductAccess && placement !== DashboardPlacement.Public && catalogEntry?.titleHref
+ ? catalogEntry.titleHref
+ : undefined
+
+ const componentProps: DashboardWidgetComponentProps = {
+ tileId: tile.id,
+ config: widget.config,
+ result,
+ loading,
+ error,
+ onRefresh,
+ onUpdateConfig,
+ }
+
+ const EditModal = definition?.EditModal
+
+ const widgetBody =
+ hasProductAccess && WidgetComponent ? (
+ <ErrorBoundary
+ className="flex min-h-0 min-w-0 flex-1 w-full max-w-full flex-col"
+ exceptionProps={{
+ feature: 'dashboard_widget',
+ widget_type: widget.widget_type,
+ tile_id: tile.id,
+ }}
+ >
+ <WidgetRuntimeAvailabilityGuard
+ availability={catalogEntry?.availability}
+ unavailableContentFallback={definition?.unavailableContentFallback}
+ >
+ <WidgetComponent {...componentProps} />
+ </WidgetRuntimeAvailabilityGuard>
+ </ErrorBoundary>
+ ) : null
+
+ const hasDashboardSectionActions =
+ !!(onMoveToDashboard || onCopyToDashboard || onRemove) ||
+ (showEditingControls && toggleShowDescription && !!description) ||
+ (showEditingControls && onUpdateMetadata && !showDescription && !description)
+
+ const refreshDisabledReason = loading ? 'Refreshing...' : undefined
+
+ // react-grid-layout injects className/style via cloneElement — WidgetCard must be the root node
+ // so decorative resize handles and RGL's .react-resizable-handle siblings share a parent (see InsightCard).
+ return (
+ <WidgetCard
+ ref={ref}
+ className={clsx('min-h-0', className)}
+ style={style}
+ {...divProps}
+ showResizeHandles={showResizeHandles}
+ canEnterEditModeFromEdge={canEnterEditModeFromEdge}
+ onEnterEditModeFromEdge={onEnterEditModeFromEdge}
+ gridChildren={children}
+ >
+ <WidgetCardHeader
+ layout={headerLayout}
+ title={title}
+ defaultTitle={defaultTitle}
+ titleHref={titleHref}
+ widgetTypeLabel={widgetTypeLabel}
+ config={widget.config}
+ headerMeta={catalogEntry?.headerMeta}
+ description={description}
+ showDescription={showDescription}
+ loading={loading}
+ showEditingControls={showEditingControls}
+ shouldHideMoreButton={widgetCardShouldHideMoreButton(placement, showEditingControls)}
+ moreButtonOverlay={
+ <>
+ {titleHref && (
+ <LemonButton to={titleHref} fullWidth>
+ View
+ </LemonButton>
+ )}
+ {showEditingControls && EditModal && (
+ <LemonButton
+ fullWidth
+ data-attr="dashboard-widget-edit"
+ onClick={() => setEditOpen(true)}
+ >
+ Edit
+ </LemonButton>
+ )}
+ {onDuplicate && (
+ <LemonButton fullWidth onClick={onDuplicate}>
+ Duplicate
+ </LemonButton>
+ )}
+ {hasDashboardSectionActions && (
+ <>
+ <LemonDivider />
+ <h5 className="mx-2 my-1">Dashboard</h5>
+ {showEditingControls && onUpdateMetadata && !showDescription && !description && (
+ <LemonButton
+ fullWidth
+ onClick={() => {
+ toggleShowDescription?.()
+ setEditOpen(true)
+ }}
+ >
+ Add description
+ </LemonButton>
+ )}
+ {showEditingControls && toggleShowDescription && !!description && (
+ <LemonButton fullWidth onClick={toggleShowDescription}>
+ {tile.show_description === false ? 'Show description' : 'Hide description'}
+ </LemonButton>
+ )}
+ {(onMoveToDashboard || onCopyToDashboard) && (
+ <DashboardWidgetPlacementMenus
+ placementDestinations={copyToDestinations ?? []}
+ onMoveToDashboard={onMoveToDashboard}
+ onCopyToDashboard={onCopyToDashboard}
+ />
+ )}
+ {onRemove && (
+ <LemonButton status="danger" fullWidth onClick={onRemove}>
+ Remove from dashboard
+ </LemonButton>
+ )}
+ </>
+ )}
+ {onRefresh && headerLayout === 'dashboard_tile' && (
+ <>
+ <LemonDivider />
+ <DashboardTileRefreshDataButton
+ onRefresh={onRefresh}
+ disabledReason={refreshDisabledReason}
+ lastRefresh={lastFetchedAt}
+ />
+ </>
+ )}
+ </>
+ }
+ onDragHandleMouseDown={onDragHandleMouseDown}
+ />
+ <WidgetCardBody
+ locked={!hasProductAccess}
+ error={hasProductAccess ? error : undefined}
+ onRefresh={onRefresh}
+ refreshing={loading}
+ >
+ {widgetBody}
+ {EditModal &&
+ editOpen &&
+ createPortal(
+ <EditModal
+ isOpen={editOpen}
+ onClose={() => setEditOpen(false)}
+ config={widget.config}
+ name={title}
+ defaultTitle={defaultTitle}
+ description={description}
+ onSaveMetadata={
+ onUpdateMetadata
+ ? async (metadata) => {
+ if (metadata.name !== undefined) {
+ onUpdateMetadata({ name: metadata.name.trim() || '' })
+ }
+ if (metadata.description !== undefined) {
+ handleDescriptionSave(metadata.description)
+ }
+ }
+ : undefined
+ }
+ onSave={async (config) => {
+ await onUpdateConfig(config)
+ }}
+ />,
+ document.body
+ )}
+ </WidgetCardBody>
+ </WidgetCard>
+ )
+ }
+)
diff --git a/products/dashboards/frontend/components/WidgetAvailabilitySetupPrompt/WidgetAvailabilitySetupPrompt.tsx b/products/dashboards/frontend/components/WidgetAvailabilitySetupPrompt/WidgetAvailabilitySetupPrompt.tsx
new file mode 100644
index 000000000000..ed2a39613fd1
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetAvailabilitySetupPrompt/WidgetAvailabilitySetupPrompt.tsx
@@ -0,0 +1,37 @@
+import { LemonButton } from '@posthog/lemon-ui'
+
+import type { WidgetAvailabilityConfig } from '../../widget_types/widgetAvailability'
+import { WIDGET_AVAILABILITY_PRESENTATION } from '../../widget_types/widgetAvailability'
+import { WidgetCardContent } from '../WidgetCard/WidgetCardBody'
+import { WidgetCardProductIntroduction } from '../WidgetCardProductIntroduction/WidgetCardProductIntroduction'
+
+type WidgetAvailabilitySetupPromptProps = {
+ availability: WidgetAvailabilityConfig
+ className?: string
+}
+
+export function WidgetAvailabilitySetupPrompt({
+ availability,
+ className,
+}: WidgetAvailabilitySetupPromptProps): JSX.Element {
+ const presentation = WIDGET_AVAILABILITY_PRESENTATION[availability.requirement]
+
+ return (
+ <WidgetCardContent className={className}>
+ <WidgetCardProductIntroduction
+ productName={presentation.productName}
+ productKey={presentation.productKey}
+ thingName={presentation.thingName}
+ titleOverride={availability.unavailableTitle}
+ description={availability.unavailableReason}
+ isEmpty
+ docsURL={availability.docsHref}
+ actionElementOverride={
+ <LemonButton type="primary" to={presentation.settingsUrl}>
+ {availability.setupActionLabel}
+ </LemonButton>
+ }
+ />
+ </WidgetCardContent>
+ )
+}
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCard.stories.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCard.stories.tsx
new file mode 100644
index 000000000000..b4d74bc64b43
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCard.stories.tsx
@@ -0,0 +1,156 @@
+import type { Meta, StoryObj } from '@storybook/react'
+import type { ReactNode } from 'react'
+
+import { DashboardPlacement } from '~/types'
+
+import { WidgetCard } from './WidgetCard'
+import { WidgetCardBody, WidgetCardBodyMessage, WidgetLoadingState } from './WidgetCardBody'
+import { WidgetCardHeader, widgetCardShouldHideMoreButton } from './WidgetCardHeader'
+import {
+ dashboardTileTopHeading,
+ mockMoreOverlay,
+ sampleListBody,
+ widgetTileFrameDecorator,
+} from './widgetCardStoryFixtures'
+
+type WidgetCardStoryProps = {
+ placement: DashboardPlacement
+ showEditingControls?: boolean
+ className?: string
+ headerLayout: 'dashboard_tile' | 'simple'
+ title: string
+ topHeading?: ReactNode
+ description?: string
+ showDescription?: boolean
+ loading?: boolean
+ moreButtonOverlay?: ReactNode
+ locked?: boolean
+ lockedMessage?: string
+ body?: ReactNode
+}
+
+function WidgetCardStory({
+ placement,
+ showEditingControls,
+ className,
+ headerLayout,
+ title,
+ topHeading,
+ description,
+ showDescription,
+ loading,
+ moreButtonOverlay,
+ locked,
+ lockedMessage,
+ body,
+}: WidgetCardStoryProps): JSX.Element {
+ return (
+ <WidgetCard className={className}>
+ <WidgetCardHeader
+ layout={headerLayout}
+ title={title}
+ topHeading={topHeading}
+ description={description}
+ showDescription={showDescription}
+ loading={loading}
+ showEditingControls={showEditingControls}
+ shouldHideMoreButton={widgetCardShouldHideMoreButton(placement, showEditingControls)}
+ moreButtonOverlay={moreButtonOverlay}
+ />
+ <WidgetCardBody locked={locked} lockedMessage={lockedMessage}>
+ {body}
+ </WidgetCardBody>
+ </WidgetCard>
+ )
+}
+
+const meta: Meta<typeof WidgetCardStory> = {
+ title: 'Dashboards/Dashboard Widgets/WidgetCard',
+ component: WidgetCardStory,
+ parameters: {
+ layout: 'padded',
+ },
+ decorators: widgetTileFrameDecorator,
+ args: {
+ placement: DashboardPlacement.Dashboard,
+ showEditingControls: false,
+ className: 'h-full',
+ headerLayout: 'dashboard_tile',
+ title: 'Sample metric',
+ topHeading: dashboardTileTopHeading,
+ },
+}
+
+export default meta
+
+type Story = StoryObj<typeof WidgetCardStory>
+
+export const DashboardTilePopulated: Story = {
+ args: {
+ headerLayout: 'dashboard_tile',
+ title: 'Sample metric',
+ topHeading: dashboardTileTopHeading,
+ description: 'A short description of what this widget shows on the dashboard.',
+ showDescription: true,
+ showEditingControls: true,
+ moreButtonOverlay: mockMoreOverlay,
+ body: sampleListBody,
+ },
+}
+
+export const SimpleHeaderLoading: Story = {
+ args: {
+ headerLayout: 'simple',
+ title: 'Custom metric',
+ loading: true,
+ body: <WidgetLoadingState />,
+ },
+}
+
+export const Locked: Story = {
+ args: {
+ title: 'Restricted widget',
+ locked: true,
+ lockedMessage: 'You need editor access to view this widget.',
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: 'Locked widgets show a centered lock icon with the access message in the body.',
+ },
+ },
+ },
+}
+
+export const EmptyBodyMessage: Story = {
+ args: {
+ body: (
+ <WidgetCardBodyMessage>
+ No data matches your filters. Adjust the date range or filters in widget settings.
+ </WidgetCardBodyMessage>
+ ),
+ },
+}
+
+export const SetupUnavailablePattern: Story = {
+ args: {
+ body: (
+ <WidgetCardBodyMessage>
+ <div className="flex max-w-sm flex-col items-center gap-2">
+ <div className="font-semibold text-primary">Enable this feature to use the widget</div>
+ <p className="m-0 text-muted">
+ Turn on the required product capability in project settings. See{' '}
+ <code>WidgetAvailabilitySetupPrompt</code> for the full gated UI (requires team logic).
+ </p>
+ </div>
+ </WidgetCardBodyMessage>
+ ),
+ },
+ parameters: {
+ docs: {
+ description: {
+ story: 'Catalog-driven setup uses `WidgetAvailabilitySetupPrompt` (Kea-backed). This story shows the centered body pattern only.',
+ },
+ },
+ },
+}
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCard.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCard.tsx
new file mode 100644
index 000000000000..27221ae15b51
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCard.tsx
@@ -0,0 +1,50 @@
+import clsx from 'clsx'
+import React from 'react'
+
+import 'lib/components/Cards/CardMeta.scss'
+import type { Resizeable } from 'lib/components/Cards/CardMeta'
+import { DashboardResizeHandles } from 'lib/components/Cards/handles'
+import { EditModeEdgeOverlay } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
+
+type WidgetCardProps = React.HTMLAttributes<HTMLDivElement> &
+ Resizeable & {
+ canEnterEditModeFromEdge?: boolean
+ onEnterEditModeFromEdge?: () => void
+ /** RGL-injected resize handle nodes — rendered after decorative handles (see InsightCard). */
+ gridChildren?: React.ReactNode
+ children?: React.ReactNode
+ }
+
+export const WidgetCard = React.forwardRef<HTMLDivElement, WidgetCardProps>(function WidgetCard(
+ {
+ showResizeHandles,
+ canEnterEditModeFromEdge,
+ onEnterEditModeFromEdge,
+ gridChildren,
+ children,
+ className,
+ style,
+ ...divProps
+ },
+ ref
+): JSX.Element {
+ return (
+ <div
+ data-slot="widget-card"
+ className={clsx(
+ 'DashboardTileCard WidgetCard dashboard-widget-card min-h-0 rounded flex flex-col bg-surface-primary border',
+ className
+ )}
+ {...divProps}
+ style={style}
+ ref={ref}
+ >
+ {children}
+ {showResizeHandles && <DashboardResizeHandles />}
+ {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
+ <EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
+ )}
+ {gridChildren}
+ </div>
+ )
+})
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.test.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.test.tsx
new file mode 100644
index 000000000000..b954c0575c5e
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.test.tsx
@@ -0,0 +1,86 @@
+import '@testing-library/jest-dom'
+
+import { render, screen } from '@testing-library/react'
+
+import { WidgetCardBody } from './WidgetCardBody'
+
+describe('WidgetCardBody', () => {
+ it('renders children', () => {
+ render(
+ <WidgetCardBody>
+ <div>Loaded content</div>
+ </WidgetCardBody>
+ )
+
+ expect(screen.getByText('Loaded content')).toBeInTheDocument()
+ })
+
+ it('renders locked message with lock icon instead of children', () => {
+ const { container } = render(
+ <WidgetCardBody locked>
+ <div>Hidden content</div>
+ </WidgetCardBody>
+ )
+
+ expect(screen.getByText('You do not have access to view this widget.')).toBeInTheDocument()
+ expect(container.querySelector('[data-attr="widget-card-body-locked"] svg')).toBeInTheDocument()
+ expect(screen.queryByText('Hidden content')).not.toBeInTheDocument()
+ })
+
+ it('renders error message instead of children', () => {
+ render(
+ <WidgetCardBody error="Something went wrong">
+ <div>Hidden content</div>
+ </WidgetCardBody>
+ )
+
+ expect(screen.getByText('Something went wrong')).toBeInTheDocument()
+ expect(screen.queryByText('Hidden content')).not.toBeInTheDocument()
+ })
+
+ it('renders refresh button on error when onRefresh is provided', async () => {
+ const onRefresh = jest.fn()
+ render(
+ <WidgetCardBody error="Something went wrong" onRefresh={onRefresh}>
+ <div>Hidden content</div>
+ </WidgetCardBody>
+ )
+
+ const refreshButton = screen.getByRole('button', { name: 'Refresh data' })
+ expect(refreshButton).toBeInTheDocument()
+ refreshButton.click()
+ expect(onRefresh).toHaveBeenCalledTimes(1)
+ })
+
+ it('centers locked message in the body', () => {
+ const { container } = render(
+ <WidgetCardBody locked>
+ <div>Hidden content</div>
+ </WidgetCardBody>
+ )
+
+ const messageContainer = container.querySelector('[data-slot="widget-card-body-message"]')
+ expect(messageContainer).toHaveClass('flex', 'min-h-full', 'items-center', 'justify-center', 'text-center')
+ })
+
+ it('declares a widget-card container for body layout queries', () => {
+ const { container } = render(
+ <WidgetCardBody>
+ <div>Loaded content</div>
+ </WidgetCardBody>
+ )
+
+ expect(container.firstChild).toHaveClass('@container/widget-card')
+ })
+
+ it('centers error message in the body', () => {
+ const { container } = render(
+ <WidgetCardBody error="Something went wrong">
+ <div>Hidden content</div>
+ </WidgetCardBody>
+ )
+
+ const messageContainer = container.querySelector('[data-slot="widget-card-body-message"]')
+ expect(messageContainer).toHaveClass('flex', 'min-h-full', 'items-center', 'justify-center', 'text-center')
+ })
+})
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.tsx
new file mode 100644
index 000000000000..e0717d68b379
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardBody.tsx
@@ -0,0 +1,212 @@
+import clsx from 'clsx'
+import React from 'react'
+
+import { IconLock } from '@posthog/icons'
+import { LemonSkeleton } from '@posthog/lemon-ui'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { cn } from 'lib/utils/css-classes'
+
+export type WidgetCardBodyProps = React.HTMLAttributes<HTMLDivElement> & {
+ locked?: boolean
+ lockedMessage?: string
+ error?: string | null
+ onRefresh?: () => void
+ refreshing?: boolean
+ children?: React.ReactNode
+}
+
+function WidgetCardBodyContent({
+ locked,
+ lockedMessage,
+ error,
+ onRefresh,
+ refreshing,
+ children,
+}: Pick<
+ WidgetCardBodyProps,
+ 'locked' | 'lockedMessage' | 'error' | 'onRefresh' | 'refreshing' | 'children'
+>): JSX.Element {
+ if (locked) {
+ return (
+ <WidgetCardBodySlot>
+ <WidgetCardContent>
+ <WidgetCardBodyMessage variant="locked">{lockedMessage}</WidgetCardBodyMessage>
+ </WidgetCardContent>
+ </WidgetCardBodySlot>
+ )
+ }
+
+ if (error) {
+ return (
+ <WidgetCardBodySlot>
+ <WidgetCardContent>
+ <WidgetCardBodyMessage variant="error" onRefresh={onRefresh} refreshing={refreshing}>
+ {error}
+ </WidgetCardBodyMessage>
+ </WidgetCardContent>
+ </WidgetCardBodySlot>
+ )
+ }
+
+ return <WidgetCardBodySlot>{children}</WidgetCardBodySlot>
+}
+
+export function WidgetCardBody({
+ locked,
+ lockedMessage = 'You do not have access to view this widget.',
+ error,
+ onRefresh,
+ refreshing = false,
+ children,
+ className,
+ ...divProps
+}: WidgetCardBodyProps): JSX.Element {
+ return (
+ <div
+ data-slot="widget-card-body"
+ className={clsx(
+ '@container/widget-card WidgetCard__body flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden p-4 pt-2',
+ className
+ )}
+ {...divProps}
+ >
+ <WidgetCardBodyContent
+ locked={locked}
+ lockedMessage={lockedMessage}
+ error={error}
+ onRefresh={onRefresh}
+ refreshing={refreshing}
+ >
+ {children}
+ </WidgetCardBodyContent>
+ </div>
+ )
+}
+
+/** Passes flex height from the card shell into widget body content. Scroll lives in `WidgetCardContent`. */
+function WidgetCardBodySlot({ children }: { children: React.ReactNode }): JSX.Element {
+ return <div className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden">{children}</div>
+}
+
+type WidgetCardBodyMessageProps = {
+ variant?: 'muted' | 'error' | 'locked'
+ onRefresh?: () => void
+ refreshing?: boolean
+ children: React.ReactNode
+}
+
+export function WidgetCardBodyMessage({
+ variant = 'muted',
+ onRefresh,
+ refreshing = false,
+ children,
+}: WidgetCardBodyMessageProps): JSX.Element {
+ let content: React.ReactNode = children
+
+ if (variant === 'locked') {
+ content = (
+ <div
+ className="flex max-w-xs flex-col items-center gap-2 px-2 text-balance"
+ data-attr="widget-card-body-locked"
+ >
+ <IconLock className="text-4xl text-muted" />
+ <span>{children}</span>
+ </div>
+ )
+ } else if (variant === 'error') {
+ content = (
+ <div
+ className="flex max-w-xs flex-col items-center gap-3 px-2 text-balance"
+ data-attr="widget-card-body-error"
+ >
+ <span>{children}</span>
+ {onRefresh ? (
+ <LemonButton
+ type="secondary"
+ size="small"
+ data-attr="widget-card-body-refresh"
+ loading={refreshing}
+ disabledReason={refreshing ? 'Refreshing…' : undefined}
+ onClick={onRefresh}
+ >
+ Refresh data
+ </LemonButton>
+ ) : null}
+ </div>
+ )
+ }
+
+ return (
+ <div
+ data-slot="widget-card-body-message"
+ className={clsx(
+ 'flex min-h-full w-full items-center justify-center text-center text-sm',
+ variant === 'error' ? 'text-danger' : 'text-muted'
+ )}
+ >
+ {content}
+ </div>
+ )
+}
+
+type WidgetCardBodySkeletonProps = {
+ rowCount?: number
+ className?: string
+}
+
+/** Generic skeleton rows for dashboard widget loading UI. Prefer wrapping in `WidgetLoadingState`. */
+export function WidgetCardBodySkeleton({ rowCount = 4, className }: WidgetCardBodySkeletonProps): JSX.Element {
+ return (
+ <div className={cn('flex flex-col gap-3', className)} aria-busy aria-label="Loading widget">
+ {Array.from({ length: rowCount }, (_, index) => (
+ <div key={index} className="flex flex-col gap-2" aria-hidden>
+ <LemonSkeleton className="h-4 w-[70%] max-w-md" />
+ <LemonSkeleton className="h-3 w-full max-w-lg" />
+ <LemonSkeleton className="h-3 w-[45%] max-w-xs" />
+ </div>
+ ))}
+ </div>
+ )
+}
+
+export type WidgetLoadingStateProps = {
+ /** Custom loading UI. When omitted, renders the generic body skeleton. */
+ children?: React.ReactNode
+ /** Row count for the generic skeleton when `children` is omitted. */
+ rowCount?: number
+ className?: string
+}
+
+/** Centers widget loading UI in the card body. Use from widget components while `loading` is true. */
+export function WidgetLoadingState({ children, rowCount, className }: WidgetLoadingStateProps): JSX.Element {
+ return (
+ <WidgetCardContent>
+ <div data-slot="widget-loading-state" className="flex min-h-min w-full items-center justify-center">
+ {children ?? (
+ <WidgetCardBodySkeleton rowCount={rowCount} className={clsx('w-full max-w-lg', className)} />
+ )}
+ </div>
+ </WidgetCardContent>
+ )
+}
+
+type WidgetCardContentProps = {
+ children: React.ReactNode
+ footer?: React.ReactNode
+ className?: string
+}
+
+/** Scrollable widget body — use for all tile content (lists, setup prompts, empty states). */
+export function WidgetCardContent({ children, footer, className }: WidgetCardContentProps): JSX.Element {
+ return (
+ <div data-slot="widget-card-content" className={clsx('flex min-h-0 min-w-0 flex-1 flex-col gap-2', className)}>
+ <div className="min-h-0 min-w-0 flex-1 overflow-auto">{children}</div>
+ {footer ? (
+ <div className="flex shrink-0 justify-center pt-0.5" data-slot="widget-card-content-footer">
+ {footer}
+ </div>
+ ) : null}
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.test.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.test.tsx
new file mode 100644
index 000000000000..32e309804b06
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.test.tsx
@@ -0,0 +1,161 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
+import { WidgetCardHeader } from './WidgetCardHeader'
+
+describe('WidgetCardHeader', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('renders dashboard_tile layout with top heading and title', () => {
+ const { container } = render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ topHeading={<span>Error tracking • Last 7 days</span>}
+ moreButtonOverlay={<div>Menu</div>}
+ />
+ )
+
+ expect(screen.getByText('Error tracking • Last 7 days')).toBeInTheDocument()
+ expect(container.querySelector('[data-attr="widget-card-title"]')).toHaveTextContent('Top issues')
+ expect(container.querySelector('.CardMeta--compact')).toBeTruthy()
+ expect(container.querySelector('.CardMeta__divider')).toBeTruthy()
+ })
+
+ it('derives top heading from catalog header meta', () => {
+ render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ widgetTypeLabel="Error tracking"
+ config={{ dateRange: { date_from: '-7d' } }}
+ headerMeta={{ showWidgetType: true, showDateRange: true }}
+ />
+ )
+
+ expect(screen.getByText('Error tracking')).toBeInTheDocument()
+ expect(screen.getByText('Last 7 days')).toBeInTheDocument()
+ })
+
+ it('derives date-only top heading when widget type is hidden', () => {
+ render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ widgetTypeLabel="Error tracking"
+ config={{ dateRange: { date_from: '-30d' } }}
+ headerMeta={{ showWidgetType: false, showDateRange: true }}
+ />
+ )
+
+ expect(screen.queryByText('Error tracking')).not.toBeInTheDocument()
+ expect(screen.getByText('Last 30 days')).toBeInTheDocument()
+ })
+
+ it('omits top heading when catalog meta hides both rows', () => {
+ render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ widgetTypeLabel="Error tracking"
+ config={{}}
+ headerMeta={{ showWidgetType: false, showDateRange: false }}
+ />
+ )
+
+ expect(screen.queryByText('Error tracking')).not.toBeInTheDocument()
+ expect(screen.queryByText('Last 7 days')).not.toBeInTheDocument()
+ })
+
+ it('links the title when titleHref is set', () => {
+ render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ titleHref="/error_tracking"
+ topHeading={<span>Error tracking • Last 7 days</span>}
+ />
+ )
+
+ expect(screen.getByRole('link', { name: /Top issues/i })).toHaveAttribute('href', '/error_tracking')
+ })
+
+ it('does not link the title in edit mode even when titleHref is set', () => {
+ render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ titleHref="/error_tracking"
+ showEditingControls
+ />
+ )
+
+ expect(screen.queryByRole('link', { name: /Top issues/i })).not.toBeInTheDocument()
+ expect(screen.getByText('Top issues')).toBeInTheDocument()
+ })
+
+ it('renders simple layout without inline refresh', () => {
+ const { container } = render(<WidgetCardHeader layout="simple" title="My widget" showEditingControls={false} />)
+
+ expect(container.querySelector('.WidgetCard__header h3')).toHaveTextContent('My widget')
+ expect(screen.queryByRole('button', { name: 'Refresh' })).not.toBeInTheDocument()
+ expect(container.querySelector('.CardMeta--compact')).toBeNull()
+ })
+
+ it('renders description in view mode when set', () => {
+ render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ description="Track the most common errors"
+ showEditingControls={false}
+ />
+ )
+
+ expect(screen.getByText('Track the most common errors')).toBeInTheDocument()
+ })
+
+ it('does not render description in view mode when empty', () => {
+ const { container } = render(
+ <WidgetCardHeader layout="dashboard_tile" title="Top issues" showEditingControls={false} />
+ )
+
+ expect(container.querySelector('.CardMeta__description')).toBeNull()
+ })
+
+ it('hides description when showDescription is false', () => {
+ const { container } = render(
+ <WidgetCardHeader
+ layout="dashboard_tile"
+ title="Top issues"
+ description="Track the most common errors"
+ showDescription={false}
+ showEditingControls
+ />
+ )
+
+ expect(container.querySelector('.CardMeta__description')).toBeNull()
+ })
+
+ it('renders default title without italic when custom title is empty', () => {
+ const { container } = render(
+ <WidgetCardHeader layout="dashboard_tile" title="" defaultTitle="Top issues" showEditingControls={false} />
+ )
+
+ expect(container.querySelector('[data-attr="widget-card-title"]')).toHaveTextContent('Top issues')
+ expect(container.querySelector('i')).toBeNull()
+ })
+
+ it('renders read-only default title in edit mode', () => {
+ const { container } = render(
+ <WidgetCardHeader layout="dashboard_tile" title="" defaultTitle="Top issues" showEditingControls />
+ )
+
+ expect(container.querySelector('[data-attr="widget-card-title"]')).toHaveTextContent('Top issues')
+ expect(container.querySelector('.EditableField')).toBeNull()
+ expect(container.querySelector('i')).toBeNull()
+ })
+})
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
new file mode 100644
index 000000000000..467295094da4
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeader.tsx
@@ -0,0 +1,281 @@
+import clsx from 'clsx'
+import React from 'react'
+
+import { CardMeta } from 'lib/components/Cards/CardMeta'
+import { CardTopHeadingRow } from 'lib/components/Cards/CardTopHeadingRow'
+import { More, MoreProps } from 'lib/lemon-ui/LemonButton/More'
+import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'
+import { Link } from 'lib/lemon-ui/Link'
+import { Spinner } from 'lib/lemon-ui/Spinner'
+import { dateFilterToText } from 'lib/utils'
+
+import { DashboardPlacement } from '~/types'
+
+import type { DashboardWidgetHeaderLayout, DashboardWidgetHeaderMeta } from '../../widget_types/catalog'
+
+export type WidgetCardHeaderProps = {
+ layout: DashboardWidgetHeaderLayout
+ title: string
+ defaultTitle?: string
+ titleHref?: string
+ /** Explicit top heading node — used by story fixtures. Otherwise derived from catalog fields below. */
+ topHeading?: React.ReactNode
+ widgetTypeLabel?: string
+ config?: Record<string, unknown>
+ headerMeta?: DashboardWidgetHeaderMeta
+ description?: string
+ showDescription?: boolean
+ loading?: boolean
+ showEditingControls?: boolean
+ shouldHideMoreButton?: boolean
+ moreButtonOverlay?: MoreProps['overlay']
+ onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
+}
+
+type WidgetCardHeaderTitleProps = {
+ title: string
+ defaultTitle?: string
+ titleHref?: string
+ loading?: boolean
+ showEditingControls?: boolean
+ headingLevel?: 'h3' | 'h4'
+ className?: string
+}
+
+function WidgetCardHeaderTitle({
+ title,
+ defaultTitle,
+ titleHref,
+ loading,
+ showEditingControls,
+ headingLevel = 'h4',
+ className,
+}: WidgetCardHeaderTitleProps): JSX.Element {
+ const displayTitle = title || defaultTitle || 'Untitled'
+ const Heading = headingLevel
+
+ const titleContent = (
+ <>
+ <span className={clsx('truncate', titleHref && !showEditingControls && 'text-primary')}>
+ {displayTitle}
+ </span>
+ {loading && (
+ <span className={clsx('text-sm font-medium ml-1.5', loading ? 'text-accent' : 'text-muted')}>
+ <Spinner className="mr-1.5 text-base" textColored />
+ Loading
+ </span>
+ )}
+ </>
+ )
+
+ const titleEl =
+ titleHref && !showEditingControls ? (
+ <Link to={titleHref} className="max-w-full truncate">
+ {titleContent}
+ </Link>
+ ) : (
+ titleContent
+ )
+
+ return (
+ <Heading
+ title={displayTitle}
+ data-attr="widget-card-title"
+ data-slot="widget-card-header-title"
+ className={clsx(
+ titleHref && !showEditingControls && 'inline-flex items-center overflow-visible',
+ headingLevel === 'h3' && 'truncate text-sm font-semibold m-0',
+ className
+ )}
+ >
+ {titleEl}
+ </Heading>
+ )
+}
+
+type WidgetCardHeaderDescriptionProps = {
+ description?: string
+ showDescription?: boolean
+ /** Compact CardMeta header — extra spacing above markdown description. */
+ compact?: boolean
+}
+
+export function WidgetCardHeaderDescription({
+ description,
+ showDescription = true,
+ compact = false,
+}: WidgetCardHeaderDescriptionProps): JSX.Element | null {
+ if (!showDescription || !description) {
+ return null
+ }
+
+ return (
+ <div
+ className={clsx(
+ 'min-w-0 max-h-24 w-full max-w-full self-stretch overflow-y-auto break-words [overflow-wrap:anywhere]',
+ compact && 'mt-1'
+ )}
+ data-slot="widget-card-header-description"
+ >
+ <LemonMarkdown className="CardMeta__description" lowKeyHeadings>
+ {description}
+ </LemonMarkdown>
+ </div>
+ )
+}
+
+type WidgetCardHeaderActionsProps = {
+ loading?: boolean
+ shouldHideMoreButton?: boolean
+ moreButtonOverlay?: MoreProps['overlay']
+ showLoadingSpinner?: boolean
+}
+
+function WidgetCardHeaderActions({
+ loading,
+ shouldHideMoreButton,
+ moreButtonOverlay,
+ showLoadingSpinner,
+}: WidgetCardHeaderActionsProps): JSX.Element {
+ return (
+ <div data-slot="widget-card-header-actions" className="flex items-center gap-1">
+ {showLoadingSpinner && loading && <Spinner />}
+ {!shouldHideMoreButton && moreButtonOverlay && <More overlay={moreButtonOverlay} />}
+ </div>
+ )
+}
+
+export function WidgetCardHeader({
+ layout,
+ title,
+ defaultTitle,
+ titleHref,
+ topHeading,
+ widgetTypeLabel,
+ config,
+ headerMeta,
+ description,
+ showDescription = true,
+ loading,
+ showEditingControls,
+ shouldHideMoreButton,
+ moreButtonOverlay,
+ onDragHandleMouseDown,
+}: WidgetCardHeaderProps): JSX.Element {
+ const showWidgetType = headerMeta?.showWidgetType ?? true
+ const showDateRange = headerMeta?.showDateRange ?? false
+ const dateText =
+ widgetTypeLabel && showDateRange
+ ? widgetDateRangeToText(config?.dateRange as Record<string, unknown> | null | undefined)
+ : null
+ const derivedTopHeading =
+ widgetTypeLabel && (showWidgetType || dateText) ? (
+ <CardTopHeadingRow typeLabel={widgetTypeLabel} showTypeLabel={showWidgetType} dateText={dateText} />
+ ) : null
+ const resolvedTopHeading = topHeading !== undefined ? topHeading : derivedTopHeading
+
+ const titleEl = (
+ <WidgetCardHeaderTitle
+ title={title}
+ defaultTitle={defaultTitle}
+ titleHref={titleHref}
+ loading={loading}
+ showEditingControls={showEditingControls}
+ headingLevel="h4"
+ />
+ )
+
+ const descriptionEl = (
+ <WidgetCardHeaderDescription
+ description={description}
+ showDescription={showDescription}
+ compact={layout === 'dashboard_tile'}
+ />
+ )
+
+ const actions = (
+ <WidgetCardHeaderActions
+ loading={loading}
+ shouldHideMoreButton={shouldHideMoreButton}
+ moreButtonOverlay={moreButtonOverlay}
+ showLoadingSpinner={layout === 'simple'}
+ />
+ )
+
+ if (layout === 'dashboard_tile') {
+ return (
+ <CardMeta
+ compact
+ className="WidgetCard__header rounded-b-none"
+ showEditingControls={!shouldHideMoreButton && !!moreButtonOverlay}
+ topHeading={(resolvedTopHeading as JSX.Element | null) ?? null}
+ onMouseDown={showEditingControls ? onDragHandleMouseDown : undefined}
+ moreButtons={moreButtonOverlay as JSX.Element | undefined}
+ content={
+ <>
+ {titleEl}
+ {descriptionEl}
+ </>
+ }
+ />
+ )
+ }
+
+ return (
+ <div
+ data-slot="widget-card-header"
+ className="WidgetCard__header flex flex-col p-4 pb-2 min-w-0 overflow-hidden"
+ >
+ <div className="flex flex-row items-center gap-2">
+ <div
+ className={clsx('drag-handle cursor-move flex-1 min-w-0', !showEditingControls && 'hidden')}
+ onMouseDown={onDragHandleMouseDown}
+ >
+ <WidgetCardHeaderTitle
+ title={title}
+ defaultTitle={defaultTitle}
+ titleHref={titleHref}
+ loading={loading}
+ showEditingControls={showEditingControls}
+ headingLevel="h3"
+ />
+ </div>
+ {!showEditingControls && (
+ <WidgetCardHeaderTitle
+ title={title}
+ defaultTitle={defaultTitle}
+ titleHref={titleHref}
+ loading={loading}
+ showEditingControls={showEditingControls}
+ headingLevel="h3"
+ className="flex-1"
+ />
+ )}
+ {actions}
+ </div>
+ {descriptionEl}
+ </div>
+ )
+}
+
+function widgetDateRangeToText(
+ dateRange: Record<string, unknown> | null | undefined,
+ defaultValue: string | null = 'Last 7 days'
+): string | null {
+ if (!dateRange || typeof dateRange !== 'object') {
+ return defaultValue
+ }
+
+ const dateFrom = 'date_from' in dateRange ? (dateRange.date_from as string | null | undefined) : undefined
+ const dateTo = 'date_to' in dateRange ? (dateRange.date_to as string | null | undefined) : undefined
+
+ if (!dateFrom && !dateTo) {
+ return defaultValue
+ }
+
+ return dateFilterToText(dateFrom, dateTo, defaultValue)
+}
+
+export function widgetCardShouldHideMoreButton(placement: DashboardPlacement, showEditingControls?: boolean): boolean {
+ return placement === DashboardPlacement.Public || showEditingControls === false
+}
diff --git a/products/dashboards/frontend/components/WidgetCard/WidgetCardHeaderDescription.test.tsx b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeaderDescription.test.tsx
new file mode 100644
index 000000000000..6436d07a26ec
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/WidgetCardHeaderDescription.test.tsx
@@ -0,0 +1,27 @@
+import '@testing-library/jest-dom'
+
+import { render, screen } from '@testing-library/react'
+
+import { WidgetCardHeaderDescription } from './WidgetCardHeader'
+
+describe('WidgetCardHeaderDescription', () => {
+ it('renders markdown when description is set and visible', () => {
+ render(<WidgetCardHeaderDescription description="Weekly error summary" showDescription />)
+
+ expect(screen.getByText('Weekly error summary')).toBeInTheDocument()
+ })
+
+ it('does not render when description is empty', () => {
+ const { container } = render(<WidgetCardHeaderDescription description="" showDescription />)
+
+ expect(container.querySelector('[data-slot="widget-card-header-description"]')).toBeNull()
+ })
+
+ it('does not render when description visibility is off', () => {
+ const { container } = render(
+ <WidgetCardHeaderDescription description="Hidden description" showDescription={false} />
+ )
+
+ expect(container.querySelector('[data-slot="widget-card-header-description"]')).toBeNull()
+ })
+})
diff --git a/products/dashboards/frontend/components/WidgetCard/index.ts b/products/dashboards/frontend/components/WidgetCard/index.ts
new file mode 100644
index 000000000000..bd7d0b2e9cb7
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/index.ts
@@ -0,0 +1,14 @@
+export { WidgetCard } from './WidgetCard'
+export {
+ WidgetCardBody,
+ WidgetCardBodyMessage,
+ WidgetCardBodySkeleton,
+ WidgetCardContent,
+ WidgetLoadingState,
+} from './WidgetCardBody'
+export {
+ WidgetCardHeader,
+ WidgetCardHeaderDescription,
+ type WidgetCardHeaderProps,
+ widgetCardShouldHideMoreButton,
+} from './WidgetCardHeader'
diff --git a/products/dashboards/frontend/components/WidgetCard/widgetCardStoryFixtures.tsx b/products/dashboards/frontend/components/WidgetCard/widgetCardStoryFixtures.tsx
new file mode 100644
index 000000000000..a74147a873ce
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCard/widgetCardStoryFixtures.tsx
@@ -0,0 +1,73 @@
+import React from 'react'
+
+import { CardTopHeadingRow } from 'lib/components/Cards/CardTopHeadingRow'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonMenuOverlay, type LemonMenuItems } from 'lib/lemon-ui/LemonMenu'
+
+import { WidgetCardContent } from './WidgetCardBody'
+
+export const TILE_WIDTH = 560
+export const TILE_HEIGHT = 480
+
+export function WidgetTileFrame({ children }: { children: React.ReactNode }): JSX.Element {
+ return (
+ <div
+ className="rounded border border-dashed border-border bg-bg-light p-4"
+ style={{ width: TILE_WIDTH, height: TILE_HEIGHT }}
+ >
+ <div className="h-full min-h-0">{children}</div>
+ </div>
+ )
+}
+
+export const widgetTileFrameDecorator = [
+ (Story: React.ComponentType): JSX.Element => (
+ <WidgetTileFrame>
+ <Story />
+ </WidgetTileFrame>
+ ),
+]
+
+/** Realistic dashboard widget ⋯ menu for Storybook — flat LemonMenu items, not bordered buttons. */
+export const mockWidgetMoreMenuItems: LemonMenuItems = [
+ { label: 'View', to: '/error_tracking' },
+ { label: 'Edit', onClick: () => undefined },
+ { label: 'Duplicate', onClick: () => undefined },
+ {
+ title: 'Dashboard',
+ items: [
+ { label: 'Hide description', onClick: () => undefined },
+ { label: 'Remove from dashboard', status: 'danger', onClick: () => undefined },
+ ],
+ },
+ { label: 'Refresh data', onClick: () => undefined },
+]
+
+export const mockMoreOverlay = <LemonMenuOverlay items={mockWidgetMoreMenuItems} />
+
+export const sampleListBody = (
+ <WidgetCardContent
+ footer={
+ <LemonButton type="secondary" size="small">
+ View all
+ </LemonButton>
+ }
+ >
+ <ul className="m-0 flex list-none flex-col gap-3 p-0 text-sm">
+ <li className="rounded border border-primary p-3">
+ <div className="font-semibold">Homepage visits</div>
+ <div className="text-muted">12,480 events · 3,210 users</div>
+ </li>
+ <li className="rounded border border-primary p-3">
+ <div className="font-semibold">Signup conversion</div>
+ <div className="text-muted">842 events · 612 users</div>
+ </li>
+ <li className="rounded border border-primary p-3">
+ <div className="font-semibold">Weekly active users</div>
+ <div className="text-muted">4,102 users · +8% vs last week</div>
+ </li>
+ </ul>
+ </WidgetCardContent>
+)
+
+export const dashboardTileTopHeading = <CardTopHeadingRow typeLabel="Analytics" showTypeLabel dateText="Last 7 days" />
diff --git a/products/dashboards/frontend/components/WidgetCardProductIntroduction/WidgetCardProductIntroduction.scss b/products/dashboards/frontend/components/WidgetCardProductIntroduction/WidgetCardProductIntroduction.scss
new file mode 100644
index 000000000000..b220cb77e60d
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCardProductIntroduction/WidgetCardProductIntroduction.scss
@@ -0,0 +1,49 @@
+// ProductIntroduction uses viewport `md:` breakpoints. Remap layout to the widget-card
+// container so setup prompts stack in narrow tiles and go horizontal when the tile is wide.
+.WidgetCardProductIntroduction {
+ [data-attr^='product-introduction'] > div {
+ flex-direction: column;
+ gap: 1rem;
+ align-items: center;
+
+ > div:first-child {
+ display: flex;
+ justify-content: center;
+ width: 100%;
+
+ > div {
+ margin-bottom: 1rem;
+
+ @container widget-card (min-width: 36rem) {
+ margin-bottom: 0;
+ }
+ }
+
+ @container widget-card (min-width: 36rem) {
+ width: auto;
+ }
+ }
+
+ > div:last-child {
+ width: 100%;
+ text-align: center;
+
+ > div:last-child {
+ justify-content: center;
+
+ @container widget-card (min-width: 36rem) {
+ justify-content: flex-start;
+ }
+ }
+
+ @container widget-card (min-width: 36rem) {
+ text-align: left;
+ }
+ }
+
+ @container widget-card (min-width: 36rem) {
+ flex-direction: row;
+ gap: 2rem;
+ }
+ }
+}
diff --git a/products/dashboards/frontend/components/WidgetCardProductIntroduction/WidgetCardProductIntroduction.tsx b/products/dashboards/frontend/components/WidgetCardProductIntroduction/WidgetCardProductIntroduction.tsx
new file mode 100644
index 000000000000..3ea80b532270
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetCardProductIntroduction/WidgetCardProductIntroduction.tsx
@@ -0,0 +1,30 @@
+import './WidgetCardProductIntroduction.scss'
+
+import {
+ ProductIntroduction,
+ type ProductIntroductionProps,
+} from 'lib/components/ProductIntroduction/ProductIntroduction'
+import { cn } from 'lib/utils/css-classes'
+
+type WidgetCardProductIntroductionProps = Omit<ProductIntroductionProps, 'hogLayout' | 'useMainContentContainerQueries'>
+
+/**
+ * ProductIntroduction tuned for dashboard widget tiles. WidgetCardBody defines
+ * `@container/widget-card`; the SCSS wrapper remaps responsive layout from viewport
+ * `md:` breakpoints to the widget-card container width.
+ */
+export function WidgetCardProductIntroduction({
+ className,
+ contentClassName,
+ ...props
+}: WidgetCardProductIntroductionProps): JSX.Element | null {
+ return (
+ <div className={cn('WidgetCardProductIntroduction', className)}>
+ <ProductIntroduction
+ {...props}
+ contentClassName={cn('max-w-none', contentClassName)}
+ hogLayout="responsive"
+ />
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/components/WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard.test.tsx b/products/dashboards/frontend/components/WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard.test.tsx
new file mode 100644
index 000000000000..5717ddb5d0b0
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard.test.tsx
@@ -0,0 +1,81 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+
+import { initKeaTests } from '~/test/init'
+
+import type { WidgetAvailabilityConfig } from '../../widget_types/widgetAvailability'
+import { WidgetRuntimeAvailabilityGuard } from './WidgetRuntimeAvailabilityGuard'
+
+const availability: WidgetAvailabilityConfig = {
+ requirement: 'exception_autocapture',
+ unavailableTitle: "You haven't captured any exceptions",
+ unavailableReason: 'Enable exception autocapture to get started.',
+ setupActionLabel: 'Enable exception autocapture',
+ docsHref: 'https://posthog.com/docs/error-tracking/installation',
+}
+
+describe('WidgetRuntimeAvailabilityGuard', () => {
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('renders children when the requirement is met', () => {
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, autocapture_exceptions_opt_in: true })
+
+ render(
+ <WidgetRuntimeAvailabilityGuard availability={availability}>
+ <div>Widget body</div>
+ </WidgetRuntimeAvailabilityGuard>
+ )
+
+ expect(screen.getByText('Widget body')).toBeInTheDocument()
+ expect(screen.queryByText("You haven't captured any exceptions")).not.toBeInTheDocument()
+ })
+
+ it('renders setup UI when the requirement is unmet', () => {
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, autocapture_exceptions_opt_in: false })
+
+ render(
+ <WidgetRuntimeAvailabilityGuard availability={availability}>
+ <div>Widget body</div>
+ </WidgetRuntimeAvailabilityGuard>
+ )
+
+ expect(screen.getByText("You haven't captured any exceptions")).toBeInTheDocument()
+ expect(screen.getByRole('link', { name: 'Enable exception autocapture' })).toBeInTheDocument()
+ expect(screen.queryByText('Widget body')).not.toBeInTheDocument()
+ })
+
+ it('renders children when no availability config is provided', () => {
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, autocapture_exceptions_opt_in: false })
+
+ render(
+ <WidgetRuntimeAvailabilityGuard availability={undefined}>
+ <div>Widget body</div>
+ </WidgetRuntimeAvailabilityGuard>
+ )
+
+ expect(screen.getByText('Widget body')).toBeInTheDocument()
+ })
+
+ it('uses a custom unavailableContentFallback when provided', () => {
+ initKeaTests(true, { ...MOCK_DEFAULT_TEAM, autocapture_exceptions_opt_in: false })
+
+ render(
+ <WidgetRuntimeAvailabilityGuard
+ availability={availability}
+ unavailableContentFallback={({ availability: config }) => (
+ <div>Custom setup for {config.requirement}</div>
+ )}
+ >
+ <div>Widget body</div>
+ </WidgetRuntimeAvailabilityGuard>
+ )
+
+ expect(screen.getByText('Custom setup for exception_autocapture')).toBeInTheDocument()
+ expect(screen.queryByText('Widget body')).not.toBeInTheDocument()
+ })
+})
diff --git a/products/dashboards/frontend/components/WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard.tsx b/products/dashboards/frontend/components/WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard.tsx
new file mode 100644
index 000000000000..1f8f0e75355c
--- /dev/null
+++ b/products/dashboards/frontend/components/WidgetRuntimeAvailabilityGuard/WidgetRuntimeAvailabilityGuard.tsx
@@ -0,0 +1,31 @@
+import type { ComponentType, ReactNode } from 'react'
+
+import type { WidgetAvailabilityConfig } from '../../widget_types/widgetAvailability'
+import { useWidgetAvailability } from '../../widget_types/widgetAvailability'
+import { WidgetAvailabilitySetupPrompt } from '../WidgetAvailabilitySetupPrompt/WidgetAvailabilitySetupPrompt'
+
+export type WidgetUnavailableContentFallbackProps = {
+ availability: WidgetAvailabilityConfig
+}
+
+type WidgetRuntimeAvailabilityGuardProps = {
+ availability: WidgetAvailabilityConfig | undefined
+ unavailableContentFallback?: ComponentType<WidgetUnavailableContentFallbackProps>
+ children: ReactNode
+}
+
+/** Shows catalog-driven setup UI when a widget requirement is unmet; otherwise renders children. */
+export function WidgetRuntimeAvailabilityGuard({
+ availability,
+ unavailableContentFallback,
+ children,
+}: WidgetRuntimeAvailabilityGuardProps): JSX.Element {
+ const { isAvailable, config } = useWidgetAvailability(availability)
+
+ if (isAvailable || !config) {
+ return <>{children}</>
+ }
+
+ const Fallback = unavailableContentFallback ?? WidgetAvailabilitySetupPrompt
+ return <Fallback availability={config} />
+}
diff --git a/products/dashboards/frontend/types.ts b/products/dashboards/frontend/types.ts
new file mode 100644
index 000000000000..dd03639ab5a3
--- /dev/null
+++ b/products/dashboards/frontend/types.ts
@@ -0,0 +1,4 @@
+/**
+ * Product RBAC for gated widget types. New types: extend union here — see products/dashboards/CONTRIBUTING.md.
+ */
+export type DashboardWidgetProductAccess = 'error_tracking'
diff --git a/products/dashboards/frontend/utils.ts b/products/dashboards/frontend/utils.ts
new file mode 100644
index 000000000000..f03140d9f8d4
--- /dev/null
+++ b/products/dashboards/frontend/utils.ts
@@ -0,0 +1,68 @@
+import type { DashboardTile, QueryBasedInsightModel } from '~/types'
+
+import { dashboardsPartialUpdate } from './generated/api'
+import type { PatchedDashboardApi } from './generated/api.schemas'
+
+export type WidgetFieldErrors = Record<string, string | undefined>
+
+export class WidgetConfigValidationError extends Error {
+ fieldErrors: WidgetFieldErrors
+
+ constructor(fieldErrors: WidgetFieldErrors) {
+ super('Widget config validation failed')
+ this.name = 'WidgetConfigValidationError'
+ this.fieldErrors = fieldErrors
+ }
+}
+
+export function isWidgetConfigValidationError(error: unknown): error is WidgetConfigValidationError {
+ return error instanceof WidgetConfigValidationError
+}
+
+export async function updateDashboardWidgetTile({
+ teamId,
+ dashboardId,
+ tile,
+ config,
+ name,
+ description,
+}: {
+ teamId: number
+ dashboardId: number
+ tile: DashboardTile<QueryBasedInsightModel>
+ config?: Record<string, unknown>
+ name?: string | null
+ description?: string
+}): Promise<DashboardTile<QueryBasedInsightModel>> {
+ if (!tile.widget) {
+ throw new Error('Tile has no widget')
+ }
+
+ const widgetPatch: Record<string, unknown> = {}
+ if (config !== undefined) {
+ widgetPatch.config = config
+ }
+ if (name !== undefined) {
+ widgetPatch.name = name || null
+ }
+ if (description !== undefined) {
+ widgetPatch.description = description
+ }
+
+ const dashboard = await dashboardsPartialUpdate(String(teamId), dashboardId, {
+ tiles: [
+ {
+ id: tile.id,
+ widget: {
+ id: tile.widget.id,
+ ...widgetPatch,
+ },
+ },
+ ],
+ } as PatchedDashboardApi)
+ const updatedTile = dashboard.tiles?.find((existingTile) => existingTile.id === tile.id)
+ if (!updatedTile) {
+ throw new Error('Updated tile not found in dashboard response')
+ }
+ return updatedTile as unknown as DashboardTile<QueryBasedInsightModel>
+}
diff --git a/products/dashboards/frontend/widgetProductAccess.ts b/products/dashboards/frontend/widgetProductAccess.ts
new file mode 100644
index 000000000000..61ef572a5401
--- /dev/null
+++ b/products/dashboards/frontend/widgetProductAccess.ts
@@ -0,0 +1,17 @@
+import { userHasAccess } from 'lib/utils/accessControlUtils'
+
+import { AccessControlLevel, AccessControlResourceType } from '~/types'
+
+import type { DashboardWidgetProductAccess } from './types'
+
+const WIDGET_PRODUCT_ACCESS_CHECKS = {
+ // New gated widget types: add a case here — CONTRIBUTING.md
+ error_tracking: () => userHasAccess(AccessControlResourceType.ErrorTracking, AccessControlLevel.Viewer),
+} satisfies Record<DashboardWidgetProductAccess, () => boolean>
+
+export function userHasDashboardWidgetProductAccess(productAccess: DashboardWidgetProductAccess | undefined): boolean {
+ if (!productAccess) {
+ return true
+ }
+ return WIDGET_PRODUCT_ACCESS_CHECKS[productAccess]()
+}
diff --git a/products/dashboards/frontend/widget_types/catalog.ts b/products/dashboards/frontend/widget_types/catalog.ts
new file mode 100644
index 000000000000..e25ea1be539c
--- /dev/null
+++ b/products/dashboards/frontend/widget_types/catalog.ts
@@ -0,0 +1,86 @@
+import type { DashboardWidgetProductAccess } from '../types'
+import type { WidgetAvailabilityConfig } from './widgetAvailability'
+
+export const DASHBOARD_WIDGET_HEADER_LAYOUTS = ['simple', 'dashboard_tile'] as const
+
+export type DashboardWidgetHeaderLayout = (typeof DASHBOARD_WIDGET_HEADER_LAYOUTS)[number]
+
+export type DashboardWidgetHeaderMeta = {
+ /** Show the widget type label in the compact top heading row (e.g. "Error tracking"). */
+ showWidgetType?: boolean
+ /** Show the configured date range in the compact top heading row (e.g. "Last 7 days"). */
+ showDateRange?: boolean
+}
+
+export type DashboardWidgetCatalogEntry = {
+ /** Stable key for grouping widgets from the same product area. */
+ groupId: string
+ /** Product area label shown as a section heading in the add-widget modal. */
+ groupLabel: string
+ /** Widget variant label within the group (also used as fallback card title). */
+ label: string
+ description: string
+ defaultConfig: Record<string, unknown>
+ defaultLayout: { w: number; h: number; minW: number; minH?: number }
+ productAccess?: DashboardWidgetProductAccess
+ headerLayout: DashboardWidgetHeaderLayout
+ headerMeta?: DashboardWidgetHeaderMeta
+ /** Title shown in the card header (defaults to `label`). */
+ headerTitle?: string
+ /** When set, the widget title links here on private dashboard placements for users with access. */
+ titleHref?: string
+ /** Optional project setup requirement surfaced in widget runtime when unmet (see `widgetAvailability.ts`). */
+ availability?: WidgetAvailabilityConfig
+}
+
+/** New widget types: add here. See products/dashboards/CONTRIBUTING.md. */
+export const DASHBOARD_WIDGET_CATALOG: Record<string, DashboardWidgetCatalogEntry> = {}
+
+export type DashboardWidgetCatalogKey = string
+
+/** New widget_type aliases: add here. See products/dashboards/CONTRIBUTING.md. */
+export const DASHBOARD_WIDGET_TYPE_ALIASES: Partial<Record<string, DashboardWidgetCatalogKey>> = {}
+
+/** New widget types: add preview components here. See products/dashboards/CONTRIBUTING.md. */
+export const DASHBOARD_WIDGET_PREVIEWS: Partial<Record<DashboardWidgetCatalogKey, () => JSX.Element>> = {}
+
+export function resolveDashboardWidgetCatalogKey(widgetType: string): DashboardWidgetCatalogKey | undefined {
+ if (widgetType in DASHBOARD_WIDGET_CATALOG) {
+ return widgetType
+ }
+ return DASHBOARD_WIDGET_TYPE_ALIASES[widgetType]
+}
+
+export function getDashboardWidgetCatalogEntry(widgetType: string): DashboardWidgetCatalogEntry | undefined {
+ return DASHBOARD_WIDGET_CATALOG[widgetType]
+}
+
+export type DashboardWidgetCatalogGroup = {
+ groupId: string
+ groupLabel: string
+ widgets: Array<{
+ widgetType: DashboardWidgetCatalogKey
+ entry: DashboardWidgetCatalogEntry
+ }>
+}
+
+function getDashboardWidgetCatalogGroups(): DashboardWidgetCatalogGroup[] {
+ const groupsById = new Map<string, DashboardWidgetCatalogGroup>()
+ const groupOrder: string[] = []
+
+ for (const [widgetType, entry] of Object.entries(DASHBOARD_WIDGET_CATALOG)) {
+ let group = groupsById.get(entry.groupId)
+
+ if (!group) {
+ group = { groupId: entry.groupId, groupLabel: entry.groupLabel, widgets: [] }
+ groupsById.set(entry.groupId, group)
+ groupOrder.push(entry.groupId)
+ }
+
+ group.widgets.push({ widgetType, entry })
+ }
+
+ return groupOrder.map((groupId) => groupsById.get(groupId)!)
+}
+
+export const DASHBOARD_WIDGET_CATALOG_GROUPS = getDashboardWidgetCatalogGroups()
diff --git a/products/dashboards/frontend/widget_types/configSchemas.ts b/products/dashboards/frontend/widget_types/configSchemas.ts
new file mode 100644
index 000000000000..927ae4d611f0
--- /dev/null
+++ b/products/dashboards/frontend/widget_types/configSchemas.ts
@@ -0,0 +1,57 @@
+import { z } from 'zod'
+
+/** Shared widget config fields inherited by all widget types. */
+export const baseWidgetConfigSchema = z.object({
+ filterTestAccounts: z.boolean().optional(),
+})
+
+export type BaseWidgetConfig = z.infer<typeof baseWidgetConfigSchema>
+
+export function resolveWidgetFilterTestAccounts(
+ configValue: boolean | undefined | null,
+ projectDefault: boolean
+): boolean {
+ return configValue ?? projectDefault
+}
+
+/** Relative `date_from` values allowed on dashboard widget configs (shortest first). */
+export const WIDGET_DATE_FROM_VALUES = ['-1h', '-3h', '-24h', '-7d', '-14d', '-30d', '-90d'] as const
+
+export type WidgetDateFromValue = (typeof WIDGET_DATE_FROM_VALUES)[number]
+
+export const widgetDateFromSchema = z.enum(WIDGET_DATE_FROM_VALUES, {
+ message: 'Select a supported date range.',
+})
+
+export const WIDGET_DATE_RANGE_SELECT_OPTIONS: { value: WidgetDateFromValue; label: string }[] = [
+ { value: '-1h', label: 'Last hour' },
+ { value: '-3h', label: 'Last 3 hours' },
+ { value: '-24h', label: 'Last 24 hours' },
+ { value: '-7d', label: 'Last 7 days' },
+ { value: '-14d', label: 'Last 14 days' },
+ { value: '-30d', label: 'Last 30 days' },
+ { value: '-90d', label: 'Last 90 days' },
+]
+
+const widgetDateRangeObjectSchema = z
+ .object({
+ date_from: widgetDateFromSchema.optional(),
+ date_to: z.string().optional(),
+ explicitDate: z.boolean().optional(),
+ })
+ .superRefine((value, ctx) => {
+ const hasDateFrom = value.date_from !== undefined
+ const hasDateTo = value.date_to !== undefined && value.date_to !== ''
+ const hasExplicitDate = value.explicitDate === true
+
+ if (!hasDateFrom && !hasDateTo && !hasExplicitDate) {
+ ctx.addIssue({
+ code: z.ZodIssueCode.custom,
+ message: 'Select a date range or enable explicit dates.',
+ })
+ }
+ })
+
+export const widgetDateRangeSchema = widgetDateRangeObjectSchema.optional()
+
+// New widget types: add per-type schemas here — CONTRIBUTING.md
diff --git a/products/dashboards/frontend/widget_types/widgetAvailability.test.ts b/products/dashboards/frontend/widget_types/widgetAvailability.test.ts
new file mode 100644
index 000000000000..d4adf5260191
--- /dev/null
+++ b/products/dashboards/frontend/widget_types/widgetAvailability.test.ts
@@ -0,0 +1,43 @@
+import { MOCK_DEFAULT_TEAM } from 'lib/api.mock'
+
+import type { WidgetAvailabilityConfig } from './widgetAvailability'
+import { getWidgetAvailabilityStatus, isWidgetAvailabilityRequirementMet } from './widgetAvailability'
+
+describe('widgetAvailability', () => {
+ it('treats widgets without availability config as available', () => {
+ expect(getWidgetAvailabilityStatus(undefined, MOCK_DEFAULT_TEAM)).toEqual({
+ isAvailable: true,
+ config: undefined,
+ })
+ })
+
+ it('evaluates exception_autocapture requirement', () => {
+ const availability: WidgetAvailabilityConfig = {
+ requirement: 'exception_autocapture',
+ unavailableTitle: "You haven't captured any exceptions",
+ unavailableReason: 'Enable exception autocapture to get started.',
+ setupActionLabel: 'Enable exception autocapture',
+ }
+
+ expect(
+ isWidgetAvailabilityRequirementMet('exception_autocapture', {
+ ...MOCK_DEFAULT_TEAM,
+ autocapture_exceptions_opt_in: false,
+ })
+ ).toBe(false)
+
+ expect(
+ isWidgetAvailabilityRequirementMet('exception_autocapture', {
+ ...MOCK_DEFAULT_TEAM,
+ autocapture_exceptions_opt_in: true,
+ })
+ ).toBe(true)
+
+ expect(
+ getWidgetAvailabilityStatus(availability, {
+ ...MOCK_DEFAULT_TEAM,
+ autocapture_exceptions_opt_in: false,
+ }).isAvailable
+ ).toBe(false)
+ })
+})
diff --git a/products/dashboards/frontend/widget_types/widgetAvailability.ts b/products/dashboards/frontend/widget_types/widgetAvailability.ts
new file mode 100644
index 000000000000..67d705b79549
--- /dev/null
+++ b/products/dashboards/frontend/widget_types/widgetAvailability.ts
@@ -0,0 +1,81 @@
+import { useValues } from 'kea'
+
+import { teamLogic } from 'scenes/teamLogic'
+import { urls } from 'scenes/urls'
+
+import { ProductKey } from '~/queries/schema/schema-general'
+import type { TeamPublicType, TeamType } from '~/types'
+
+/** New catalog-driven setup requirements: add here — CONTRIBUTING.md */
+export type WidgetAvailabilityRequirementId = 'exception_autocapture'
+
+export type WidgetAvailabilityPresentation = {
+ productName: string
+ productKey: ProductKey
+ thingName: string
+ settingsUrl: string
+}
+
+/** Presentation for setup prompts keyed by requirement id (single source of truth with catalog). */
+export const WIDGET_AVAILABILITY_PRESENTATION: Record<WidgetAvailabilityRequirementId, WidgetAvailabilityPresentation> =
+ {
+ // New requirements: add here — CONTRIBUTING.md
+ exception_autocapture: {
+ productName: 'Error tracking',
+ productKey: ProductKey.ERROR_TRACKING,
+ thingName: 'exception',
+ settingsUrl: urls.settings('environment-error-tracking', 'error-tracking-exception-autocapture'),
+ },
+ }
+
+export type WidgetAvailabilityConfig = {
+ /** Stable id evaluated by `widgetAvailability` helpers. */
+ requirement: WidgetAvailabilityRequirementId
+ /** Title shown in setup prompts when the requirement is unmet. */
+ unavailableTitle: string
+ /** Body copy shown in setup prompts when the requirement is unmet. */
+ unavailableReason: string
+ /** Primary setup CTA label. */
+ setupActionLabel: string
+ /** Optional docs link for a secondary CTA. */
+ docsHref?: string
+}
+
+export type WidgetAvailabilityStatus = {
+ isAvailable: boolean
+ config: WidgetAvailabilityConfig | undefined
+}
+
+export function isWidgetAvailabilityRequirementMet(
+ requirement: WidgetAvailabilityRequirementId,
+ team: TeamType | TeamPublicType | null
+): boolean {
+ switch (requirement) {
+ // New requirements: add a case here — CONTRIBUTING.md
+ case 'exception_autocapture':
+ return !!team?.autocapture_exceptions_opt_in
+ default: {
+ const _exhaustive: never = requirement
+ return _exhaustive
+ }
+ }
+}
+
+export function getWidgetAvailabilityStatus(
+ config: WidgetAvailabilityConfig | undefined,
+ team: TeamType | TeamPublicType | null
+): WidgetAvailabilityStatus {
+ if (!config) {
+ return { isAvailable: true, config: undefined }
+ }
+
+ return {
+ isAvailable: isWidgetAvailabilityRequirementMet(config.requirement, team),
+ config,
+ }
+}
+
+export function useWidgetAvailability(config: WidgetAvailabilityConfig | undefined): WidgetAvailabilityStatus {
+ const { currentTeam } = useValues(teamLogic)
+ return getWidgetAvailabilityStatus(config, currentTeam)
+}
diff --git a/products/dashboards/frontend/widgets/AddWidgetModal.tsx b/products/dashboards/frontend/widgets/AddWidgetModal.tsx
new file mode 100644
index 000000000000..81583f9e4170
--- /dev/null
+++ b/products/dashboards/frontend/widgets/AddWidgetModal.tsx
@@ -0,0 +1,125 @@
+import { useActions, useValues } from 'kea'
+import { Fragment } from 'react'
+
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
+
+import {
+ DASHBOARD_WIDGET_CATALOG_GROUPS,
+ DASHBOARD_WIDGET_PREVIEWS,
+ type DashboardWidgetCatalogEntry,
+ type DashboardWidgetCatalogKey,
+} from '../widget_types/catalog'
+import {
+ type AddWidgetPayload,
+ getAddButtonLabel,
+ getAddWidgetDisabledReason,
+ submitAddWidgetPayloads,
+} from './addWidgetModalUtils'
+import { WidgetTypePickerCard } from './WidgetTypePickerCard'
+
+export type { AddWidgetPayload }
+
+type AddWidgetModalProps = {
+ isOpen: boolean
+ onClose: () => void
+ loading?: boolean
+ onAdd: (payloads: AddWidgetPayload[]) => Promise<void>
+}
+
+type AddWidgetCatalogPickerProps = {
+ widgetType: DashboardWidgetCatalogKey
+ entry: DashboardWidgetCatalogEntry
+ selected: boolean
+ onToggleWidgetType: (widgetType: string) => void
+}
+
+function AddWidgetCatalogPicker({
+ widgetType,
+ entry,
+ selected,
+ onToggleWidgetType,
+}: AddWidgetCatalogPickerProps): JSX.Element {
+ const WidgetPreview = DASHBOARD_WIDGET_PREVIEWS[widgetType]
+
+ function handleSelect(): void {
+ onToggleWidgetType(widgetType)
+ }
+
+ return (
+ <WidgetTypePickerCard
+ label={entry.label}
+ description={entry.description}
+ selected={selected}
+ preview={WidgetPreview ? <WidgetPreview /> : <div />}
+ onSelect={handleSelect}
+ />
+ )
+}
+
+export function AddWidgetModal({ isOpen, onClose, loading, onAdd }: AddWidgetModalProps): JSX.Element {
+ const { addWidgetSelectedTypes } = useValues(dashboardLogic)
+ const { toggleAddWidgetSelectedType } = useActions(dashboardLogic)
+ const selectedTypes = new Set(addWidgetSelectedTypes)
+
+ const selectedCount = selectedTypes.size
+
+ function handleToggleWidgetType(widgetType: string): void {
+ toggleAddWidgetSelectedType(widgetType)
+ }
+
+ function handleAddWidgets(): void {
+ void submitAddWidgetPayloads(selectedTypes, onAdd, onClose)
+ }
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={onClose}
+ title="Add widget"
+ description="Bring context from your different PostHog products into one dashboard."
+ width={960}
+ footer={
+ <>
+ <div className="flex-1" />
+ <LemonButton type="secondary" onClick={onClose}>
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ loading={loading}
+ disabledReason={getAddWidgetDisabledReason(loading, selectedCount)}
+ onClick={handleAddWidgets}
+ >
+ {getAddButtonLabel(selectedCount)}
+ </LemonButton>
+ </>
+ }
+ >
+ <div className="@container/add-widget-modal">
+ <div
+ className="grid grid-cols-1 @min-[36rem]/add-widget-modal:grid-cols-2 gap-x-3 gap-y-4"
+ aria-label="Widget types"
+ >
+ {DASHBOARD_WIDGET_CATALOG_GROUPS.map((group, groupIndex) => (
+ <Fragment key={group.groupId}>
+ {groupIndex > 0 ? <LemonDivider className="col-span-full my-0" /> : null}
+ <h5 className="col-span-full mx-0 my-0">{group.groupLabel}</h5>
+ {group.widgets.map(({ widgetType, entry }) => (
+ <AddWidgetCatalogPicker
+ key={widgetType}
+ widgetType={widgetType}
+ entry={entry}
+ selected={selectedTypes.has(widgetType)}
+ onToggleWidgetType={handleToggleWidgetType}
+ />
+ ))}
+ </Fragment>
+ ))}
+ </div>
+ </div>
+ </LemonModal>
+ )
+}
diff --git a/products/dashboards/frontend/widgets/WidgetTypePickerCard.test.tsx b/products/dashboards/frontend/widgets/WidgetTypePickerCard.test.tsx
new file mode 100644
index 000000000000..c4b7d0f93dc1
--- /dev/null
+++ b/products/dashboards/frontend/widgets/WidgetTypePickerCard.test.tsx
@@ -0,0 +1,133 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+
+import { WidgetTypePickerCard } from './WidgetTypePickerCard'
+
+describe('WidgetTypePickerCard', () => {
+ afterEach(() => {
+ cleanup()
+ })
+ it('shows empty circle when unselected and check in filled circle when selected', () => {
+ const { rerender } = render(
+ <WidgetTypePickerCard
+ label="Error tracking"
+ description="Top issues"
+ selected={false}
+ preview={<div>Preview</div>}
+ onSelect={jest.fn()}
+ />
+ )
+
+ let checkbox = screen.getByRole('checkbox', { name: 'Error tracking' })
+ expect(checkbox).toHaveAttribute('aria-checked', 'false')
+
+ let indicator = checkbox.querySelector('[aria-hidden="true"]')
+ expect(indicator).toHaveClass('border-2')
+ expect(indicator?.querySelector('svg')).not.toBeInTheDocument()
+
+ rerender(
+ <WidgetTypePickerCard
+ label="Error tracking"
+ description="Top issues"
+ selected={true}
+ preview={<div>Preview</div>}
+ onSelect={jest.fn()}
+ />
+ )
+
+ checkbox = screen.getByRole('checkbox', { name: 'Error tracking' })
+ expect(checkbox).toHaveAttribute('aria-checked', 'true')
+ indicator = checkbox.querySelector('[aria-hidden="true"]')
+ expect(indicator?.querySelector('svg')).toBeInTheDocument()
+ })
+
+ it('deselects when clicking an already-selected card', async () => {
+ function TogglePicker(): JSX.Element {
+ const [selected, setSelected] = useState(true)
+
+ return (
+ <>
+ <WidgetTypePickerCard
+ label="Logs widget"
+ description="Recent log lines"
+ selected={selected}
+ preview={<div>Preview</div>}
+ onSelect={() => setSelected((current) => !current)}
+ />
+ <span data-attr="selected-state">{selected ? 'selected' : 'deselected'}</span>
+ </>
+ )
+ }
+
+ render(<TogglePicker />)
+
+ expect(screen.getByRole('checkbox', { name: 'Logs widget' })).toHaveAttribute('aria-checked', 'true')
+ expect(screen.getByTestId('selected-state')).toHaveTextContent('selected')
+
+ await userEvent.click(screen.getByRole('checkbox', { name: 'Logs widget' }))
+
+ expect(screen.getByRole('checkbox', { name: 'Logs widget' })).toHaveAttribute('aria-checked', 'false')
+ expect(screen.getByTestId('selected-state')).toHaveTextContent('deselected')
+ })
+
+ it('calls onSelect on click and keyboard activation', async () => {
+ const onSelect = jest.fn()
+ render(
+ <WidgetTypePickerCard
+ label="Logs widget"
+ description="Recent log lines"
+ selected={false}
+ preview={<div>Preview</div>}
+ onSelect={onSelect}
+ />
+ )
+
+ const checkbox = screen.getByRole('checkbox', { name: 'Logs widget' })
+ await userEvent.click(checkbox)
+ expect(onSelect).toHaveBeenCalledTimes(1)
+
+ checkbox.focus()
+ await userEvent.keyboard('{Enter}')
+ expect(onSelect).toHaveBeenCalledTimes(2)
+
+ await userEvent.keyboard(' ')
+ expect(onSelect).toHaveBeenCalledTimes(3)
+ })
+
+ it('selects card when clicking preview content', async () => {
+ const onSelect = jest.fn()
+ render(
+ <WidgetTypePickerCard
+ label="Error tracking"
+ description="Top issues"
+ selected={false}
+ preview={<div data-attr="preview-row">Preview row</div>}
+ onSelect={onSelect}
+ />
+ )
+
+ await userEvent.click(screen.getByTestId('preview-row'))
+
+ expect(onSelect).toHaveBeenCalledTimes(1)
+ })
+
+ it('marks preview content as non-interactive', () => {
+ render(
+ <WidgetTypePickerCard
+ label="Error tracking"
+ description="Top issues"
+ selected={false}
+ preview={<div data-attr="preview-content">Preview</div>}
+ onSelect={jest.fn()}
+ />
+ )
+
+ const previewWrapper = screen.getByTestId('preview-content').parentElement
+ expect(previewWrapper).toHaveClass('pointer-events-none')
+ expect(previewWrapper).toHaveClass('select-none')
+ expect(previewWrapper).toHaveAttribute('aria-hidden', 'true')
+ })
+})
diff --git a/products/dashboards/frontend/widgets/WidgetTypePickerCard.tsx b/products/dashboards/frontend/widgets/WidgetTypePickerCard.tsx
new file mode 100644
index 000000000000..e8fe5f0071c1
--- /dev/null
+++ b/products/dashboards/frontend/widgets/WidgetTypePickerCard.tsx
@@ -0,0 +1,63 @@
+import clsx from 'clsx'
+
+import { IconCheck } from '@posthog/icons'
+
+type WidgetTypePickerCardProps = {
+ label: string
+ description: string
+ selected: boolean
+ preview: JSX.Element
+ onSelect: () => void
+}
+
+function WidgetTypePickerSelectionIndicator({ selected }: { selected: boolean }): JSX.Element {
+ return (
+ <span
+ className={clsx(
+ 'flex shrink-0 items-center justify-center rounded-full size-5 transition-colors',
+ selected ? 'bg-accent text-primary-inverse' : 'border-2 border-primary bg-bg-light'
+ )}
+ aria-hidden
+ >
+ {selected ? <IconCheck className="size-3" /> : null}
+ </span>
+ )
+}
+
+export function WidgetTypePickerCard({
+ label,
+ description,
+ selected,
+ preview,
+ onSelect,
+}: WidgetTypePickerCardProps): JSX.Element {
+ return (
+ <div
+ role="checkbox"
+ aria-checked={selected}
+ aria-label={label}
+ tabIndex={0}
+ className={clsx(
+ 'text-left w-full rounded border p-3 transition-colors cursor-pointer',
+ 'focus:outline-none focus-visible:ring-2 focus-visible:ring-accent focus-visible:ring-offset-2',
+ selected ? 'border-accent bg-accent/5 ring-1 ring-accent' : 'border-primary hover:border-accent/40'
+ )}
+ onClick={onSelect}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' || e.key === ' ') {
+ e.preventDefault()
+ onSelect()
+ }
+ }}
+ >
+ <div className="flex items-center justify-between gap-2">
+ <div className="font-semibold">{label}</div>
+ <WidgetTypePickerSelectionIndicator selected={selected} />
+ </div>
+ <p className="text-xs text-muted m-0 mt-0.5 mb-2">{description}</p>
+ <div className="pointer-events-none select-none" aria-hidden="true">
+ {preview}
+ </div>
+ </div>
+ )
+}
diff --git a/products/dashboards/frontend/widgets/addWidgetModalUtils.ts b/products/dashboards/frontend/widgets/addWidgetModalUtils.ts
new file mode 100644
index 000000000000..c029a7e73b0e
--- /dev/null
+++ b/products/dashboards/frontend/widgets/addWidgetModalUtils.ts
@@ -0,0 +1,61 @@
+import { isReadOnly } from 'lib/readOnlyGuard'
+
+import { DASHBOARD_WIDGET_CATALOG, type DashboardWidgetCatalogKey } from '../widget_types/catalog'
+
+export type AddWidgetPayload = {
+ widgetType: string
+ config: Record<string, unknown>
+}
+
+export function getAddButtonLabel(selectedCount: number): string {
+ if (selectedCount <= 1) {
+ return 'Add widget'
+ }
+ return `Add ${selectedCount} widgets`
+}
+
+export function getAddWidgetDisabledReason(loading: boolean | undefined, selectedCount: number): string | undefined {
+ if (loading) {
+ return 'Adding widgets…'
+ }
+ if (isReadOnly()) {
+ return 'Read-only mode is on — allow writes temporarily to add widgets'
+ }
+ if (selectedCount === 0) {
+ return 'Select at least one widget type'
+ }
+ return undefined
+}
+
+export function buildAddWidgetPayloads(selectedTypes: Iterable<string>): AddWidgetPayload[] {
+ const payloads: AddWidgetPayload[] = []
+
+ for (const widgetType of selectedTypes) {
+ const catalogEntry = DASHBOARD_WIDGET_CATALOG[widgetType as DashboardWidgetCatalogKey]
+ if (!catalogEntry) {
+ continue
+ }
+ payloads.push({ widgetType, config: catalogEntry.defaultConfig })
+ }
+
+ return payloads
+}
+
+export async function submitAddWidgetPayloads(
+ selectedTypes: Set<string>,
+ onAdd: (payloads: AddWidgetPayload[]) => Promise<void>,
+ onClose: () => void
+): Promise<void> {
+ if (selectedTypes.size === 0) {
+ return
+ }
+
+ const payloads = buildAddWidgetPayloads(selectedTypes)
+ if (payloads.length === 0) {
+ return
+ }
+
+ // onAdd (dashboardLogic.addWidgetTiles) toasts and rethrows on failure — keep the modal open.
+ await onAdd(payloads)
+ onClose()
+}
diff --git a/products/dashboards/frontend/widgets/constants.ts b/products/dashboards/frontend/widgets/constants.ts
new file mode 100644
index 000000000000..8782e021ca4a
--- /dev/null
+++ b/products/dashboards/frontend/widgets/constants.ts
@@ -0,0 +1,20 @@
+/** Shown on the widget tile when run_widgets fails or returns a per-tile error. */
+export const DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE = 'Failed to load widget data.'
+
+const WIDGET_FETCH_ERROR_PASSTHROUGH_PREFIXES = [
+ 'Tile not found',
+ 'You do not have access',
+ 'Unknown widget type:',
+] as const
+
+export function getDashboardWidgetFetchDisplayError(error: string | null | undefined): string | null {
+ if (!error) {
+ return null
+ }
+
+ if (WIDGET_FETCH_ERROR_PASSTHROUGH_PREFIXES.some((prefix) => error.startsWith(prefix))) {
+ return error
+ }
+
+ return DASHBOARD_WIDGET_FETCH_ERROR_MESSAGE
+}
diff --git a/products/dashboards/frontend/widgets/registry.test.tsx b/products/dashboards/frontend/widgets/registry.test.tsx
new file mode 100644
index 000000000000..b1a060d9f1e8
--- /dev/null
+++ b/products/dashboards/frontend/widgets/registry.test.tsx
@@ -0,0 +1,55 @@
+import posthog from 'posthog-js'
+
+import { DASHBOARD_WIDGET_CATALOG } from '../widget_types/catalog'
+import { getDashboardWidgetDefinition } from './registry'
+import { resetDashboardWidgetRegistryReportingForTests } from './registry'
+
+jest.mock('posthog-js', () => ({
+ __esModule: true,
+ default: {
+ captureException: jest.fn(),
+ },
+}))
+
+describe('dashboard widget registry', () => {
+ beforeEach(() => {
+ jest.mocked(posthog.captureException).mockClear()
+ resetDashboardWidgetRegistryReportingForTests()
+ })
+
+ it('registers every catalog key', () => {
+ for (const key of Object.keys(DASHBOARD_WIDGET_CATALOG)) {
+ expect(getDashboardWidgetDefinition(key)).not.toBeUndefined()
+ }
+ })
+
+ it('reports unknown widget types to PostHog once per canonical type', () => {
+ expect(getDashboardWidgetDefinition('unknown_widget_type')).toBeUndefined()
+ expect(getDashboardWidgetDefinition('unknown_widget_type')).toBeUndefined()
+
+ expect(posthog.captureException).toHaveBeenCalledTimes(1)
+ expect(posthog.captureException).toHaveBeenCalledWith(
+ expect.objectContaining({
+ message: 'Dashboard widget type has no frontend registry implementation',
+ }),
+ expect.objectContaining({
+ feature: 'dashboard_widget',
+ widget_type: 'unknown_widget_type',
+ canonical_widget_type: 'unknown_widget_type',
+ has_catalog_entry: false,
+ })
+ )
+ })
+
+ it('includes tile context when provided', () => {
+ getDashboardWidgetDefinition('unknown_widget_type', { tileId: 42, dashboardId: 7 })
+
+ expect(posthog.captureException).toHaveBeenCalledWith(
+ expect.any(Error),
+ expect.objectContaining({
+ tile_id: 42,
+ dashboard_id: 7,
+ })
+ )
+ })
+})
diff --git a/products/dashboards/frontend/widgets/registry.tsx b/products/dashboards/frontend/widgets/registry.tsx
new file mode 100644
index 000000000000..6b3883f45b80
--- /dev/null
+++ b/products/dashboards/frontend/widgets/registry.tsx
@@ -0,0 +1,104 @@
+import posthog from 'posthog-js'
+import type { ComponentType } from 'react'
+
+import type { DashboardWidgetProductAccess } from '../types'
+import {
+ type DashboardWidgetCatalogKey,
+ DASHBOARD_WIDGET_TYPE_ALIASES,
+ getDashboardWidgetCatalogEntry,
+} from '../widget_types/catalog'
+import type { WidgetAvailabilityConfig } from '../widget_types/widgetAvailability'
+
+export type DashboardWidgetRegistryLookupContext = {
+ tileId?: number
+ dashboardId?: number
+}
+
+const reportedMissingRegistryEntries = new Set<string>()
+
+/** Test-only: clears dedupe state so missing-registry capture can be asserted per test. */
+export function resetDashboardWidgetRegistryReportingForTests(): void {
+ reportedMissingRegistryEntries.clear()
+}
+
+function reportMissingDashboardWidgetRegistryEntry(
+ widgetType: string,
+ canonicalType: string,
+ context?: DashboardWidgetRegistryLookupContext
+): void {
+ if (!widgetType.trim()) {
+ return
+ }
+
+ const hasCatalogEntry = getDashboardWidgetCatalogEntry(widgetType) !== undefined
+ const dedupeKey = `${canonicalType}:${hasCatalogEntry ? 'catalog' : 'none'}`
+ if (reportedMissingRegistryEntries.has(dedupeKey)) {
+ return
+ }
+ reportedMissingRegistryEntries.add(dedupeKey)
+
+ const message = hasCatalogEntry
+ ? 'Dashboard widget catalog entry has no matching frontend registry implementation'
+ : 'Dashboard widget type has no frontend registry implementation'
+
+ posthog.captureException(new Error(message), {
+ feature: 'dashboard_widget',
+ widget_type: widgetType,
+ canonical_widget_type: canonicalType,
+ has_catalog_entry: hasCatalogEntry,
+ tile_id: context?.tileId,
+ dashboard_id: context?.dashboardId,
+ })
+}
+
+export type DashboardWidgetDefinition = {
+ Component: ComponentType<DashboardWidgetComponentProps>
+ EditModal?: ComponentType<DashboardWidgetEditModalProps>
+ productAccess?: DashboardWidgetProductAccess
+ /** Fallback when catalog `availability` is unmet; defaults to `WidgetAvailabilitySetupPrompt`. */
+ unavailableContentFallback?: ComponentType<{ availability: WidgetAvailabilityConfig }>
+}
+
+export type DashboardWidgetComponentProps = {
+ tileId: number
+ config: Record<string, unknown>
+ result: unknown
+ loading: boolean
+ error?: string | null
+ onRefresh?: () => void
+ onUpdateConfig?: (config: Record<string, unknown>) => void | Promise<void>
+}
+
+export type DashboardWidgetEditModalProps = {
+ isOpen: boolean
+ onClose: () => void
+ config: Record<string, unknown>
+ onSave: (config: Record<string, unknown>) => void | Promise<void>
+ name?: string
+ defaultTitle?: string
+ description?: string
+ onSaveMetadata?: (metadata: { name?: string; description?: string }) => void | Promise<void>
+}
+
+/**
+ * New widget types: add here. See products/dashboards/CONTRIBUTING.md.
+ *
+ * `satisfies Record<DashboardWidgetCatalogKey, …>` fails typecheck if catalog grows without a matching key.
+ */
+export const DASHBOARD_WIDGET_REGISTRY: Record<string, DashboardWidgetDefinition> = {}
+
+function isDashboardWidgetRegistryKey(widgetType: string): widgetType is DashboardWidgetCatalogKey {
+ return widgetType in DASHBOARD_WIDGET_REGISTRY
+}
+
+export function getDashboardWidgetDefinition(
+ widgetType: string,
+ context?: DashboardWidgetRegistryLookupContext
+): DashboardWidgetDefinition | undefined {
+ const canonicalType = DASHBOARD_WIDGET_TYPE_ALIASES[widgetType] ?? widgetType
+ if (!isDashboardWidgetRegistryKey(canonicalType)) {
+ reportMissingDashboardWidgetRegistryEntry(widgetType, canonicalType, context)
+ return undefined
+ }
+ return DASHBOARD_WIDGET_REGISTRY[canonicalType]
+}
diff --git a/products/dashboards/package.json b/products/dashboards/package.json
index a6c8d9dad932..abed922431be 100644
--- a/products/dashboards/package.json
+++ b/products/dashboards/package.json
@@ -6,13 +6,28 @@
"dependencies": {
"kea": "catalog:",
"kea-loaders": "catalog:",
- "kea-router": "catalog:"
+ "kea-router": "catalog:",
+ "posthog-js": "catalog:"
+ },
+ "devDependencies": {
+ "@storybook/react": "^8.6.14",
+ "@testing-library/jest-dom": "^5.17.0",
+ "@testing-library/react": "^14.3.1",
+ "@testing-library/user-event": "^14.6.1",
+ "jest": "^29.7.0"
},
"peerDependencies": {
"@posthog/icons": "*",
+ "@storybook/react": "*",
+ "@testing-library/jest-dom": "*",
+ "@testing-library/react": "*",
+ "@testing-library/user-event": "*",
"@types/react": "*",
+ "@types/react-dom": "*",
"clsx": "*",
"fuse.js": "*",
- "react": "*"
+ "jest": "*",
+ "react": "*",
+ "react-dom": "*"
}
}