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 image tiles (#91958)

Matt Pua5292af7c2db2
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 8d212fb65b8f..861218b8b45f 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -5384,6 +5384,26 @@ snapshots:
hash: v1.k794b7964.15506e7ebede7d15231f8d94aaacf5476dc036a9813d0e27659f408dc1d6ad1d.IJN2vnAPYA2fmYKhLlvF1-iqrHCinD36ji0trpAgbps
products-dashboards-templates-dashboardtemplatemodal--full-json-editor--light:
hash: v1.k794b7964.34123ac547729bed64d24fc376be3136665bdbc176b2bfca1e72084534c89be8._KQHMBnLrhlHtCxzJdCShfU-fbmlZCtiXDRilu_ARss
+ products-dashboards-tiles-dashboard-image-tile--default--dark:
+ hash: v1.k794b7964.cf718e541ea2226a737073e84b44dc3104b03b8cbff226cb6d12255a6250a272.IWY_qAWP3JmmxhHU7siNrNEASqFQ5ffHr5Il_JiWioA
+ products-dashboards-tiles-dashboard-image-tile--default--light:
+ hash: v1.k794b7964.859f64dd437ad3103df066cb519919222b862589741dc97ff74bac86fe5c45ff.mFMuarxWJkWSugcRsfGIqg3IvTdMm64pRXTtZqqhtbg
+ products-dashboards-tiles-dashboard-image-tile--opaque-card--dark:
+ hash: v1.k794b7964.de3e292d4aa1534245054a441555c55c3c5fb3c9af5656e15b1a70d36c4b3522.cBRMoSa4yIIAy3X4OgiLErcgrv-QNEloPmOsZX03mzo
+ products-dashboards-tiles-dashboard-image-tile--opaque-card--light:
+ hash: v1.k794b7964.397b1c7903a22443b21d8660f81ce443234ec649bb775748c47fa47956c1a1c9.4r3zU_g75ZV9zATLQwt2uYtvGXrsmux--P7Lzov8UL8
+ products-dashboards-tiles-image-tile-modal--empty--dark:
+ hash: v1.k794b7964.5c49cf9eb7062c6dd77a03d7f7d7f552a51cd7d2d698c8a1f85def1d8395036c.B95sgLhXl5mTGCGEAD50-8NV289Wy6q-3-DEycNutD4
+ products-dashboards-tiles-image-tile-modal--empty--light:
+ hash: v1.k794b7964.26d5ac6151f28654e3ff448e8a5d869cf6d3edf7b97578a3497958547b0ed710.6hdq3gE-KlJ1wsVwKdzBPwBNyKzpwvDbcjjq6Ez9IyM
+ products-dashboards-tiles-image-tile-modal--existing-cover--dark:
+ hash: v1.k794b7964.0bc10d5c8131ebe8e5f8d68c17e55b7b8ca2370de4ca8f36c5ffd751d321017a.QVAeu6EpZspGSAQ8qy4fIBq5Ek-SvFAZhCUe6JgccvE
+ products-dashboards-tiles-image-tile-modal--existing-cover--light:
+ hash: v1.k794b7964.cac0ff14bd628afd54ff06b7e923d2b488113a21093f9b2449f14d9d86daecac.PBLJqdHZ37SZgOA9E-V2PX0FfoGKYmqAB5yzccDjGsA
+ products-dashboards-tiles-image-tile-modal--existing-image--dark:
+ hash: v1.k794b7964.20c015c66f2a8df4b13180fe46f6ad7d23c008014120d2333305338bfd473eaa.jN29SgNagj6AhlrI5b50krX4pQlMrOA5O7iYLuVMai4
+ products-dashboards-tiles-image-tile-modal--existing-image--light:
+ hash: v1.k794b7964.a6f0232a7044b1a581e4beb9105ee9c00bbed9748fdfcd1c3c1a232acfa0333c.D40_QysPPcg1v2fjLF3-6qPyFXkBZ9rrdYat6l6djGU
products-data-modeling-lineage-graph--canvas--dark:
hash: v1.k794b7964.cb415b8a2cb9697e353db5cd11808642c38d589431a0cb95cb1ddf632160eed8.ND20cRcJ3o2QK0K6DSbHBN66H2HwvcsKMd8tgfSITaY
products-data-modeling-lineage-graph--canvas--light:
diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx
index 86f97c99c405..2a4849b3df2b 100644
--- a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx
+++ b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCard.tsx
@@ -93,7 +93,7 @@ function ButtonTileCardInternal(
<div
className={clsx(
- 'ButtonTileCard__body flex w-full flex-1 p-4 items-center',
+ 'DashboardTileCard__body ButtonTileCard__body flex w-full flex-1 p-4 items-center',
!shouldHideMoreButton && 'pr-14',
button_tile.placement === 'right' ? 'md:justify-end' : 'justify-start',
onDragHandleMouseDown && 'cursor-grab'
diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx
index f9421fc7d3b8..0d930c81b156 100644
--- a/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx
+++ b/frontend/src/lib/components/Cards/ButtonTileCard/ButtonTileCardModal.tsx
@@ -9,7 +9,7 @@ import { LemonModal } from 'lib/lemon-ui/LemonModal'
import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
-import { DashboardPlacement, DashboardTile, DashboardType, QueryBasedInsightModel } from '~/types'
+import { DashboardPlacement, DashboardTile, DashboardTileIdOrNew, DashboardType, QueryBasedInsightModel } from '~/types'
export function ButtonTileCardModal({
isOpen,
@@ -20,9 +20,10 @@ export function ButtonTileCardModal({
isOpen: boolean
onClose: () => void
dashboard: DashboardType<QueryBasedInsightModel>
- buttonTileId: number | 'new' | null
+ buttonTileId: DashboardTileIdOrNew
}): JSX.Element {
- const modalLogic = buttonTileCardModalLogic({ dashboard, buttonTileId: buttonTileId ?? 'new', onClose })
+ const isNewTile = buttonTileId === null
+ const modalLogic = buttonTileCardModalLogic({ dashboard, buttonTileId, onClose })
const { buttonTile, isButtonTileSubmitting, buttonTileValidationErrors } = useValues(modalLogic)
const { submitButtonTile, resetButtonTile } = useActions(modalLogic)
@@ -33,7 +34,7 @@ export function ButtonTileCardModal({
const firstError = buttonTileValidationErrors.url || buttonTileValidationErrors.text
const previewTile: DashboardTile<QueryBasedInsightModel> = {
- id: buttonTileId === 'new' ? 0 : (buttonTileId ?? 0),
+ id: buttonTileId ?? 0,
color: null,
button_tile: { ...buttonTile, text: buttonTile.text || 'Click me' },
transparent_background: buttonTile.transparent_background,
@@ -43,7 +44,7 @@ export function ButtonTileCardModal({
<LemonModal
closable={true}
isOpen={isOpen}
- title={buttonTileId === 'new' ? 'Add link' : 'Edit link'}
+ title={isNewTile ? 'Add link' : 'Edit link'}
onClose={handleClose}
footer={
<>
@@ -61,7 +62,7 @@ export function ButtonTileCardModal({
htmlType="submit"
type="primary"
onClick={submitButtonTile}
- data-attr={buttonTileId === 'new' ? 'save-new-button-tile' : 'edit-button-tile'}
+ data-attr={isNewTile ? 'save-new-button-tile' : 'edit-button-tile'}
>
Save
</LemonButton>
diff --git a/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts b/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts
index 88cc58b33ce5..47d00e9b1edd 100644
--- a/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts
+++ b/frontend/src/lib/components/Cards/ButtonTileCard/buttonTileCardModalLogic.ts
@@ -6,7 +6,7 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { dashboardsModel } from '~/models/dashboardsModel'
-import { DashboardType, QueryBasedInsightModel } from '~/types'
+import { DashboardTileIdOrNew, DashboardType, QueryBasedInsightModel } from '~/types'
export interface ButtonTileForm {
url: string
@@ -18,7 +18,7 @@ export interface ButtonTileForm {
export interface ButtonTileCardModalProps {
dashboard: DashboardType<QueryBasedInsightModel>
- buttonTileId: number | 'new'
+ buttonTileId: DashboardTileIdOrNew
onClose: () => void
}
@@ -141,15 +141,15 @@ export const buttonTileCardModalLogic = kea<buttonTileCardModalLogicType>([
posthog.capture('dashboard button tile saved', {
dashboard_id: props.dashboard.id,
- button_tile_id: props.buttonTileId === 'new' ? null : props.buttonTileId,
- is_new: props.buttonTileId === 'new',
+ button_tile_id: props.buttonTileId,
+ is_new: props.buttonTileId === null,
url_type: buttonTile.url.startsWith('/') ? 'pathname' : 'full_url',
})
},
})),
forms(({ props, actions }) => ({
buttonTile: {
- defaults: (props.buttonTileId && props.buttonTileId !== 'new'
+ defaults: (props.buttonTileId !== null
? getExistingButtonTile(props.dashboard, props.buttonTileId)
: {
url: '',
@@ -178,7 +178,7 @@ export const buttonTileCardModalLogic = kea<buttonTileCardModalLogicType>([
transparent_background: t.transparent_background,
}))
- if (props.buttonTileId === 'new') {
+ if (props.buttonTileId === null) {
actions.updateDashboard({
id: props.dashboard.id,
tiles: [{ button_tile: buttonTileFields, transparent_background }],
diff --git a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
index 04eddd5bf460..678018bd63dc 100644
--- a/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
+++ b/frontend/src/lib/components/Cards/TextCard/TextCard.tsx
@@ -95,7 +95,6 @@ function TextCardInternal(
const shouldHideMoreButton = placement === DashboardPlacement.Public || showEditingControls === false
const isTransparent = textTile.transparent_background
-
return (
<div
className={clsx(
@@ -115,7 +114,10 @@ function TextCardInternal(
)}
<div
- className={clsx('TextCard__body w-full', onDragHandleMouseDown && 'cursor-grab')}
+ className={clsx(
+ 'DashboardTileCard__body TextCard__body w-full',
+ onDragHandleMouseDown && 'cursor-grab'
+ )}
onMouseDown={onDragHandleMouseDown}
>
<TextContent text={text.body} className={shouldHideMoreButton ? 'p-4' : 'p-4 pr-14'} />
diff --git a/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx b/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
index 0af89da63c6e..62421b2272f8 100644
--- a/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
+++ b/frontend/src/lib/components/Cards/TextCard/TextCardModal.tsx
@@ -5,12 +5,13 @@ import { useCallback, useState } from 'react'
import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { TextCardModalBodyField } from 'lib/components/Cards/TextCard/TextCardModalBodyField'
import { textCardModalLogic } from 'lib/components/Cards/TextCard/textCardModalLogic'
+import type { TextCardModalProps } from 'lib/components/Cards/TextCard/textCardModalLogic'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
import { DialogClose, DialogPrimitive, DialogPrimitiveTitle } from 'lib/ui/DialogPrimitive/DialogPrimitive'
import { cn } from 'lib/utils/css-classes'
-import { DashboardType, QueryBasedInsightModel } from '~/types'
+import { DashboardTileIdOrNew, DashboardType, QueryBasedInsightModel } from '~/types'
export function TextCardModal({
isOpen,
@@ -21,16 +22,16 @@ export function TextCardModal({
isOpen: boolean
onClose: () => void
dashboard: DashboardType<QueryBasedInsightModel>
- textTileId: number | 'new' | null
+ textTileId: DashboardTileIdOrNew
}): JSX.Element {
- const resolvedTileId = textTileId ?? 'new'
- const modalLogicProps = { dashboard, textTileId: resolvedTileId, onClose }
+ const isNewTile = textTileId === null
+ const modalLogicProps: TextCardModalProps = { dashboard, textTileId, onClose, tileType: 'text' }
const modalLogic = textCardModalLogic(modalLogicProps)
// Form `body` + validation drive updates while typing; splitting useValues does not reduce rerenders.
const { isTextTileSubmitting, textTileValidationErrors, textTile } = useValues(modalLogic)
const { resetTextTile } = useActions(modalLogic)
const [initialBody] = useState(() =>
- resolvedTileId !== 'new' ? dashboard.tiles?.find((tile) => tile.id === resolvedTileId)?.text?.body || '' : ''
+ textTileId !== null ? dashboard.tiles?.find((tile) => tile.id === textTileId)?.text?.body || '' : ''
)
const shouldUseLegacyMarkdownEditor = !textCardConverter.isRoundTripSafe(initialBody)
const hasUnsavedInput = (textTile?.body || '') !== initialBody
@@ -55,7 +56,7 @@ export function TextCardModal({
>
<div className="flex shrink-0 items-center justify-between gap-2 border-b border-primary py-2 pl-4 pr-2">
<DialogPrimitiveTitle className="min-w-0 flex-1 text-base font-semibold">
- {resolvedTileId === 'new' ? 'Add text card' : 'Edit text card'}
+ {isNewTile ? 'Add text card' : 'Edit text card'}
</DialogPrimitiveTitle>
<DialogClose className="shrink-0" />
</div>
@@ -105,7 +106,7 @@ export function TextCardModal({
form="text-tile-form"
htmlType="submit"
type="primary"
- data-attr={resolvedTileId === 'new' ? 'save-new-text-tile' : 'edit-text-tile-text'}
+ data-attr={isNewTile ? 'save-new-text-tile' : 'edit-text-tile-text'}
>
Save
</LemonButton>
diff --git a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
index 519d9d38b671..040b599c3cfa 100644
--- a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
+++ b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts
@@ -1,70 +1,26 @@
-import { Image } from '@tiptap/extension-image'
-
import {
MARKDOWN_BASE_EDITABLE_EXTENSIONS,
MARKDOWN_BASE_READONLY_EXTENSIONS,
} from 'lib/components/MarkdownEditor/shared/markdownExtensions'
import { createTiptapMarkdownConverter } from 'lib/utils/markdown'
-import { WordArtExtension } from './WordArt/WordArtExtension'
-
-function escapeHtmlAttribute(value: string): string {
- return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;')
-}
-
-const TextCardImageExtension = Image.extend({
- renderMarkdown(node) {
- const attrs = node.attrs || {}
- const src = attrs.src || ''
- const alt = attrs.alt || ''
- const title = attrs.title || ''
- const width = attrs.width
- const height = attrs.height
-
- if (!width && !height) {
- return title ? `![${alt}](${src} "${title}")` : `![${alt}](${src})`
- }
-
- const htmlAttrs = [
- `src="${escapeHtmlAttribute(String(src))}"`,
- `alt="${escapeHtmlAttribute(String(alt))}"`,
- ...(title ? [`title="${escapeHtmlAttribute(String(title))}"`] : []),
- ...(width ? [`width="${escapeHtmlAttribute(String(width))}"`] : []),
- ...(height ? [`height="${escapeHtmlAttribute(String(height))}"`] : []),
- ]
+import {
+ IMAGE_TILE_MARKDOWN_EDITABLE_EXTENSION,
+ IMAGE_TILE_MARKDOWN_READONLY_EXTENSION,
+} from 'products/dashboards/frontend/components/ImageTile/imageTileMarkdown'
- return `<img ${htmlAttrs.join(' ')} />`
- },
-})
+import { WordArtExtension } from './WordArt/WordArtExtension'
export const TEXT_CARD_MARKDOWN_EXTENSIONS = [
...MARKDOWN_BASE_EDITABLE_EXTENSIONS,
WordArtExtension,
- TextCardImageExtension.configure({
- HTMLAttributes: {
- draggable: 'true',
- },
- resize: {
- enabled: true,
- directions: ['top', 'bottom', 'left', 'right'],
- minWidth: 50,
- minHeight: 50,
- alwaysPreserveAspectRatio: true,
- },
- }),
+ IMAGE_TILE_MARKDOWN_EDITABLE_EXTENSION,
]
export const TEXT_CARD_MARKDOWN_READONLY_EXTENSIONS = [
...MARKDOWN_BASE_READONLY_EXTENSIONS,
WordArtExtension,
- TextCardImageExtension.configure({
- HTMLAttributes: {
- draggable: 'false',
- },
- resize: {
- enabled: false,
- },
- }),
+ IMAGE_TILE_MARKDOWN_READONLY_EXTENSION,
]
export const textCardConverter = createTiptapMarkdownConverter(TEXT_CARD_MARKDOWN_EXTENSIONS)
diff --git a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.test.ts b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.test.ts
index 3fcc133b740b..28535f9c9f0e 100644
--- a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.test.ts
+++ b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.test.ts
@@ -1,4 +1,5 @@
import { expectLogic } from 'kea-test-utils'
+import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
@@ -39,6 +40,7 @@ describe('textCardModalLogic', () => {
beforeEach(() => {
initKeaTests()
jest.spyOn(lemonToast, 'error').mockImplementation(jest.fn())
+ jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
})
afterEach(() => {
@@ -50,6 +52,7 @@ describe('textCardModalLogic', () => {
dashboard: makeDashboard('x'.repeat(4001)),
textTileId: 1,
onClose: jest.fn(),
+ tileType: 'text',
})
logic.mount()
@@ -65,8 +68,9 @@ describe('textCardModalLogic', () => {
it('rejects empty text card body in form validation', async () => {
const logic = textCardModalLogic({
dashboard: makeDashboard(''),
- textTileId: 'new',
+ textTileId: null,
onClose: jest.fn(),
+ tileType: 'text',
})
logic.mount()
@@ -79,11 +83,24 @@ describe('textCardModalLogic', () => {
expect(lemonToast.error).not.toHaveBeenCalled()
})
+ it('defaults new image tiles to a transparent background', () => {
+ const logic = textCardModalLogic({
+ dashboard: makeDashboard(),
+ textTileId: null,
+ onClose: jest.fn(),
+ tileType: 'image',
+ })
+ logic.mount()
+
+ expect(logic.values.textTile.transparent_background).toBe(true)
+ })
+
it('does not show toast for expected api body validation errors', () => {
const logic = textCardModalLogic({
dashboard: makeDashboard('valid'),
textTileId: 1,
onClose: jest.fn(),
+ tileType: 'text',
})
logic.mount()
@@ -103,6 +120,7 @@ describe('textCardModalLogic', () => {
dashboard: makeDashboard('valid'),
textTileId: 1,
onClose: jest.fn(),
+ tileType: 'text',
})
logic.mount()
@@ -116,4 +134,44 @@ describe('textCardModalLogic', () => {
expect(lemonToast.error).toHaveBeenCalledWith('Could not save text: Network error')
})
+
+ it('uses image wording for unexpected image tile save failures', () => {
+ const logic = textCardModalLogic({
+ dashboard: makeDashboard('![Image](https://example.com/image.png)'),
+ textTileId: 1,
+ onClose: jest.fn(),
+ tileType: 'image',
+ })
+ logic.mount()
+
+ logic.actions.submitTextTileFailure(
+ {
+ error: 'Network error',
+ errors: {},
+ } as any,
+ {}
+ )
+
+ expect(lemonToast.error).toHaveBeenCalledWith('Could not save image: Network error')
+ })
+
+ it.each([
+ ['image', '![Diagram](https://example.com/diagram.png)'],
+ ['text', 'Dashboard context'],
+ ])('reports %s content type when a text tile saves', (contentType, body) => {
+ const logic = textCardModalLogic({
+ dashboard: makeDashboard(),
+ textTileId: null,
+ onClose: jest.fn(),
+ tileType: 'text',
+ })
+ logic.mount()
+
+ logic.actions.submitTextTileSuccess({ body, transparent_background: false })
+
+ expect(posthog.capture).toHaveBeenCalledWith(
+ 'dashboard text tile saved',
+ expect.objectContaining({ content_type: contentType })
+ )
+ })
})
diff --git a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts
index 113472db2918..ead23c5f25e5 100644
--- a/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts
+++ b/frontend/src/lib/components/Cards/TextCard/textCardModalLogic.ts
@@ -6,17 +6,24 @@ import posthog from 'posthog-js'
import { lemonToast } from '@posthog/lemon-ui'
import { dashboardsModel } from '~/models/dashboardsModel'
-import { DashboardTile, DashboardType, QueryBasedInsightModel } from '~/types'
+import { DashboardTile, DashboardTileIdOrNew, DashboardType, QueryBasedInsightModel } from '~/types'
+
+import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'
+
+import { textCardConverter } from './textCardMarkdown'
export interface TextTileForm {
body: string
transparent_background: boolean
}
+export type TextCardTileType = 'text' | 'image'
+
export interface TextCardModalProps {
dashboard: DashboardType<QueryBasedInsightModel>
- textTileId: number | 'new'
+ textTileId: DashboardTileIdOrNew
onClose: () => void
+ tileType: TextCardTileType
}
const MAX_TEXT_CARD_BODY_LENGTH = 4000
@@ -100,7 +107,7 @@ export type textCardModalLogicType = MakeLogicType<
export const textCardModalLogic = kea<textCardModalLogicType>([
path(['scenes', 'dashboard', 'dashboardTextTileModal', 'logic']),
props({} as TextCardModalProps),
- key((props) => `textCardModalLogic-${props.dashboard.id}-${props.textTileId}`),
+ key((props) => `textCardModalLogic-${props.dashboard.id}-${props.textTileId}-${props.tileType}`),
connect(() => ({ actions: [dashboardsModel, ['updateDashboard']] })),
listeners(({ props, actions, values }) => ({
submitTextTileFailure: (error) => {
@@ -131,7 +138,7 @@ export const textCardModalLogic = kea<textCardModalLogicType>([
return
}
- lemonToast.error(`Could not save text: ${normalizedMessage}`)
+ lemonToast.error(`Could not save ${props.tileType}: ${normalizedMessage}`)
}
},
submitTextTileSuccess: ({ textTile }: { textTile: TextTileForm }) => {
@@ -140,17 +147,18 @@ export const textCardModalLogic = kea<textCardModalLogicType>([
posthog.capture('dashboard text tile saved', {
dashboard_id: props.dashboard.id,
- text_tile_id: props.textTileId === 'new' ? null : props.textTileId,
- is_new: props.textTileId === 'new',
+ text_tile_id: props.textTileId,
+ is_new: props.textTileId === null,
body_length: textTile.body.length,
+ content_type: getImageOnlyTextCardImage(textCardConverter, textTile.body) ? 'image' : 'text',
})
},
})),
forms(({ props, actions }) => ({
textTile: {
- defaults: (props.textTileId && props.textTileId !== 'new'
+ defaults: (props.textTileId !== null
? getExistingTextTile(props.dashboard, props.textTileId)
- : { body: '', transparent_background: false }) as TextTileForm,
+ : { body: '', transparent_background: props.tileType === 'image' }) as TextTileForm,
errors: ({ body }) => {
return {
body: !body.trim()
@@ -168,7 +176,7 @@ export const textCardModalLogic = kea<textCardModalLogicType>([
transparent_background: t.transparent_background,
}))
- if (props.textTileId === 'new') {
+ if (props.textTileId === null) {
actions.updateDashboard({
id: props.dashboard.id,
tiles: [
diff --git a/frontend/src/lib/hooks/useUploadFiles.test.ts b/frontend/src/lib/hooks/useUploadFiles.test.ts
new file mode 100644
index 000000000000..c3d6d748be44
--- /dev/null
+++ b/frontend/src/lib/hooks/useUploadFiles.test.ts
@@ -0,0 +1,53 @@
+import api from 'lib/api'
+
+import { uploadFile } from './useUploadFiles'
+
+const allowedMimeTypes = ['image/png']
+const maxSizeBytes = 4
+
+jest.mock('lib/api', () => ({
+ __esModule: true,
+ default: {
+ media: {
+ upload: jest.fn(),
+ },
+ },
+}))
+
+describe('uploadFile', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ })
+
+ it.each([['video/mp4', 'File is not an image']])('rejects %s before uploading', async (type, message) => {
+ await expect(
+ uploadFile(new File(['file'], 'file', { type }), {
+ allowedMimeTypes,
+ maxSizeBytes,
+ })
+ ).rejects.toThrow(message)
+ expect(api.media.upload).not.toHaveBeenCalled()
+ })
+
+ it('rejects an image format excluded by the caller', async () => {
+ await expect(
+ uploadFile(new File(['file'], 'file.svg', { type: 'image/svg+xml' }), {
+ allowedMimeTypes,
+ maxSizeBytes,
+ })
+ ).rejects.toThrow('This image format is not supported')
+ expect(api.media.upload).not.toHaveBeenCalled()
+ })
+
+ it('rejects an image larger than the configured upload limit before decoding', async () => {
+ const file = new File([new Uint8Array(maxSizeBytes + 1)], 'image.png', { type: 'image/png' })
+
+ await expect(
+ uploadFile(file, {
+ allowedMimeTypes,
+ maxSizeBytes,
+ })
+ ).rejects.toThrow('Image exceeds the maximum file size')
+ expect(api.media.upload).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/lib/hooks/useUploadFiles.ts b/frontend/src/lib/hooks/useUploadFiles.ts
index acd472c542fd..35d2a9e4fe24 100644
--- a/frontend/src/lib/hooks/useUploadFiles.ts
+++ b/frontend/src/lib/hooks/useUploadFiles.ts
@@ -1,7 +1,9 @@
import posthog from 'posthog-js'
import { useEffect, useRef, useState } from 'react'
+import type { Dispatch, SetStateAction } from 'react'
import api from 'lib/api'
+import { ApiError } from 'lib/api-error'
import { MediaUploadResponse } from '~/types'
@@ -71,16 +73,30 @@ function canReduceThisBlobType(file: File): boolean {
return supportedTypes.includes(file.type)
}
-export async function uploadFile(file: File): Promise<MediaUploadResponse> {
+export interface UploadFileOptions {
+ allowedMimeTypes?: readonly string[]
+ maxSizeBytes?: number
+}
+
+export async function uploadFile(file: File, options: UploadFileOptions = {}): Promise<MediaUploadResponse> {
if (!file.type.startsWith('image/')) {
throw new Error('File is not an image')
}
+ if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(file.type)) {
+ throw new Error('This image format is not supported')
+ }
+ if (options.maxSizeBytes !== undefined && file.size > options.maxSizeBytes) {
+ throw new Error('Image exceeds the maximum file size')
+ }
let fileToUpload = file
if (canReduceThisBlobType(file)) {
const compressedBlob = await lazyImageBlobReducer(file)
fileToUpload = new File([compressedBlob], file.name, { type: compressedBlob.type })
}
+ if (options.maxSizeBytes !== undefined && fileToUpload.size > options.maxSizeBytes) {
+ throw new Error('Image exceeds the maximum file size')
+ }
const formData = new FormData()
formData.append('image', fileToUpload)
@@ -90,41 +106,69 @@ export async function uploadFile(file: File): Promise<MediaUploadResponse> {
export function useUploadFiles({
onUpload,
onError,
+ uploadFileOptions,
}: {
onUpload?: (url: string, fileName: string, uploadedMediaId: string) => void
onError: (detail: string) => void
+ uploadFileOptions?: UploadFileOptions
}): {
- setFilesToUpload: (files: File[]) => void
+ setFilesToUpload: Dispatch<SetStateAction<File[]>>
filesToUpload: File[]
uploading: boolean
} {
const [uploading, setUploading] = useState(false)
const [filesToUpload, setFilesToUpload] = useState<File[]>([])
const uploadInProgressRef = useRef(false)
+ const isMountedRef = useRef(true)
+
+ useEffect(() => {
+ isMountedRef.current = true
+ return () => {
+ isMountedRef.current = false
+ }
+ }, [])
useEffect(() => {
const uploadFiles = async (): Promise<void> => {
- if (filesToUpload.length === 0 || uploadInProgressRef.current) {
+ if (filesToUpload.length === 0) {
setUploading(false)
return
}
+ if (uploadInProgressRef.current) {
+ return
+ }
+ const file = filesToUpload[0]
try {
uploadInProgressRef.current = true
setUploading(true)
- const file: File = filesToUpload[0]
- const media = await uploadFile(file)
- onUpload?.(media.image_location, media.name, media.id)
+ const media = await uploadFile(file, uploadFileOptions)
+ if (isMountedRef.current) {
+ onUpload?.(media.image_location, media.name, media.id)
+ }
} catch (error) {
- const errorDetail = (error as any).detail || 'unknown error'
- onError(errorDetail)
+ if (isMountedRef.current) {
+ let errorDetail = 'unknown error'
+ if (error instanceof ApiError && error.detail) {
+ errorDetail = error.detail
+ } else if (error instanceof Error && error.message) {
+ errorDetail = error.message
+ }
+ onError(errorDetail)
+ }
} finally {
uploadInProgressRef.current = false
- setUploading(false)
- setFilesToUpload([])
+ if (isMountedRef.current) {
+ setUploading(false)
+ setFilesToUpload((files) => files.filter((queuedFile) => queuedFile !== file))
+ }
}
}
- uploadFiles().catch(console.error)
+ uploadFiles().catch((error) => {
+ if (isMountedRef.current) {
+ console.error(error)
+ }
+ })
}, [filesToUpload]) // oxlint-disable-line react-hooks/exhaustive-deps
return { setFilesToUpload, filesToUpload, uploading }
diff --git a/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsx b/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsx
index d8b20842abad..157af97b3cdd 100644
--- a/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsx
+++ b/frontend/src/lib/lemon-ui/LemonFileInput/LemonFileInput.tsx
@@ -12,6 +12,7 @@ import { Spinner } from 'lib/lemon-ui/Spinner/Spinner'
export interface LemonFileInputProps extends Pick<HTMLInputElement, 'multiple' | 'accept'> {
value?: File[]
onChange?: (newValue: File[]) => void
+ inputRef?: RefObject<HTMLInputElement>
/**
* are the files currently being uploaded?
*/
@@ -43,18 +44,19 @@ export const LemonFileInput = ({
disabledReason,
// e.g. '.json' or 'image/*'
accept,
+ inputRef,
alternativeDropTargetRef,
callToAction,
showUploadedFiles = true,
}: LemonFileInputProps): JSX.Element => {
- const [files, setFiles] = useState(value || value || ([] as File[]))
+ const [files, setFiles] = useState(value || ([] as File[]))
// dragCounter and drag are used to track whether the user is dragging a file over the textarea
// without drag counter the textarea highlight would flicker when the user drags a file over it
let dragCounter = 0
const [drag, setDrag] = useState(false)
const dropRef = createRef<HTMLDivElement>()
- const fileInputRef = createRef<HTMLInputElement>()
+ const fileInputRef = inputRef ?? createRef<HTMLInputElement>()
useEffect(() => {
if (value && value !== files) {
@@ -90,6 +92,9 @@ export const LemonFileInput = ({
const handleDragIn = (e: DragEvent): void => {
e.preventDefault()
e.stopPropagation()
+ if (disabledReason) {
+ return
+ }
dragCounter++
if (e.dataTransfer?.items && e.dataTransfer.items.length > 0) {
setDrag(true)
@@ -108,6 +113,9 @@ export const LemonFileInput = ({
const handleDrop = (e: DragEvent): void => {
e.preventDefault()
e.stopPropagation()
+ if (disabledReason) {
+ return
+ }
setDrag(false)
if (e.dataTransfer?.files && e.dataTransfer.files.length > 0) {
const filesArr = Array.prototype.slice.call(e.dataTransfer?.files)
diff --git a/frontend/src/lib/utils/eventUsageLogic.ts b/frontend/src/lib/utils/eventUsageLogic.ts
index ad681016e51d..9b174979964f 100644
--- a/frontend/src/lib/utils/eventUsageLogic.ts
+++ b/frontend/src/lib/utils/eventUsageLogic.ts
@@ -9,7 +9,6 @@ import { TimeToSeeDataPayload } from 'lib/internalMetrics'
import { preflightLogic } from 'lib/logic/preflightLogic'
import { objectClean } from 'lib/utils/objects'
import { BillingUsageInteractionProps } from 'scenes/billing/types'
-import type { DashboardAddTileType } from 'scenes/dashboard/dashboardAddTileTypes'
import { SharedMetric } from 'scenes/experiments/SharedMetrics/sharedMetricLogic'
import type { SelfDrivingOnboardingStepId } from 'scenes/onboarding/onboardingEventUsageLogic'
import { ProductTourEvent } from 'scenes/product-tours/constants'
@@ -79,6 +78,8 @@ import {
SurveyQuestionType,
} from '~/types'
+import type { DashboardAddTileType } from 'products/dashboards/frontend/types'
+
import type { ExperimentMetricUnion } from '../../queries/schema/schema-general'
import type { FunnelCorrelationResultsType, Realm, UserType } from '../../types'
diff --git a/frontend/src/products.tsx b/frontend/src/products.tsx
index 0a388eda70a8..b06c4407a881 100644
--- a/frontend/src/products.tsx
+++ b/frontend/src/products.tsx
@@ -1128,10 +1128,7 @@ export const productUrls = {
dashboards: (): string => '/dashboard',
dashboard: (id: string | number, highlightInsightId?: string): string =>
combineUrl(`/dashboard/${id}`, highlightInsightId ? { highlightInsightId } : {}).url,
- dashboardTextTile: (id: string | number, textTileId: string | number): string =>
- `${urls.dashboard(id)}/text-tiles/${textTileId}`,
- dashboardButtonTile: (id: string | number, buttonTileId: string | number): string =>
- `${urls.dashboard(id)}/button-tiles/${buttonTileId}`,
+ dashboardTile: (id: string | number, tileId: string | number): string => `${urls.dashboard(id)}/tiles/${tileId}`,
dashboardSharing: (id: string | number): string => `/dashboard/${id}/sharing`,
dashboardSubscriptions: (id: string | number): string => `/dashboard/${id}/subscriptions`,
dashboardSubscription: (id: string | number, subscriptionId: string): string =>
diff --git a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
index f67388649a02..bc71448af151 100644
--- a/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
+++ b/frontend/src/scenes/dashboard/DashboardHeaderActions.tsx
@@ -25,16 +25,20 @@ import { DashboardLoadAction, dashboardLogic } from './dashboardLogic'
import { DashboardSubscribeButton } from './DashboardSubscribeButton'
export function getAddTileMenuItems({
- dashboardId,
dashboardWidgetsEnabled,
onAddInsight,
+ onAddText,
+ onAddImage,
+ onAddButton,
push,
setAddWidgetModalOpen,
onBeforeSelect,
}: {
- dashboardId: number
dashboardWidgetsEnabled: boolean
onAddInsight: () => void
+ onAddText: () => void
+ onAddImage: () => void
+ onAddButton: () => void
push: (url: string) => void
setAddWidgetModalOpen: (open: boolean) => void
onBeforeSelect?: () => void
@@ -54,12 +58,18 @@ export function getAddTileMenuItems({
},
{
label: 'Add text',
- onClick: withBeforeSelect(() => push(urls.dashboardTextTile(dashboardId, 'new'))),
+ onClick: withBeforeSelect(onAddText),
'data-attr': 'dashboard-add-text-tile',
},
+ {
+ label: 'Image',
+ tag: 'new' as const,
+ onClick: withBeforeSelect(onAddImage),
+ 'data-attr': 'dashboard-add-image-tile',
+ },
{
label: 'Button',
- onClick: withBeforeSelect(() => push(urls.dashboardButtonTile(dashboardId, 'new'))),
+ onClick: withBeforeSelect(onAddButton),
'data-attr': 'dashboard-add-button-tile',
},
dashboardWidgetsEnabled
@@ -83,8 +93,15 @@ export function getAddTileMenuItems({
export function DashboardAddTileButton(): JSX.Element | null {
const { dashboard, dashboardWidgetsEnabled, tiles } = useValues(dashboardLogic)
- const { loadDashboard, setAddWidgetModalOpen, setPendingInsertion, openAddInsightModal } =
- useActions(dashboardLogic)
+ const {
+ loadDashboard,
+ setAddWidgetModalOpen,
+ setPendingInsertion,
+ openAddInsightModal,
+ openTextTileModal,
+ openImageTileModal,
+ openButtonTileModal,
+ } = useActions(dashboardLogic)
const { push } = useActions(router)
const { reportDashboardAddMenuOpened } = useActions(eventUsageLogic)
@@ -119,9 +136,11 @@ export function DashboardAddTileButton(): JSX.Element | null {
>
<LemonMenu
items={getAddTileMenuItems({
- dashboardId: dashboard.id,
dashboardWidgetsEnabled,
onAddInsight: openAddInsightModal,
+ onAddText: openTextTileModal,
+ onAddImage: openImageTileModal,
+ onAddButton: openButtonTileModal,
push,
setAddWidgetModalOpen,
// Adding from the header appends at the bottom; drop any stale inline-insertion target.
diff --git a/frontend/src/scenes/dashboard/DashboardItems.scss b/frontend/src/scenes/dashboard/DashboardItems.scss
index 6458611076aa..2d8bcda06427 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.scss
+++ b/frontend/src/scenes/dashboard/DashboardItems.scss
@@ -64,9 +64,9 @@
.react-grid-item.react-draggable.DashboardTileCard {
.CardMeta,
- .TextCard__body,
- .ButtonTileCard__body,
- .WidgetCard__header {
+ .DashboardTileCard__body,
+ .WidgetCard__header,
+ .drag-handle {
// 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
diff --git a/frontend/src/scenes/dashboard/DashboardItems.test.tsx b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
index 9c092bb998fa..68a5a9d420e0 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.test.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.test.tsx
@@ -80,7 +80,7 @@ jest.mock('scenes/urls', () => ({
...jest.requireActual('scenes/urls'),
urls: {
...jest.requireActual('scenes/urls').urls,
- dashboardTextTile: () => '/dashboard/5/text/1',
+ dashboardTile: () => '/dashboard/5/tiles/1/text',
},
}))
@@ -114,7 +114,7 @@ jest.mock('lib/components/Cards/InsightCard', () => ({
},
}))
-jest.mock('./items/DashboardTextItem', () => ({
+jest.mock('products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem', () => ({
DashboardTextItem: ({ tile, showResizeHandles }: { tile: { id: number }; showResizeHandles: boolean }) => (
<div
data-attr="text-card"
diff --git a/frontend/src/scenes/dashboard/DashboardItems.tsx b/frontend/src/scenes/dashboard/DashboardItems.tsx
index 399f2f17ba4a..cb42b87097eb 100644
--- a/frontend/src/scenes/dashboard/DashboardItems.tsx
+++ b/frontend/src/scenes/dashboard/DashboardItems.tsx
@@ -38,11 +38,11 @@ import { getCurrentExporterData, isSharedView } from '~/exporter/exporterViewLog
import { insightsModel } from '~/models/insightsModel'
import { DashboardLayoutSize, DashboardMode, DashboardPlacement, DashboardType } from '~/types'
+import { DashboardTextItem } from 'products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem'
import { getDashboardTileSpacingGap } from 'products/dashboards/frontend/dashboardCustomization'
import { DashboardButtonTileItem } from './items/DashboardButtonTileItem'
import { DashboardErrorTileItem } from './items/DashboardErrorTileItem'
-import { DashboardTextItem } from './items/DashboardTextItem'
const DRAG_AUTO_SCROLL_THRESHOLD = 100
const DRAG_AUTO_SCROLL_SPEED = 50
@@ -122,6 +122,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
setDashboardMode,
setAddWidgetModalOpen,
setPendingInsertion,
+ openTextTileModal,
+ openImageTileModal,
+ openButtonTileModal,
} = useActions(dashboardLogic)
const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
const { updateWidgetTile } = useAsyncActions(dashboardLogic)
@@ -265,9 +268,11 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
(targetX: number, targetY: number, targetW?: number): LemonMenuItems =>
dashboard
? getAddTileMenuItems({
- dashboardId: dashboard.id,
dashboardWidgetsEnabled,
onAddInsight: showAddInsightToDashboardModal,
+ onAddText: openTextTileModal,
+ onAddImage: openImageTileModal,
+ onAddButton: openButtonTileModal,
push,
setAddWidgetModalOpen,
onBeforeSelect: () => setPendingInsertion({ x: targetX, y: targetY, w: targetW ?? null }),
@@ -280,6 +285,9 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
push,
setAddWidgetModalOpen,
setPendingInsertion,
+ openTextTileModal,
+ openImageTileModal,
+ openButtonTileModal,
]
)
@@ -293,7 +301,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
const dragConfig = useMemo(
() => ({
enabled: layoutEditMode && !isMobileView,
- handle: '.CardMeta,.TextCard__body,.ButtonTileCard__body,.WidgetCard__header,.drag-handle',
+ handle: '.CardMeta,.DashboardTileCard__body,.WidgetCard__header,.drag-handle',
cancel: 'a,table,button,input,.Popover',
bounded: true,
}),
@@ -625,7 +633,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
dashboardId={dashboard?.id}
onEdit={() => {
if (dashboard?.id) {
- push(urls.dashboardTextTile(dashboard.id, tile.id))
+ push(urls.dashboardTile(dashboard.id, tile.id))
}
}}
onMoveToDashboard={commonTileProps.moveToDashboard}
@@ -651,7 +659,7 @@ export function DashboardItems({ showCreateAnomalyAlertButton }: DashboardItemsP
isDraggingRef={isDragging}
onEdit={() => {
if (dashboard?.id) {
- push(urls.dashboardButtonTile(dashboard.id, tile.id))
+ push(urls.dashboardTile(dashboard.id, tile.id))
}
}}
onMoveToDashboard={commonTileProps.moveToDashboard}
diff --git a/frontend/src/scenes/dashboard/DashboardModals.test.tsx b/frontend/src/scenes/dashboard/DashboardModals.test.tsx
new file mode 100644
index 000000000000..3567c0687dfd
--- /dev/null
+++ b/frontend/src/scenes/dashboard/DashboardModals.test.tsx
@@ -0,0 +1,117 @@
+import { render } from '@testing-library/react'
+import { useActions, useValues } from 'kea'
+
+import type { DashboardType, QueryBasedInsightModel } from '~/types'
+
+import { dashboardLogic } from './dashboardLogic'
+import { DashboardModals } from './DashboardModals'
+
+jest.mock('kea', () => ({
+ useActions: jest.fn(),
+ useValues: jest.fn(),
+}))
+
+jest.mock('kea-router', () => ({
+ router: { __mock: 'router' },
+}))
+
+jest.mock('./dashboardLogic', () => ({
+ dashboardLogic: { __mock: 'dashboardLogic' },
+}))
+
+jest.mock('~/models/dashboardsModel', () => ({
+ dashboardsModel: { __mock: 'dashboardsModel' },
+}))
+
+jest.mock('scenes/userLogic', () => ({
+ userLogic: { __mock: 'userLogic' },
+}))
+
+jest.mock('@posthog/products-dashboards/frontend/widgets/AddWidgetModal', () => ({
+ AddWidgetModal: () => null,
+}))
+
+jest.mock('lib/components/Cards/ButtonTileCard/ButtonTileCardModal', () => ({
+ ButtonTileCardModal: () => null,
+}))
+
+jest.mock('lib/components/Cards/TextCard/TextCardModal', () => ({
+ TextCardModal: () => null,
+}))
+
+jest.mock('lib/components/Sharing/SharingModal', () => ({
+ SharingModal: () => null,
+}))
+
+jest.mock('lib/components/TerraformExporter/TerraformExportModal', () => ({
+ TerraformExportModal: () => null,
+}))
+
+jest.mock('products/dashboards/frontend/components/ImageTile/ImageTileModal', () => ({
+ ImageTileModal: () => null,
+}))
+
+jest.mock('products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal', () => ({
+ SubscriptionsModal: () => null,
+}))
+
+jest.mock('./DashboardInsightColorsModal', () => ({
+ DashboardInsightColorsModal: () => null,
+}))
+
+jest.mock('./DashboardTemplateEditor', () => ({
+ DashboardTemplateEditor: () => null,
+}))
+
+jest.mock('./DeleteDashboardModal', () => ({
+ DeleteDashboardModal: () => null,
+}))
+
+jest.mock('./DuplicateDashboardModal', () => ({
+ DuplicateDashboardModal: () => null,
+}))
+
+const mockedUseActions = useActions as jest.Mock
+const mockedUseValues = useValues as jest.Mock
+const push = jest.fn()
+
+describe('DashboardModals', () => {
+ beforeEach(() => {
+ jest.clearAllMocks()
+ mockedUseValues.mockImplementation((logic) => {
+ if (logic === dashboardLogic) {
+ return {
+ dashboardMode: null,
+ canEditDashboard: true,
+ showSubscriptions: false,
+ subscriptionId: null,
+ showTextTileModal: true,
+ textTileId: 999,
+ showImageTileModal: false,
+ showButtonTileModal: false,
+ buttonTileId: null,
+ terraformModalOpen: false,
+ addWidgetModalOpen: false,
+ dashboardWidgetsEnabled: false,
+ addWidgetTileLoading: false,
+ }
+ }
+ return { user: null }
+ })
+ mockedUseActions.mockImplementation(() => ({
+ push,
+ setTerraformModalOpen: jest.fn(),
+ setAddWidgetModalOpen: jest.fn(),
+ addWidgetTiles: jest.fn(),
+ updateDashboardSuccess: jest.fn(),
+ }))
+ })
+
+ it('returns to the dashboard when a tile route references a missing tile', () => {
+ const dashboard = { id: 5, tiles: [] } as unknown as DashboardType<QueryBasedInsightModel>
+
+ render(<DashboardModals dashboard={dashboard} />)
+
+ expect(push).toHaveBeenCalledWith('/dashboard/5')
+ })
+})
diff --git a/frontend/src/scenes/dashboard/DashboardModals.tsx b/frontend/src/scenes/dashboard/DashboardModals.tsx
index 0004807a8503..4c63820085b4 100644
--- a/frontend/src/scenes/dashboard/DashboardModals.tsx
+++ b/frontend/src/scenes/dashboard/DashboardModals.tsx
@@ -1,9 +1,11 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
+import { useEffect } from 'react'
import { AddWidgetModal } from '@posthog/products-dashboards/frontend/widgets/AddWidgetModal'
import { ButtonTileCardModal } from 'lib/components/Cards/ButtonTileCard/ButtonTileCardModal'
+import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { TextCardModal } from 'lib/components/Cards/TextCard/TextCardModal'
import { SharingModal } from 'lib/components/Sharing/SharingModal'
import { TerraformExportModal } from 'lib/components/TerraformExporter/TerraformExportModal'
@@ -13,6 +15,8 @@ import { userLogic } from 'scenes/userLogic'
import { dashboardsModel } from '~/models/dashboardsModel'
import { DashboardMode, DashboardType, QueryBasedInsightModel } from '~/types'
+import { ImageTileModal } from 'products/dashboards/frontend/components/ImageTile/ImageTileModal'
+import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'
import { SubscriptionsModal } from 'products/subscriptions/frontend/components/Subscriptions/SubscriptionsModal'
import { DashboardInsightColorsModal } from './DashboardInsightColorsModal'
@@ -29,6 +33,7 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType<QueryB
subscriptionId,
showTextTileModal,
textTileId,
+ showImageTileModal,
showButtonTileModal,
buttonTileId,
terraformModalOpen,
@@ -40,6 +45,23 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType<QueryB
const { updateDashboardSuccess } = useActions(dashboardsModel)
const { push } = useActions(router)
const { user } = useValues(userLogic)
+ const textRouteTile =
+ textTileId !== null ? dashboard.tiles?.find((tile) => tile.id === Number(textTileId)) : undefined
+ const isCreatingTextTile = textTileId === null
+ const textRouteHasImage =
+ !!textRouteTile?.text && !!getImageOnlyTextCardImage(textCardConverter, textRouteTile.text.body)
+ const buttonRouteTile =
+ buttonTileId !== null ? dashboard.tiles?.find((tile) => tile.id === Number(buttonTileId)) : undefined
+ const isCreatingButtonTile = buttonTileId === null
+ const selectedImageTileId = textRouteHasImage ? (textRouteTile?.id ?? null) : null
+ const shouldShowImageTileModal = showImageTileModal || selectedImageTileId !== null
+ const hasMissingRouteTile = (textTileId !== null && !textRouteTile) || (buttonTileId !== null && !buttonRouteTile)
+
+ useEffect(() => {
+ if (hasMissingRouteTile) {
+ push(urls.dashboard(dashboard.id))
+ }
+ }, [dashboard.id, hasMissingRouteTile, push])
return (
<>
@@ -60,14 +82,24 @@ export function DashboardModals({ dashboard }: { dashboard: DashboardType<QueryB
/>
{canEditDashboard && (
<>
- <TextCardModal
- isOpen={showTextTileModal}
- onClose={() => push(urls.dashboard(dashboard.id))}
- dashboard={dashboard}
- textTileId={textTileId}
- />
+ {shouldShowImageTileModal ? (
+ <ImageTileModal
+ key={selectedImageTileId ?? 'new'}
+ isOpen={shouldShowImageTileModal}
+ onClose={() => push(urls.dashboard(dashboard.id))}
+ dashboard={dashboard}
+ imageTileId={selectedImageTileId}
+ />
+ ) : (
+ <TextCardModal
+ isOpen={showTextTileModal && (isCreatingTextTile || !!textRouteTile?.text)}
+ onClose={() => push(urls.dashboard(dashboard.id))}
+ dashboard={dashboard}
+ textTileId={textTileId}
+ />
+ )}
<ButtonTileCardModal
- isOpen={showButtonTileModal}
+ isOpen={showButtonTileModal && (isCreatingButtonTile || !!buttonRouteTile?.button_tile)}
onClose={() => push(urls.dashboard(dashboard.id))}
dashboard={dashboard}
buttonTileId={buttonTileId}
diff --git a/frontend/src/scenes/dashboard/EmptyDashboardComponent.test.tsx b/frontend/src/scenes/dashboard/EmptyDashboardComponent.test.tsx
index 9bc224c2843f..c608f862d6e6 100644
--- a/frontend/src/scenes/dashboard/EmptyDashboardComponent.test.tsx
+++ b/frontend/src/scenes/dashboard/EmptyDashboardComponent.test.tsx
@@ -152,9 +152,11 @@ describe('EmptyDashboardComponent', () => {
expect(screen.getByText('Content')).toBeInTheDocument()
expect(screen.getByText('Charts')).toBeInTheDocument()
expect(screen.getByText('Add text')).toBeInTheDocument()
+ expect(screen.getByText('Image')).toBeInTheDocument()
expect(screen.getByText('Button')).toBeInTheDocument()
expect(screen.getByText('Widget')).toBeInTheDocument()
expect(screen.getByText('BETA')).toBeInTheDocument()
+ expect(screen.getAllByText('NEW')).toHaveLength(1)
logic.unmount()
})
@@ -165,7 +167,7 @@ describe('EmptyDashboardComponent', () => {
await openAddFirstChartDropdown()
expect(screen.getByText('Widget')).toBeInTheDocument()
- expect(screen.getByText('NEW')).toBeInTheDocument()
+ expect(screen.getAllByText('NEW')).toHaveLength(2)
logic.unmount()
})
diff --git a/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx b/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx
index 28b9f5f6dcfc..706916d98853 100644
--- a/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx
+++ b/frontend/src/scenes/dashboard/EmptyDashboardComponent.tsx
@@ -42,6 +42,9 @@ function DashboardEmptyActions({
aiDisabledReason,
dashboardWidgetsEnabled,
onAddInsight,
+ onAddText,
+ onAddImage,
+ onAddButton,
onAddWidget,
push,
onOpenAiWithPrompt,
@@ -52,6 +55,9 @@ function DashboardEmptyActions({
aiDisabledReason: string | false
dashboardWidgetsEnabled: boolean
onAddInsight: () => void
+ onAddText: () => void
+ onAddImage: () => void
+ onAddButton: () => void
onAddWidget: () => void
push: (path: string) => void
onOpenAiWithPrompt: (prompt: string) => void
@@ -99,9 +105,11 @@ function DashboardEmptyActions({
overlay: (
<LemonMenuOverlay
items={getAddTileMenuItems({
- dashboardId: dashboard.id,
dashboardWidgetsEnabled,
onAddInsight: handleAddInsight,
+ onAddText,
+ onAddImage,
+ onAddButton,
push,
setAddWidgetModalOpen: onAddWidget,
})}
@@ -132,7 +140,8 @@ function DashboardEmptyActions({
function EmptyDashboardContent({ canEdit }: { canEdit: boolean }): JSX.Element {
const { showAddInsightToDashboardModal } = useActions(addInsightToDashboardLogic)
const { dashboard, dashboardWidgetsEnabled } = useValues(dashboardLogic)
- const { setAddWidgetModalOpen } = useActions(dashboardLogic)
+ const { setAddWidgetModalOpen, openTextTileModal, openImageTileModal, openButtonTileModal } =
+ useActions(dashboardLogic)
const { push } = useActions(router)
const { openSidePanel } = useActions(sidePanelStateLogic)
const { dataProcessingAccepted, dataProcessingApprovalDisabledReason } = useValues(maxGlobalLogic)
@@ -174,6 +183,9 @@ function EmptyDashboardContent({ canEdit }: { canEdit: boolean }): JSX.Element {
aiDisabledReason={aiDisabledReason}
dashboardWidgetsEnabled={dashboardWidgetsEnabled}
onAddInsight={showAddInsightToDashboardModal}
+ onAddText={openTextTileModal}
+ onAddImage={openImageTileModal}
+ onAddButton={openButtonTileModal}
onAddWidget={() => setAddWidgetModalOpen(true)}
push={push}
onOpenAiWithPrompt={onOpenAiWithPrompt}
diff --git a/frontend/src/scenes/dashboard/dashboardAddTileTypes.ts b/frontend/src/scenes/dashboard/dashboardAddTileTypes.ts
deleted file mode 100644
index 6bd0e308cfde..000000000000
--- a/frontend/src/scenes/dashboard/dashboardAddTileTypes.ts
+++ /dev/null
@@ -1 +0,0 @@
-export type DashboardAddTileType = 'insight' | 'text_card' | 'button' | 'widget'
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.tsx b/frontend/src/scenes/dashboard/dashboardLogic.tsx
index e6e91b658748..cc55619d1f03 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.tsx
+++ b/frontend/src/scenes/dashboard/dashboardLogic.tsx
@@ -40,6 +40,7 @@ import {
import api, { ApiMethodOptions, getJSONOrNull } from 'lib/api'
import { ApiError, isAccessDeniedError } from 'lib/api-error'
import { DataColorTheme } from 'lib/colors'
+import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { OrganizationMembershipLevel } from 'lib/constants'
import { FEATURE_FLAGS } from 'lib/constants'
import { Dayjs, dayjs, now } from 'lib/dayjs'
@@ -102,6 +103,7 @@ import {
DashboardTemplateEditorType,
DashboardTile,
DashboardTileBasicType,
+ DashboardTileIdOrNew,
DashboardTileSpacing,
DashboardType,
DashboardWidgetType,
@@ -115,7 +117,9 @@ import {
TileLayout,
} from '~/types'
+import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'
import { DashboardGridCompaction } from 'products/dashboards/frontend/dashboardCustomization'
+import type { DashboardAddTileType } from 'products/dashboards/frontend/types'
import type { FeatureFlagsSet } from '../../lib/logic/featureFlagLogic'
import type { Node } from '../../queries/schema/schema-general'
@@ -209,6 +213,11 @@ export interface PendingInsertion {
w: number | null
}
+function parseDashboardTileId(tileId: string | undefined): DashboardTileIdOrNew {
+ const parsedTileId = Number(tileId)
+ return Number.isNaN(parsedTileId) ? null : parsedTileId
+}
+
const tileLayoutsFromDashboard = (
dashboard: DashboardType<QueryBasedInsightModel> | null | undefined
): Record<number, DashboardTile['layouts']> => {
@@ -272,7 +281,7 @@ export interface dashboardLogicValues {
blockRefresh: boolean
breadcrumbs: Breadcrumb[]
breakdownValuesIncomplete: boolean
- buttonTileId: number | 'new' | null
+ buttonTileId: DashboardTileIdOrNew
canAutoPreview: boolean
canEditDashboard: boolean
canRestrictDashboard: boolean
@@ -354,6 +363,7 @@ export interface dashboardLogicValues {
shouldUseStreaming: boolean
showApplyFiltersBanner: boolean
showButtonTileModal: boolean
+ showImageTileModal: boolean
showRetentionBanner: boolean
showSubscriptions: boolean
showTextTileModal: boolean
@@ -366,7 +376,7 @@ export interface dashboardLogicValues {
themeId: number | null
} | null
terraformModalOpen: boolean
- textTileId: number | 'new' | null
+ textTileId: DashboardTileIdOrNew
textTiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[]
tiles: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>[]
urlFilters: DashboardFilter
@@ -599,6 +609,15 @@ export interface dashboardLogicActions {
openAddInsightModal: () => {
value: true
}
+ openButtonTileModal: () => {
+ value: true
+ }
+ openImageTileModal: () => {
+ value: true
+ }
+ openTextTileModal: () => {
+ value: true
+ }
overrideVariableValue: (
variableId: string,
value: any,
@@ -729,8 +748,8 @@ export interface dashboardLogicActions {
setBreakdownFilter: (breakdown_filter: BreakdownFilter | null) => {
breakdown_filter: BreakdownFilter | null
}
- setButtonTileId: (buttonTileId: number | 'new' | null) => {
- buttonTileId: number | 'new' | null
+ setButtonTileId: (buttonTileId: DashboardTileIdOrNew) => {
+ buttonTileId: DashboardTileIdOrNew
}
setDashboardCustomizeMenuOpen: (open: boolean) => {
open: boolean
@@ -857,8 +876,8 @@ export interface dashboardLogicActions {
setTerraformModalOpen: (open: boolean) => {
open: boolean
}
- setTextTileId: (textTileId: number | 'new' | null) => {
- textTileId: number | 'new' | null
+ setTextTileId: (textTileId: DashboardTileIdOrNew) => {
+ textTileId: DashboardTileIdOrNew
}
setTileOverride: (tile: DashboardTile<QueryBasedInsightModel>) => {
tile: DashboardTile<QueryBasedInsightModel<Node<Record<string, any>>>>
@@ -1404,9 +1423,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
toDashboard,
toDashboardName,
}),
- setTextTileId: (textTileId: number | 'new' | null) => ({ textTileId }),
- setButtonTileId: (buttonTileId: number | 'new' | null) => ({ buttonTileId }),
+ setTextTileId: (textTileId: DashboardTileIdOrNew) => ({ textTileId }),
+ setButtonTileId: (buttonTileId: DashboardTileIdOrNew) => ({ buttonTileId }),
openAddInsightModal: true,
+ openTextTileModal: true,
+ openImageTileModal: true,
+ openButtonTileModal: true,
setTileOverride: (tile: DashboardTile<QueryBasedInsightModel>) => ({ tile }),
/**
@@ -2289,12 +2311,21 @@ export const dashboardLogic = kea<dashboardLogicType>([
false,
{
setTextTileId: (_, { textTileId }) => !!textTileId,
+ openTextTileModal: () => true,
+ },
+ ],
+ showImageTileModal: [
+ false,
+ {
+ openImageTileModal: () => true,
+ setTextTileId: () => false,
},
],
textTileId: [
- null as number | 'new' | null,
+ null as DashboardTileIdOrNew,
{
setTextTileId: (_, { textTileId }) => textTileId,
+ openTextTileModal: () => null,
},
],
@@ -2302,12 +2333,14 @@ export const dashboardLogic = kea<dashboardLogicType>([
false,
{
setButtonTileId: (_, { buttonTileId }) => !!buttonTileId,
+ openButtonTileModal: () => true,
},
],
buttonTileId: [
- null as number | 'new' | null,
+ null as DashboardTileIdOrNew,
{
setButtonTileId: (_, { buttonTileId }) => buttonTileId,
+ openButtonTileModal: () => null,
},
],
@@ -3423,13 +3456,18 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.updateLayouts({ ...values.layouts, sm: newSmLayout })
// The inline insert has now landed at the line — report it (outcome, vs the option-clicked intent).
- const insertedTileType = newTile.text
- ? 'text_card'
- : newTile.button_tile
- ? 'button'
- : newTile.widget
- ? 'widget'
- : 'insight'
+ const insertedTileType = (() => {
+ switch (getDashboardWidgetType(newTile)) {
+ case 'text':
+ return getImageOnlyTextCardImage(textCardConverter, newTile.text!.body) ? 'image' : 'text_card'
+ case 'button_tile':
+ return 'button'
+ case 'widget':
+ return 'widget'
+ case 'insight':
+ return 'insight'
+ }
+ })() satisfies DashboardAddTileType
eventUsageLogic.actions.reportDashboardTileInsertedInline(
insertedTileType,
props.id,
@@ -4958,13 +4996,24 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.setDashboardMode(null, DashboardEventSource.Browser)
},
- '/dashboard/:id': () => {
+ '/dashboard/:id': (_params, searchParams) => {
actions.setSubscriptionMode(false, undefined)
actions.setTextTileId(null)
actions.setButtonTileId(null)
if (values.dashboardMode === DashboardMode.Sharing) {
actions.setDashboardMode(null, DashboardEventSource.Browser)
}
+ switch (searchParams.tileType) {
+ case 'text':
+ actions.openTextTileModal()
+ break
+ case 'image':
+ actions.openImageTileModal()
+ break
+ case 'button':
+ actions.openButtonTileModal()
+ break
+ }
},
'/dashboard/:id/sharing': () => {
actions.setSubscriptionMode(false, undefined)
@@ -4972,19 +5021,12 @@ export const dashboardLogic = kea<dashboardLogicType>([
actions.setButtonTileId(null)
actions.setDashboardMode(DashboardMode.Sharing, DashboardEventSource.Browser)
},
- '/dashboard/:id/text-tiles/:textTileId': ({ textTileId }) => {
+ '/dashboard/:id/tiles/:tileId': ({ tileId }) => {
actions.setSubscriptionMode(false, undefined)
actions.setDashboardMode(null, DashboardEventSource.Browser)
- actions.setButtonTileId(null)
- actions.setTextTileId(textTileId === undefined ? 'new' : textTileId !== 'new' ? Number(textTileId) : 'new')
- },
- '/dashboard/:id/button-tiles/:buttonTileId': ({ buttonTileId }) => {
- actions.setSubscriptionMode(false, undefined)
- actions.setDashboardMode(null, DashboardEventSource.Browser)
- actions.setTextTileId(null)
- actions.setButtonTileId(
- buttonTileId === undefined ? 'new' : buttonTileId !== 'new' ? Number(buttonTileId) : 'new'
- )
+ const parsedTileId = parseDashboardTileId(tileId)
+ actions.setTextTileId(parsedTileId)
+ actions.setButtonTileId(parsedTileId)
},
})),
])
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.test.ts b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
index 1b8a38a4f2b3..00d13f176581 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.test.ts
@@ -69,6 +69,52 @@ describe('dashboardToSaveableTemplate', () => {
button_tile: { url: '/replay/home', text: 'Watch replays' },
})
})
+
+ it('preserves display attributes for every tile type', () => {
+ const dashboard = {
+ name: 'My dashboard',
+ description: '',
+ filters: {},
+ tags: [],
+ tiles: [
+ {
+ id: 1,
+ text: { body: 'Text', last_modified_at: '2024-01-01' },
+ layouts: {},
+ color: null,
+ transparent_background: true,
+ },
+ {
+ id: 2,
+ insight: { name: 'Insight', query: { kind: 'TrendsQuery' } },
+ layouts: {},
+ color: null,
+ transparent_background: false,
+ },
+ {
+ id: 3,
+ button_tile: { url: '/insights', text: 'Insights', placement: 'left', style: 'primary' },
+ layouts: {},
+ color: null,
+ transparent_background: true,
+ },
+ {
+ id: 4,
+ widget: { id: 'widget-1', widget_type: 'todo', config: {} },
+ layouts: {},
+ color: null,
+ transparent_background: false,
+ },
+ ],
+ } as unknown as DashboardType<InsightModel>
+
+ expect(dashboardToSaveableTemplate(dashboard)?.tiles).toMatchObject([
+ { type: 'TEXT', transparent_background: true },
+ { type: 'INSIGHT', transparent_background: false },
+ { type: 'BUTTON', transparent_background: true },
+ { type: 'WIDGET', transparent_background: false },
+ ])
+ })
})
describe('isWidgetTileVisibleOnPlacement', () => {
diff --git a/frontend/src/scenes/dashboard/dashboardUtils.ts b/frontend/src/scenes/dashboard/dashboardUtils.ts
index 689c48c8f9ad..650217b5fc2e 100644
--- a/frontend/src/scenes/dashboard/dashboardUtils.ts
+++ b/frontend/src/scenes/dashboard/dashboardUtils.ts
@@ -69,6 +69,7 @@ export function dashboardToSaveableTemplate(
body: tile.text.body,
layouts: tile.layouts,
color: tile.color,
+ transparent_background: tile.transparent_background,
}
}
if (tile.insight) {
@@ -79,6 +80,7 @@ export function dashboardToSaveableTemplate(
query: tile.insight.query,
layouts: tile.layouts,
color: tile.color,
+ transparent_background: tile.transparent_background,
}
}
if (tile.button_tile) {
@@ -92,6 +94,7 @@ export function dashboardToSaveableTemplate(
},
layouts: tile.layouts,
color: tile.color,
+ transparent_background: tile.transparent_background,
}
}
if (tile.widget) {
@@ -101,6 +104,7 @@ export function dashboardToSaveableTemplate(
config: tile.widget.config,
layouts: tile.layouts,
color: tile.color,
+ transparent_background: tile.transparent_background,
}
}
throw new Error('Unknown tile type')
diff --git a/frontend/src/scenes/dashboard/tileLayouts.test.ts b/frontend/src/scenes/dashboard/tileLayouts.test.ts
index d285c5dddc3f..765d259eeaca 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.test.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.test.ts
@@ -29,6 +29,41 @@ describe('calculating tile layouts', () => {
})
})
+ it('sets a 1 by 2 minimum for image tiles', () => {
+ const tiles: DashboardTile<QueryBasedInsightModel>[] = [
+ {
+ id: 1,
+ text: { body: '![image](https://example.com/image.png)' },
+ layouts: {},
+ } as unknown as DashboardTile<QueryBasedInsightModel>,
+ ]
+
+ const layouts = calculateLayouts(tiles)
+
+ expect(layouts.sm?.[0]).toMatchObject({ w: 2, h: 2, minW: 1, minH: 2 })
+ expect(layouts.xs?.[0]).toMatchObject({ w: 1, h: 2, minW: 1, minH: 2 })
+ })
+
+ it('raises a stored image tile height to its minimum', () => {
+ const tiles: DashboardTile<QueryBasedInsightModel>[] = [
+ {
+ id: 1,
+ text: { body: '![image](https://example.com/image.png)' },
+ layouts: { sm: { i: '1', x: 0, y: 0, w: 1, h: 1 } },
+ } as unknown as DashboardTile<QueryBasedInsightModel>,
+ ]
+
+ expect(calculateLayouts(tiles).sm?.[0]).toMatchObject({ w: 1, h: 2, minW: 1, minH: 2 })
+ })
+
+ it('defaults button tiles to two columns', () => {
+ const tiles: DashboardTile<QueryBasedInsightModel>[] = [
+ { id: 1, button_tile: { id: '1' }, layouts: {} } as unknown as DashboardTile<QueryBasedInsightModel>,
+ ]
+
+ expect(calculateLayouts(tiles).sm?.[0]).toMatchObject({ w: 2, h: 1 })
+ })
+
it('when the tiles have only 2-col layouts, 1 col layout is calculated', () => {
// sm layouts have been re-ordered
// they are not in creation order when read left to right.
diff --git a/frontend/src/scenes/dashboard/tileLayouts.ts b/frontend/src/scenes/dashboard/tileLayouts.ts
index 2bcd8dd58212..f4db3073bb0a 100644
--- a/frontend/src/scenes/dashboard/tileLayouts.ts
+++ b/frontend/src/scenes/dashboard/tileLayouts.ts
@@ -6,12 +6,15 @@ import {
type DashboardWidgetCatalogEntry,
} from '@posthog/products-dashboards/frontend/widget_types/catalog'
+import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { BREAKPOINT_COLUMN_COUNTS } from 'scenes/dashboard/dashboardUtils'
import { getQueryBasedInsightModel } from '~/queries/nodes/InsightViz/utils'
import { isFunnelsQuery, isPathsQuery, isRetentionQuery, isTrendsQuery } from '~/queries/utils'
import { ChartDisplayType, DashboardLayoutSize, DashboardTile, QueryBasedInsightModel } from '~/types'
+import { getImageOnlyTextCardImage } from 'products/dashboards/frontend/components/ImageTile/imageTileUtils'
+
export interface TileLayout {
x: number
y: number
@@ -19,10 +22,15 @@ export interface TileLayout {
h: number
}
-const MIN_TILE_HEIGHT_ROWS = 2
-const MIN_TEXT_TILE_HEIGHT_ROWS = 1
-const MIN_WIDGET_TILE_WIDTH_COLS = 3
-const MIN_WIDGET_TILE_HEIGHT_ROWS = 4
+const MIN_TILE_DIMENSIONS = {
+ default: { w: 2, h: 2 },
+ image: { w: 1, h: 2 },
+ text: { w: 1, h: 1 },
+ button: { w: 1, h: 1 },
+ widget: { w: 3, h: 4 },
+} as const
+
+type TileLayoutKind = keyof typeof MIN_TILE_DIMENSIONS
/** Fallback tile dimensions (half-width, standard height) when a tile has no known layout yet. */
export const DEFAULT_INSERTED_TILE_SIZE = { w: 6, h: 5 } as const
@@ -32,7 +40,7 @@ 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`).
+ * (default size 6×5, mins `MIN_TILE_DIMENSIONS.widget`).
*/
function getWidgetCatalogLayout(widgetType: string | undefined): WidgetCatalogLayout | undefined {
if (!widgetType || !(widgetType in DASHBOARD_WIDGET_CATALOG)) {
@@ -42,26 +50,25 @@ function getWidgetCatalogLayout(widgetType: string | undefined): WidgetCatalogLa
}
function getTileMinDimensions({
- isTextTile,
- isButtonTile,
- isWidgetTile,
+ tileLayoutKind,
widgetCatalogLayout,
}: {
- isTextTile: boolean
- isButtonTile: boolean
- isWidgetTile: boolean
+ tileLayoutKind: TileLayoutKind
widgetCatalogLayout: WidgetCatalogLayout | undefined
}): { minW: number; minH: number } {
- if (isTextTile || isButtonTile) {
- return { minW: 1, minH: MIN_TEXT_TILE_HEIGHT_ROWS }
- }
- if (isWidgetTile) {
+ if (tileLayoutKind === 'widget') {
+ const dimensions = MIN_TILE_DIMENSIONS.widget
return {
- minW: widgetCatalogLayout?.minW ?? MIN_WIDGET_TILE_WIDTH_COLS,
- minH: widgetCatalogLayout?.minH ?? MIN_WIDGET_TILE_HEIGHT_ROWS,
+ minW: widgetCatalogLayout?.minW ?? dimensions.w,
+ minH: widgetCatalogLayout?.minH ?? dimensions.h,
}
}
- return { minW: 2, minH: MIN_TILE_HEIGHT_ROWS }
+
+ const dimensions = MIN_TILE_DIMENSIONS[tileLayoutKind]
+ return {
+ minW: dimensions.w,
+ minH: dimensions.h,
+ }
}
export interface DuplicateLayoutResult {
@@ -218,6 +225,11 @@ export const calculateLayouts = (
tiles: DashboardTile<QueryBasedInsightModel>[]
): Partial<Record<DashboardLayoutSize, Layout>> => {
const allLayouts: Partial<Record<keyof typeof BREAKPOINT_COLUMN_COUNTS, Layout>> = {}
+ const imageTileIds = new Set(
+ tiles
+ .filter((tile) => !!tile.text && !!getImageOnlyTextCardImage(textCardConverter, tile.text.body))
+ .map((tile) => tile.id)
+ )
// Always calculate sm layout first to establish reference order
let referenceOrder: number[] | undefined = undefined
@@ -271,11 +283,33 @@ export const calculateLayouts = (
const { x, y, w, h } = layout || {}
const isTextTile = !!tile.text
+ const isImageTile = imageTileIds.has(tile.id)
const isButtonTile = !!tile.button_tile
const isWidgetTile = !!tile.widget
+ let tileLayoutKind: TileLayoutKind
+ switch (true) {
+ case isImageTile:
+ tileLayoutKind = 'image'
+ break
+ case isTextTile:
+ tileLayoutKind = 'text'
+ break
+ case isButtonTile:
+ tileLayoutKind = 'button'
+ break
+ case isWidgetTile:
+ tileLayoutKind = 'widget'
+ break
+ case !!tile.insight:
+ tileLayoutKind = 'default'
+ break
+ default:
+ console.warn('Unknown dashboard tile type', { tileId: tile.id })
+ tileLayoutKind = 'default'
+ }
const widgetCatalogLayout = isWidgetTile ? getWidgetCatalogLayout(tile.widget?.widget_type) : undefined
if (isButtonTile) {
- defaultW = 3
+ defaultW = 2
defaultH = 1
} else if (isWidgetTile) {
defaultW = widgetCatalogLayout?.w ?? 6
@@ -285,18 +319,18 @@ export const calculateLayouts = (
const realW = Math.min(w || defaultW, columnCount)
const realH = h || (typeof xsSmH === 'number' && xsSmH > 0 ? xsSmH : undefined) || defaultH
const { minW, minH } = getTileMinDimensions({
- isTextTile,
- isButtonTile,
- isWidgetTile,
+ tileLayoutKind,
widgetCatalogLayout,
})
+ const constrainedW = isImageTile ? Math.max(realW, minW) : realW
+ const constrainedH = isImageTile ? Math.max(realH, minH) : realH
return {
i: tile.id?.toString(),
- x: x != null && Number.isInteger(x) && x + realW - 1 < columnCount ? x : 0,
+ x: x != null && Number.isInteger(x) && x + constrainedW - 1 < columnCount ? x : 0,
y: y != null && Number.isInteger(y) ? y : Infinity,
- w: realW,
- h: realH,
+ w: constrainedW,
+ h: constrainedH,
minW,
minH,
}
diff --git a/frontend/src/scenes/scenes.ts b/frontend/src/scenes/scenes.ts
index 1fdb38dedda8..36b6da27437c 100644
--- a/frontend/src/scenes/scenes.ts
+++ b/frontend/src/scenes/scenes.ts
@@ -747,6 +747,10 @@ export const redirects: Record<
// Redirect old path-based /configuration URLs to query param format
'/functions/:id/configuration': ({ id }) => urls.hogFunction(id, 'configuration'),
+ '/dashboard/:id/text-tiles/:tileId': ({ id, tileId }) =>
+ combineUrl(urls.dashboardTile(id, tileId), { tileType: 'text' }).url,
+ '/dashboard/:id/button-tiles/:tileId': ({ id, tileId }) =>
+ combineUrl(urls.dashboardTile(id, tileId), { tileType: 'button' }).url,
...productRedirects,
}
@@ -756,8 +760,7 @@ export const routes: Record<string, [Scene | string, string]> = {
[urls.dashboards()]: [Scene.Dashboards, 'dashboards'],
[urls.dashboardTemplateCopyToProject(':sourceTemplateId')]: [Scene.DashboardTemplateCopy, 'dashboardTemplateCopy'],
[urls.dashboard(':id')]: [Scene.Dashboard, 'dashboard'],
- [urls.dashboardTextTile(':id', ':textTileId')]: [Scene.Dashboard, 'dashboardTextTile'],
- [urls.dashboardButtonTile(':id', ':buttonTileId')]: [Scene.Dashboard, 'dashboardButtonTile'],
+ [urls.dashboardTile(':id', ':tileId')]: [Scene.Dashboard, 'dashboardTile'],
[urls.dashboardSharing(':id')]: [Scene.Dashboard, 'dashboardSharing'],
[urls.dashboardSubscriptions(':id')]: [Scene.Dashboard, 'dashboardSubscriptions'],
[urls.dashboardSubscription(':id', ':subscriptionId')]: [Scene.Dashboard, 'dashboardSubscription'],
diff --git a/frontend/src/types.ts b/frontend/src/types.ts
index 0b126b8a017c..1b70d9a57243 100644
--- a/frontend/src/types.ts
+++ b/frontend/src/types.ts
@@ -2543,6 +2543,8 @@ export interface Tileable {
color: InsightColor | null
}
+export type DashboardTileIdOrNew = number | null
+
export interface DashboardTile<T = InsightModel> extends Tileable {
id: number
insight?: T
@@ -2777,6 +2779,7 @@ export type DashboardTemplateStoredInsightTile = {
query?: Node | Record<string, unknown> | null
layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
color?: InsightColor | null
+ transparent_background?: boolean | null
filters?: Record<string, unknown>
}
@@ -2785,6 +2788,7 @@ export type DashboardTemplateStoredTextTile = {
body: string
layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
color?: InsightColor | null
+ transparent_background?: boolean | null
}
export type DashboardTemplateStoredButtonTile = {
@@ -2797,6 +2801,7 @@ export type DashboardTemplateStoredButtonTile = {
}
layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
color?: InsightColor | null
+ transparent_background?: boolean | null
}
export type DashboardTemplateStoredWidgetTile = {
@@ -2805,6 +2810,7 @@ export type DashboardTemplateStoredWidgetTile = {
config?: Record<string, unknown>
layouts?: Record<DashboardLayoutSize, TileLayout> | Record<string, never>
color?: InsightColor | null
+ transparent_background?: boolean | null
}
export type DashboardTemplateStoredTile =
diff --git a/playwright/page-models/dashboardPage.ts b/playwright/page-models/dashboardPage.ts
index 089c025111bb..af513f0e38ad 100644
--- a/playwright/page-models/dashboardPage.ts
+++ b/playwright/page-models/dashboardPage.ts
@@ -93,8 +93,6 @@ export class DashboardPage {
await expect(addTextTileButton).toBeVisible()
await addTextTileButton.click()
- await expect(this.page).toHaveURL(/\/dashboard\/\d+\/text-tiles\/new(?:\?.*)?$/, { timeout: 5000 })
-
// Text card edit UI uses DialogPrimitive, not LemonModal (see TextCardModal.tsx).
const modal = this.page.getByTestId('text-card-modal')
await expect(modal).toBeVisible()
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 682858067610..32771e1b28c6 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -2929,6 +2929,9 @@ importers:
kea:
specifier: 'catalog:'
version: 4.0.0-pre.6(patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected])
+ kea-forms:
+ specifier: 'catalog:'
+ version: 3.2.0([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
kea-loaders:
specifier: 'catalog:'
version: 3.1.1([email protected](patch_hash=139b8d1f1304f9d9da452a9a1244c94ea679dbcb85687d8999563146879fb6f5)([email protected]))
diff --git a/posthog/api/test/dashboards/test_dashboard.py b/posthog/api/test/dashboards/test_dashboard.py
index be417643d5da..9b3ebdf00e81 100644
--- a/posthog/api/test/dashboards/test_dashboard.py
+++ b/posthog/api/test/dashboards/test_dashboard.py
@@ -4302,13 +4302,20 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
- def test_create_text_tile_adds_markdown_tile_to_dashboard(self):
+ @parameterized.expand(
+ [
+ ("text", "text", "## Section heading\n\nIntro markdown."),
+ ("image", "image", "![Dashboard image](https://example.com/image.png)"),
+ ]
+ )
+ def test_create_text_tile_accepts_tile_types(self, _name: str, tile_type: str, tile_body: str) -> None:
dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard")
response = self.client.post(
f"/api/environments/{self.team.pk}/dashboards/{dashboard.pk}/create_text_tile/",
{
- "body": "## Section heading\n\nIntro markdown.",
+ "type": tile_type,
+ "body": tile_body,
"layouts": {"sm": {"x": 0, "y": 0, "w": 12, "h": 1}},
},
content_type="application/json",
@@ -4317,14 +4324,14 @@ class TestDashboard(APIBaseTest, QueryMatchingTest):
body = response.json()
self.assertIsNotNone(body["id"])
self.assertIsNone(body["insight"])
- self.assertEqual(body["text"]["body"], "## Section heading\n\nIntro markdown.")
+ self.assertEqual(body["text"]["body"], tile_body)
self.assertEqual(body["layouts"]["sm"], {"x": 0, "y": 0, "w": 12, "h": 1})
dashboard_response = self.client.get(f"/api/environments/{self.team.pk}/dashboards/{dashboard.pk}/")
self.assertEqual(dashboard_response.status_code, status.HTTP_200_OK)
tiles = dashboard_response.json()["tiles"]
self.assertEqual(len(tiles), 1)
- self.assertEqual(tiles[0]["text"]["body"], "## Section heading\n\nIntro markdown.")
+ self.assertEqual(tiles[0]["text"]["body"], tile_body)
def test_create_text_tile_without_layouts_uses_default(self):
dashboard = Dashboard.objects.create(team=self.team, name="Test Dashboard")
diff --git a/products/dashboards/backend/api/dashboard.py b/products/dashboards/backend/api/dashboard.py
index 11c212551183..8a8d29767670 100644
--- a/products/dashboards/backend/api/dashboard.py
+++ b/products/dashboards/backend/api/dashboard.py
@@ -572,18 +572,24 @@ class TileLayoutsSerializer(serializers.Serializer):
class CreateTextTileRequestSerializer(serializers.Serializer):
+ type = serializers.ChoiceField(
+ choices=["text", "image"],
+ required=False,
+ default="text",
+ help_text="Tile type. Use image for a body with exactly one Markdown image. Defaults to text.",
+ )
body = serializers.CharField(
min_length=1,
max_length=4000,
required=True,
allow_blank=False,
help_text=(
- "Markdown body for the text tile. Supports headings, lists, and inline formatting. "
- "Useful as a dashboard section heading, divider, or annotation between insights. Max 4000 characters."
+ "Markdown body for the dashboard tile. Text tiles support headings, lists, and inline formatting. "
+ "Image tiles require exactly one Markdown image. Max 4000 characters."
),
error_messages={
- "min_length": "Text body cannot be empty",
- "max_length": "Text body cannot exceed 4000 characters",
+ "min_length": "Tile body cannot be empty",
+ "max_length": "Tile body cannot exceed 4000 characters",
},
)
layouts = TileLayoutsSerializer(
diff --git a/products/dashboards/frontend/Tiles/DashboardImageTile.stories.tsx b/products/dashboards/frontend/Tiles/DashboardImageTile.stories.tsx
new file mode 100644
index 000000000000..1379bfe92847
--- /dev/null
+++ b/products/dashboards/frontend/Tiles/DashboardImageTile.stories.tsx
@@ -0,0 +1,54 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { DashboardPlacement, DashboardTile, InsightColor, QueryBasedInsightModel } from '~/types'
+
+import { DashboardImageTile } from 'products/dashboards/frontend/components/ImageTile/DashboardImageTile'
+
+const IMAGE_URL = 'https://imagedelivery.net/lvc9lblm6_VvsB0sE7lLrg/70-s-dance-hog/md'
+
+const transparentTile: DashboardTile<QueryBasedInsightModel> = {
+ id: 1,
+ color: InsightColor.White,
+ transparent_background: true,
+}
+
+const image = {
+ src: IMAGE_URL,
+ alt: 'Abstract red and yellow image',
+ title: '',
+ layout: 'contain' as const,
+ position: { x: 50, y: 50 },
+}
+
+const meta: Meta<typeof DashboardImageTile> = {
+ title: 'Products/Dashboards/Tiles/Dashboard Image Tile',
+ component: DashboardImageTile,
+ parameters: {
+ layout: 'fullscreen',
+ },
+ argTypes: {
+ image: {
+ control: 'object',
+ },
+ },
+ args: {
+ tile: transparentTile,
+ image,
+ placement: DashboardPlacement.Dashboard,
+ className: 'm-8 h-96 w-full max-w-3xl',
+ },
+}
+
+export default meta
+type Story = StoryObj<typeof DashboardImageTile>
+
+export const Default: Story = {}
+
+export const OpaqueCard: Story = {
+ args: {
+ tile: {
+ ...transparentTile,
+ transparent_background: false,
+ },
+ },
+}
diff --git a/products/dashboards/frontend/Tiles/ImageTileModal.stories.tsx b/products/dashboards/frontend/Tiles/ImageTileModal.stories.tsx
new file mode 100644
index 000000000000..727969e72041
--- /dev/null
+++ b/products/dashboards/frontend/Tiles/ImageTileModal.stories.tsx
@@ -0,0 +1,69 @@
+import type { Meta, StoryObj } from '@storybook/react'
+
+import { AccessControlLevel, DashboardType, QueryBasedInsightModel } from '~/types'
+
+import { ImageTileModal } from 'products/dashboards/frontend/components/ImageTile/ImageTileModal'
+
+const IMAGE_URL = 'https://imagedelivery.net/lvc9lblm6_VvsB0sE7lLrg/70-s-dance-hog/md'
+
+const makeDashboard = (body?: string): DashboardType<QueryBasedInsightModel> =>
+ ({
+ id: 123,
+ name: 'Image tile story',
+ description: '',
+ pinned: false,
+ created_at: '2024-01-01T00:00:00Z',
+ created_by: null,
+ last_accessed_at: null,
+ is_shared: false,
+ deleted: false,
+ creation_mode: 'default',
+ tiles: body
+ ? [
+ {
+ id: 1,
+ color: null,
+ layouts: {},
+ text: { body, last_modified_at: '2024-01-01T00:00:00Z' },
+ },
+ ]
+ : [],
+ filters: {},
+ tags: [],
+ user_access_level: AccessControlLevel.Editor,
+ }) as DashboardType<QueryBasedInsightModel>
+
+const meta: Meta<typeof ImageTileModal> = {
+ title: 'Products/Dashboards/Tiles/Image Tile Modal',
+ component: ImageTileModal,
+ parameters: {
+ layout: 'fullscreen',
+ },
+ args: {
+ isOpen: true,
+ onClose: () => undefined,
+ dashboard: makeDashboard(),
+ imageTileId: null,
+ },
+}
+
+export default meta
+type Story = StoryObj<typeof ImageTileModal>
+
+export const Empty: Story = {}
+
+export const ExistingImage: Story = {
+ args: {
+ dashboard: makeDashboard(`![Portrait](${IMAGE_URL})`),
+ imageTileId: 1,
+ },
+}
+
+export const ExistingCover: Story = {
+ args: {
+ dashboard: makeDashboard(
+ `<img src="${IMAGE_URL}" alt="Cover" data-layout="cover" data-position-x="75" data-position-y="50" />`
+ ),
+ imageTileId: 1,
+ },
+}
diff --git a/frontend/src/scenes/dashboard/items/DashboardTextItem.tsx b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx
similarity index 55%
rename from frontend/src/scenes/dashboard/items/DashboardTextItem.tsx
rename to products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx
index 13fbd72adea9..39113dc0b1cf 100644
--- a/frontend/src/scenes/dashboard/items/DashboardTextItem.tsx
+++ b/products/dashboards/frontend/components/DashboardTextItem/DashboardTextItem.tsx
@@ -4,11 +4,15 @@ import React from 'react'
import { dashboardWidgetMenusLogic } from 'lib/components/Cards/InsightCard/dashboardWidgetMenusLogic'
import { DashboardWidgetPlacementMenus } from 'lib/components/Cards/InsightCard/DashboardWidgetPlacementMenus'
import { TextCard } from 'lib/components/Cards/TextCard/TextCard'
+import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
import { LemonButton } from 'lib/lemon-ui/LemonButton'
import { LemonDivider } from 'lib/lemon-ui/LemonDivider'
import { DashboardPlacement, DashboardTile, DashboardType, QueryBasedInsightModel } from '~/types'
+import { DashboardImageTile } from '../ImageTile/DashboardImageTile'
+import { getImageOnlyTextCardImage } from '../ImageTile/imageTileUtils'
+
type BaseTextCardProps = React.ComponentProps<typeof TextCard>
interface DashboardTextItemProps extends Omit<BaseTextCardProps, 'textTile' | 'placement' | 'moreButtonOverlay'> {
@@ -46,39 +50,56 @@ function DashboardTextItemInternal(
})
)
+ const image = tile.text ? getImageOnlyTextCardImage(textCardConverter, tile.text.body) : null
+ const tileType = image ? 'image' : 'text'
+ const moreButtonOverlay = (
+ <>
+ <LemonButton fullWidth onClick={onEdit} data-attr={`edit-${tileType}`}>
+ Edit {tileType}
+ </LemonButton>
+
+ <DashboardWidgetPlacementMenus
+ placementDestinations={copyToDestinations}
+ onMoveToDashboard={onMoveToDashboard}
+ onCopyToDashboard={onCopyToDashboard}
+ />
+
+ <LemonButton onClick={onDuplicate} fullWidth data-attr={`duplicate-${tileType}-from-dashboard`}>
+ Duplicate
+ </LemonButton>
+ <LemonDivider />
+ {onRemove && (
+ <LemonButton
+ status="danger"
+ onClick={() => onRemove()}
+ fullWidth
+ data-attr={`remove-${tileType}-tile-from-dashboard`}
+ >
+ Delete
+ </LemonButton>
+ )}
+ </>
+ )
+
+ if (image) {
+ return (
+ <DashboardImageTile
+ ref={ref}
+ tile={tile}
+ image={image}
+ placement={placement}
+ moreButtonOverlay={moreButtonOverlay}
+ {...textCardProps}
+ />
+ )
+ }
+
return (
<TextCard
ref={ref}
textTile={tile}
placement={placement}
- moreButtonOverlay={
- <>
- <LemonButton fullWidth onClick={onEdit} data-attr="edit-text">
- Edit text
- </LemonButton>
-
- <DashboardWidgetPlacementMenus
- placementDestinations={copyToDestinations}
- onMoveToDashboard={onMoveToDashboard}
- onCopyToDashboard={onCopyToDashboard}
- />
-
- <LemonButton onClick={onDuplicate} fullWidth data-attr="duplicate-text-from-dashboard">
- Duplicate
- </LemonButton>
- <LemonDivider />
- {onRemove && (
- <LemonButton
- status="danger"
- onClick={() => onRemove()}
- fullWidth
- data-attr="remove-text-tile-from-dashboard"
- >
- Delete
- </LemonButton>
- )}
- </>
- }
+ moreButtonOverlay={moreButtonOverlay}
{...textCardProps}
/>
)
diff --git a/products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsx b/products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsx
new file mode 100644
index 000000000000..2a24b462b592
--- /dev/null
+++ b/products/dashboards/frontend/components/ImageTile/DashboardImageTile.tsx
@@ -0,0 +1,129 @@
+import clsx from 'clsx'
+import React from 'react'
+
+import { Resizeable } from 'lib/components/Cards/CardMeta'
+import { DashboardResizeHandles } from 'lib/components/Cards/handles'
+import { EditModeEdge, EditModeEdgeOverlay } from 'lib/components/Cards/InsightCard/EditModeEdgeOverlay'
+import { More, MoreProps } from 'lib/lemon-ui/LemonButton/More'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+
+import { DashboardPlacement, DashboardTile, QueryBasedInsightModel } from '~/types'
+
+import { imageTilePositionToCss } from './imageTileUtils'
+import type { ImageTileImage } from './imageTileUtils'
+
+interface DashboardImageTileProps extends React.HTMLAttributes<HTMLDivElement>, Resizeable {
+ tile: DashboardTile<QueryBasedInsightModel>
+ image: ImageTileImage
+ placement: DashboardPlacement
+ children?: JSX.Element
+ canEnterEditModeFromEdge?: boolean
+ onEnterEditModeFromEdge?: (event: React.MouseEvent<HTMLDivElement>, edge: EditModeEdge) => void
+ moreButtonOverlay?: MoreProps['overlay']
+ onDragHandleMouseDown?: React.MouseEventHandler<HTMLDivElement>
+ showEditingControls?: boolean
+}
+
+function DashboardImageTileInternal(
+ {
+ tile,
+ image,
+ showResizeHandles,
+ children,
+ className,
+ moreButtonOverlay,
+ placement,
+ canEnterEditModeFromEdge,
+ onEnterEditModeFromEdge,
+ onDragHandleMouseDown,
+ showEditingControls,
+ ...divProps
+ }: DashboardImageTileProps,
+ ref: React.Ref<HTMLDivElement>
+): JSX.Element {
+ const [isImagePreviewOpen, setIsImagePreviewOpen] = React.useState(false)
+ const shouldHideMoreButton = placement === DashboardPlacement.Public || showEditingControls === false
+ const isTransparent = tile.transparent_background
+ const imageStyle = {
+ objectPosition: imageTilePositionToCss(image.position),
+ }
+
+ return (
+ <>
+ <div
+ className={clsx(
+ 'DashboardTileCard DashboardImageTile rounded flex flex-col',
+ !isTransparent && 'bg-surface-primary border',
+ isTransparent && showResizeHandles && 'border border-dashed border-border',
+ className
+ )}
+ data-attr="image-tile"
+ {...divProps}
+ ref={ref}
+ >
+ {moreButtonOverlay && !shouldHideMoreButton && (
+ <div className="absolute right-4 top-4">
+ <More overlay={moreButtonOverlay} />
+ </div>
+ )}
+ <div
+ className={clsx(
+ 'DashboardTileCard__body ImageTile__body flex flex-1 min-h-0 w-full overflow-hidden p-4',
+ onDragHandleMouseDown && 'cursor-grab'
+ )}
+ onMouseDown={onDragHandleMouseDown}
+ >
+ {showResizeHandles ? (
+ <div className="flex h-full w-full items-center justify-center overflow-hidden rounded">
+ <img
+ src={image.src}
+ alt={image.alt}
+ draggable={false}
+ className={clsx(
+ 'h-full w-full',
+ image.layout === 'cover' ? 'object-cover' : 'object-contain'
+ )}
+ style={imageStyle}
+ />
+ </div>
+ ) : (
+ <button
+ type="button"
+ className="flex h-full w-full cursor-pointer items-center justify-center overflow-hidden rounded"
+ onClick={() => setIsImagePreviewOpen(true)}
+ aria-label={image.alt || 'Open image preview'}
+ data-attr="open-image-tile-preview"
+ >
+ <img
+ src={image.src}
+ alt={image.alt}
+ draggable={false}
+ className={clsx(
+ 'h-full w-full',
+ image.layout === 'cover' ? 'object-cover' : 'object-contain'
+ )}
+ style={imageStyle}
+ />
+ </button>
+ )}
+ </div>
+ {canEnterEditModeFromEdge && !showResizeHandles && onEnterEditModeFromEdge && (
+ <EditModeEdgeOverlay onEnterEditMode={onEnterEditModeFromEdge} />
+ )}
+ {showResizeHandles && <DashboardResizeHandles />}
+ {children}
+ </div>
+ <LemonModal
+ isOpen={isImagePreviewOpen}
+ onClose={() => setIsImagePreviewOpen(false)}
+ title="Image preview"
+ width="90vw"
+ maxWidth={1400}
+ >
+ <img src={image.src} alt={image.alt} className="h-[80vh] w-full object-contain" />
+ </LemonModal>
+ </>
+ )
+}
+
+export const DashboardImageTile = React.forwardRef<HTMLDivElement, DashboardImageTileProps>(DashboardImageTileInternal)
diff --git a/products/dashboards/frontend/components/ImageTile/ImageTileModal.test.tsx b/products/dashboards/frontend/components/ImageTile/ImageTileModal.test.tsx
new file mode 100644
index 000000000000..e8532de70a61
--- /dev/null
+++ b/products/dashboards/frontend/components/ImageTile/ImageTileModal.test.tsx
@@ -0,0 +1,361 @@
+import '@testing-library/jest-dom'
+
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import posthog from 'posthog-js'
+
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { useUploadFiles } from 'lib/hooks/useUploadFiles'
+import { preflightLogic } from 'lib/logic/preflightLogic'
+
+import { initKeaTests } from '~/test/init'
+import {
+ AccessControlLevel,
+ type DashboardTileIdOrNew,
+ DashboardType,
+ PreflightStatus,
+ QueryBasedInsightModel,
+} from '~/types'
+
+import { ImageTileModal } from 'products/dashboards/frontend/components/ImageTile/ImageTileModal'
+
+jest.mock('lib/hooks/useUploadFiles', () => ({
+ useUploadFiles: jest.fn(),
+}))
+
+const makeDashboard = (body?: string): DashboardType<QueryBasedInsightModel> =>
+ ({
+ id: 123,
+ name: 'Test dashboard',
+ description: '',
+ pinned: false,
+ created_at: '2024-01-01T00:00:00Z',
+ created_by: null,
+ last_accessed_at: null,
+ is_shared: false,
+ deleted: false,
+ creation_mode: 'default',
+ tiles: body
+ ? [
+ {
+ id: 1,
+ color: null,
+ layouts: {},
+ text: { body, last_modified_at: '2024-01-01T00:00:00Z' },
+ },
+ ]
+ : [],
+ filters: {},
+ tags: [],
+ user_access_level: AccessControlLevel.Editor,
+ }) as DashboardType<QueryBasedInsightModel>
+
+const firePointerEvent = (
+ element: HTMLElement,
+ type: 'pointerdown' | 'pointermove' | 'pointerup' | 'pointercancel',
+ init: { button?: number; pointerId: number; clientX: number; clientY: number }
+): void => {
+ const event = new Event(type, { bubbles: true, cancelable: true })
+ Object.defineProperties(event, {
+ button: { value: init.button ?? 0 },
+ pointerId: { value: init.pointerId },
+ clientX: { value: init.clientX },
+ clientY: { value: init.clientY },
+ })
+ fireEvent(element, event)
+}
+
+describe('ImageTileModal', () => {
+ const useUploadFilesMock = jest.mocked(useUploadFiles)
+
+ beforeEach(() => {
+ initKeaTests(false)
+ preflightLogic.mount()
+ preflightLogic.actions.loadPreflightSuccess({ object_storage: true } as PreflightStatus)
+ useUploadFilesMock.mockReturnValue({
+ setFilesToUpload: jest.fn(),
+ filesToUpload: [],
+ uploading: false,
+ })
+ jest.spyOn(posthog, 'capture').mockImplementation(() => undefined)
+ jest.spyOn(lemonToast, 'error').mockImplementation(jest.fn())
+ })
+
+ afterEach(() => {
+ cleanup()
+ jest.restoreAllMocks()
+ })
+
+ function renderModal(
+ imageTileId: DashboardTileIdOrNew = null,
+ body?: string
+ ): { onClose: jest.Mock; uploadOptions: Parameters<typeof useUploadFiles>[0] } {
+ const onClose = jest.fn()
+ render(<ImageTileModal isOpen onClose={onClose} dashboard={makeDashboard(body)} imageTileId={imageTileId} />)
+
+ return {
+ onClose,
+ uploadOptions: useUploadFilesMock.mock.calls.at(-1)?.[0] as Parameters<typeof useUploadFiles>[0],
+ }
+ }
+
+ function getDataAttr(dataAttr: string): HTMLElement {
+ return document.querySelector(`[data-attr="${dataAttr}"]`) as HTMLElement
+ }
+
+ it('requires an image before saving and hides the tile background option', () => {
+ renderModal()
+
+ expect(getDataAttr('save-new-image-tile')).toHaveAttribute('aria-disabled', 'true')
+ expect(document.querySelector('[data-attr="image-tile-transparent-background"]')).not.toBeInTheDocument()
+ })
+
+ it('renders a replacement preview after upload', () => {
+ const { uploadOptions } = renderModal()
+
+ act(() => {
+ uploadOptions.onUpload?.('https://example.com/portrait.png', 'portrait.png', 'media-id')
+ })
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveAttribute('src', 'https://example.com/portrait.png')
+ expect(screen.queryByText(/Drag or use arrow keys to reposition the image/)).not.toBeInTheDocument()
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveAttribute('alt', 'Dashboard image')
+ expect(getDataAttr('save-new-image-tile')).toHaveAttribute('aria-disabled', 'false')
+ expect(getDataAttr('image-tile-transparent-background')).toHaveAttribute('aria-checked', 'true')
+ })
+
+ it('opens the file picker when the empty preview is clicked', () => {
+ renderModal()
+
+ expect(getDataAttr('image-tile-preview')).toHaveTextContent(
+ 'Drag and drop an image or click here to upload an image'
+ )
+
+ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
+ const click = jest.spyOn(fileInput, 'click')
+
+ fireEvent.click(getDataAttr('image-tile-preview'))
+
+ expect(click).toHaveBeenCalledTimes(1)
+ })
+
+ it('opens the file picker when replace image is clicked', () => {
+ renderModal(1, '![Image](https://example.com/image.png)')
+
+ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
+ const click = jest.spyOn(fileInput, 'click')
+
+ fireEvent.click(getDataAttr('replace-image-tile-image'))
+
+ expect(click).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not open the file picker when an existing image is clicked', () => {
+ renderModal(1, '![Image](https://example.com/image.png)')
+
+ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
+ const click = jest.spyOn(fileInput, 'click')
+
+ fireEvent.click(getDataAttr('image-tile-preview'))
+
+ expect(click).not.toHaveBeenCalled()
+ })
+
+ it('ignores a second file selection before the first upload starts', () => {
+ const setFilesToUpload = jest.fn()
+ useUploadFilesMock.mockReturnValue({
+ setFilesToUpload,
+ filesToUpload: [],
+ uploading: false,
+ })
+
+ renderModal()
+
+ const input = document.querySelector('input[type="file"]') as HTMLInputElement
+ const firstFile = new File(['first'], 'first.png', { type: 'image/png' })
+ const secondFile = new File(['second'], 'second.png', { type: 'image/png' })
+
+ fireEvent.change(input, { target: { files: [firstFile] } })
+ fireEvent.change(input, { target: { files: [secondFile] } })
+
+ expect(setFilesToUpload).toHaveBeenCalledTimes(1)
+ expect(setFilesToUpload).toHaveBeenCalledWith([firstFile])
+ })
+
+ it('loads saved image settings and applies them to the preview', () => {
+ renderModal(
+ 1,
+ '<img src="https://example.com/landscape.png" alt="Landscape" data-layout="cover" data-position-x="25" data-position-y="75" />'
+ )
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveClass('object-cover')
+ expect(getDataAttr('image-tile-preview')).toHaveAttribute('aria-label', 'Drag to reposition the image')
+ expect(getDataAttr('image-tile-preview-image')).toHaveStyle({
+ objectPosition: '25% 75%',
+ })
+ })
+
+ it('keeps the full image visible in show full image mode', () => {
+ renderModal(
+ 1,
+ '<img src="https://example.com/landscape.png" alt="Landscape" data-position-x="25" data-position-y="75" />'
+ )
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveClass('object-contain')
+ expect(screen.queryByText(/Drag or use arrow keys to reposition the image/)).not.toBeInTheDocument()
+ })
+
+ it('updates the image display mode', () => {
+ renderModal(1, '![Landscape](https://example.com/landscape.png)')
+
+ fireEvent.click(getDataAttr('image-tile-layout'))
+ fireEvent.click(screen.getByText('Fill the tile'))
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveClass('object-cover')
+ })
+
+ it('updates the saved image position when the preview is dragged', () => {
+ renderModal(1, '<img src="https://example.com/landscape.png" alt="Landscape" data-layout="cover" />')
+
+ const preview = getDataAttr('image-tile-preview')
+ const image = getDataAttr('image-tile-preview-image')
+ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
+ const click = jest.spyOn(fileInput, 'click')
+ expect(image).toHaveClass('pointer-events-none')
+ jest.spyOn(preview, 'getBoundingClientRect').mockReturnValue({ width: 200, height: 100 } as DOMRect)
+ firePointerEvent(image, 'pointerdown', { button: 0, pointerId: 1, clientX: 100, clientY: 50 })
+ firePointerEvent(image, 'pointermove', { pointerId: 1, clientX: 140, clientY: 70 })
+ firePointerEvent(image, 'pointerup', { pointerId: 1, clientX: 140, clientY: 70 })
+ fireEvent.click(preview)
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveStyle({ objectPosition: '10% 30%' })
+ expect(click).not.toHaveBeenCalled()
+ })
+
+ it('discards a cancelled drag without opening the file picker', () => {
+ renderModal(1, '<img src="https://example.com/landscape.png" alt="Landscape" data-layout="cover" />')
+
+ const preview = getDataAttr('image-tile-preview')
+ const image = getDataAttr('image-tile-preview-image')
+ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
+ const click = jest.spyOn(fileInput, 'click')
+ jest.spyOn(preview, 'getBoundingClientRect').mockReturnValue({ width: 200, height: 100 } as DOMRect)
+
+ firePointerEvent(image, 'pointerdown', { button: 0, pointerId: 1, clientX: 100, clientY: 50 })
+ firePointerEvent(image, 'pointermove', { pointerId: 1, clientX: 140, clientY: 70 })
+ firePointerEvent(image, 'pointercancel', { pointerId: 1, clientX: 140, clientY: 70 })
+ fireEvent.click(preview)
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveStyle({ objectPosition: '50% 50%' })
+ expect(click).not.toHaveBeenCalled()
+ })
+
+ it('keeps the image position when replacing an image', () => {
+ const { uploadOptions } = renderModal(
+ 1,
+ '<img src="https://example.com/landscape.png" alt="Landscape" data-layout="cover" data-position-x="25" data-position-y="75" />'
+ )
+
+ act(() => {
+ uploadOptions.onUpload?.('https://example.com/replacement.png', 'replacement.png', 'media-id')
+ })
+
+ expect(getDataAttr('image-tile-preview-image')).toHaveAttribute('src', 'https://example.com/replacement.png')
+ expect(getDataAttr('image-tile-preview-image')).toHaveStyle({
+ objectPosition: '25% 75%',
+ })
+ })
+
+ it('reports upload failure without sending upload details', () => {
+ const { uploadOptions } = renderModal()
+ const capture = jest.mocked(posthog.capture)
+ capture.mockClear()
+
+ act(() => {
+ uploadOptions.onError('storage unavailable')
+ })
+
+ expect(capture).toHaveBeenCalledWith('dashboard image tile upload failed')
+ expect(capture).not.toHaveBeenCalledWith('dashboard image tile upload failed', expect.anything())
+ expect(lemonToast.error).toHaveBeenCalledWith('We could not upload that image. Try again.')
+ })
+
+ it('shows a safe actionable message for an unsupported image format', () => {
+ const { uploadOptions } = renderModal()
+
+ act(() => {
+ uploadOptions.onError('This image format is not supported')
+ })
+
+ expect(lemonToast.error).toHaveBeenCalledWith('Choose a PNG, JPG, GIF, WebP, or AVIF image.')
+ expect(posthog.capture).toHaveBeenCalledWith('dashboard image tile upload failed')
+ })
+
+ it('disables save while an upload is in progress', () => {
+ useUploadFilesMock.mockReturnValue({
+ setFilesToUpload: jest.fn(),
+ filesToUpload: [],
+ uploading: true,
+ })
+
+ renderModal(1, '![Image](https://example.com/image.png)')
+
+ expect(getDataAttr('edit-image-tile')).toHaveAttribute('aria-disabled', 'true')
+ expect(getDataAttr('edit-image-tile')).toHaveClass('LemonButton--loading')
+ expect(document.querySelector('input[type="file"]')).toBeDisabled()
+ expect(getDataAttr('image-tile-preview')).toHaveAttribute('aria-disabled', 'true')
+ expect(getDataAttr('image-tile-preview')).toHaveAttribute('tabindex', '-1')
+ expect(getDataAttr('image-tile-layout')).toHaveAttribute('aria-disabled', 'true')
+ })
+
+ it('rejects dropped files while an upload is in progress', () => {
+ const setFilesToUpload = jest.fn()
+ useUploadFilesMock.mockReturnValue({
+ setFilesToUpload,
+ filesToUpload: [],
+ uploading: true,
+ })
+
+ renderModal(1, '![Image](https://example.com/image.png)')
+
+ fireEvent.drop(getDataAttr('image-tile-preview'), {
+ dataTransfer: {
+ files: [new File(['image'], 'image.png', { type: 'image/png' })],
+ items: [{ kind: 'file', type: 'image/png' }],
+ },
+ })
+
+ expect(setFilesToUpload).not.toHaveBeenCalled()
+ })
+
+ it('prevents cancelling while an upload is in progress', () => {
+ const onClose = jest.fn()
+ useUploadFilesMock.mockReturnValue({
+ setFilesToUpload: jest.fn(),
+ filesToUpload: [],
+ uploading: true,
+ })
+
+ render(
+ <ImageTileModal
+ isOpen
+ onClose={onClose}
+ dashboard={makeDashboard('![Image](https://example.com/image.png)')}
+ imageTileId={1}
+ />
+ )
+
+ fireEvent.click(screen.getByText('Cancel'))
+
+ expect(onClose).not.toHaveBeenCalled()
+ })
+
+ it('closes when cancel is clicked', () => {
+ const { onClose } = renderModal()
+
+ fireEvent.click(screen.getByText('Cancel'))
+
+ expect(onClose).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx b/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx
new file mode 100644
index 000000000000..804788c9e660
--- /dev/null
+++ b/products/dashboards/frontend/components/ImageTile/ImageTileModal.tsx
@@ -0,0 +1,522 @@
+import clsx from 'clsx'
+import { useActions, useValues } from 'kea'
+import { Field, Form } from 'kea-forms'
+import posthog from 'posthog-js'
+import { useEffect, useRef, useState } from 'react'
+import type { KeyboardEvent, PointerEvent, RefObject } from 'react'
+
+import { IconImage } from '@posthog/icons'
+
+import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
+import { textCardModalLogic } from 'lib/components/Cards/TextCard/textCardModalLogic'
+import type { TextCardModalProps } from 'lib/components/Cards/TextCard/textCardModalLogic'
+import { useUploadFiles } from 'lib/hooks/useUploadFiles'
+import { LemonButton } from 'lib/lemon-ui/LemonButton'
+import { LemonFileInput } from 'lib/lemon-ui/LemonFileInput'
+import { LemonInput } from 'lib/lemon-ui/LemonInput'
+import { LemonLabel } from 'lib/lemon-ui/LemonLabel'
+import { LemonModal } from 'lib/lemon-ui/LemonModal'
+import { LemonSelect } from 'lib/lemon-ui/LemonSelect'
+import { LemonSwitch } from 'lib/lemon-ui/LemonSwitch'
+import { lemonToast } from 'lib/lemon-ui/LemonToast'
+import { preflightLogic } from 'lib/logic/preflightLogic'
+
+import { DashboardTileIdOrNew, DashboardType, QueryBasedInsightModel } from '~/types'
+
+import {
+ DEFAULT_IMAGE_TILE_POSITION,
+ getImageOnlyTextCardImage,
+ imageTileToMarkdown,
+ imageTilePositionToCss,
+} from './imageTileUtils'
+import type { ImageTileImage, ImageTilePosition } from './imageTileUtils'
+
+const IMAGE_TILE_LAYOUT_OPTIONS = [
+ { value: 'contain', label: 'Show full image' },
+ { value: 'cover', label: 'Fill the tile' },
+] satisfies { value: ImageTileImage['layout']; label: string }[]
+
+interface ImagePreviewDragState {
+ pointerId: number
+ startClientX: number
+ startClientY: number
+ startPosition: ImageTilePosition
+ previewWidth: number
+ previewHeight: number
+}
+
+const IMAGE_TILE_HORIZONTAL_DRAG_FACTOR = 2
+const IMAGE_TILE_POSITION_STEP = 10
+const MAX_IMAGE_UPLOAD_SIZE_BYTES = 4 * 1024 * 1024
+const IMAGE_UPLOAD_ERROR_MESSAGES = {
+ NOT_AN_IMAGE: 'File is not an image',
+ UNSUPPORTED_TYPE: 'This image format is not supported',
+ TOO_LARGE: 'Image exceeds the maximum file size',
+} as const
+const SUPPORTED_IMAGE_UPLOAD_TYPES = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp', 'image/avif']
+
+export function ImageTileModal({
+ isOpen,
+ onClose,
+ dashboard,
+ imageTileId,
+}: {
+ isOpen: boolean
+ onClose: () => void
+ dashboard: DashboardType<QueryBasedInsightModel>
+ imageTileId: DashboardTileIdOrNew
+}): JSX.Element {
+ const isNewTile = imageTileId === null
+ const modalLogicProps: TextCardModalProps = {
+ dashboard,
+ textTileId: imageTileId,
+ onClose,
+ tileType: 'image',
+ }
+ const modalLogic = textCardModalLogic(modalLogicProps)
+ const { objectStorageAvailable } = useValues(preflightLogic)
+ const { isTextTileSubmitting, textTile, textTileValidationErrors } = useValues(modalLogic)
+ const { resetTextTile, setTextTileValues } = useActions(modalLogic)
+ const previewRef = useRef<HTMLElement | null>(null)
+ const fileInputRef = useRef<HTMLInputElement>(null)
+ const previewDragRef = useRef<ImagePreviewDragState | null>(null)
+ const imageRef = useRef<ImageTileImage | null>(null)
+ const previewPositionRef = useRef<ImageTilePosition | null>(null)
+ const imageOperationInProgressRef = useRef(false)
+ const uploadRequestedRef = useRef(false)
+ const [isDragging, setIsDragging] = useState(false)
+ const [previewPosition, setPreviewPosition] = useState<ImageTilePosition | null>(null)
+ const [uploadComplete, setUploadComplete] = useState(false)
+ const image = getImageOnlyTextCardImage(textCardConverter, textTile.body)
+ const previewImage = image && previewPosition ? { ...image, position: previewPosition } : image
+ imageRef.current = image
+
+ useEffect(() => {
+ const previewPositionToCommit = previewPositionRef.current
+ if (
+ previewPositionToCommit &&
+ image &&
+ previewPositionToCommit.x === image.position.x &&
+ previewPositionToCommit.y === image.position.y
+ ) {
+ previewPositionRef.current = null
+ setPreviewPosition(null)
+ }
+ }, [image])
+
+ const setPreviewRef = (element: HTMLElement | null): void => {
+ previewRef.current = element
+ }
+
+ const { setFilesToUpload, filesToUpload, uploading } = useUploadFiles({
+ onUpload: (url) => {
+ const currentImage = imageRef.current
+ const nextImage: ImageTileImage = currentImage
+ ? { ...currentImage, src: url }
+ : {
+ src: url,
+ alt: '',
+ title: '',
+ layout: 'contain',
+ position: DEFAULT_IMAGE_TILE_POSITION,
+ }
+ setTextTileValues({
+ body: imageTileToMarkdown(textCardConverter, nextImage),
+ })
+ setUploadComplete(true)
+ },
+ uploadFileOptions: {
+ allowedMimeTypes: SUPPORTED_IMAGE_UPLOAD_TYPES,
+ maxSizeBytes: MAX_IMAGE_UPLOAD_SIZE_BYTES,
+ },
+ onError: (detail) => {
+ posthog.capture('dashboard image tile upload failed')
+ if (detail === IMAGE_UPLOAD_ERROR_MESSAGES.NOT_AN_IMAGE) {
+ lemonToast.error('Upload an image file.')
+ } else if (detail === IMAGE_UPLOAD_ERROR_MESSAGES.UNSUPPORTED_TYPE) {
+ lemonToast.error('Choose a PNG, JPG, GIF, WebP, or AVIF image.')
+ } else if (detail === IMAGE_UPLOAD_ERROR_MESSAGES.TOO_LARGE) {
+ lemonToast.error('Image must be 4 MB or smaller.')
+ } else {
+ lemonToast.error('We could not upload that image. Try again.')
+ }
+ },
+ })
+ const imageOperationInProgress = isTextTileSubmitting || uploading
+ imageOperationInProgressRef.current = imageOperationInProgress
+
+ useEffect(() => {
+ if (!uploading && filesToUpload.length === 0) {
+ uploadRequestedRef.current = false
+ }
+ }, [filesToUpload.length, uploading])
+
+ const [initialBody] = useState(() =>
+ imageTileId !== null ? dashboard.tiles?.find((tile) => tile.id === imageTileId)?.text?.body || '' : ''
+ )
+ const hasUnsavedInput = textTile.body !== initialBody
+
+ const handleClose = (): void => {
+ if (imageOperationInProgress) {
+ return
+ }
+
+ resetTextTile()
+ onClose()
+ }
+
+ const updateImageBody = (nextImage: ImageTileImage): void => {
+ imageRef.current = nextImage
+ setTextTileValues({ body: imageTileToMarkdown(textCardConverter, nextImage) })
+ }
+
+ const updateLayout = (layout: ImageTileImage['layout']): void => {
+ const currentImage = imageRef.current
+ if (!currentImage) {
+ return
+ }
+
+ updateImageBody({
+ ...currentImage,
+ layout,
+ })
+ }
+
+ const updatePosition = (position: ImageTilePosition): void => {
+ const currentImage = imageRef.current
+ if (!currentImage) {
+ return
+ }
+
+ updateImageBody({ ...currentImage, position })
+ }
+
+ const handlePreviewPointerDown = (event: PointerEvent<HTMLElement>): void => {
+ if (!image || imageOperationInProgress || event.button !== 0) {
+ return
+ }
+
+ const rect = event.currentTarget.getBoundingClientRect()
+ if (!rect.width || !rect.height) {
+ return
+ }
+
+ previewDragRef.current = {
+ pointerId: event.pointerId,
+ startClientX: event.clientX,
+ startClientY: event.clientY,
+ startPosition: image.position,
+ previewWidth: rect.width,
+ previewHeight: rect.height,
+ }
+ previewPositionRef.current = null
+ setPreviewPosition(null)
+ event.currentTarget.setPointerCapture?.(event.pointerId)
+ setIsDragging(true)
+ }
+
+ const handlePreviewPointerMove = (event: PointerEvent<HTMLElement>): void => {
+ const drag = previewDragRef.current
+ if (!drag || drag.pointerId !== event.pointerId || !image || imageOperationInProgress) {
+ return
+ }
+
+ if (Math.hypot(event.clientX - drag.startClientX, event.clientY - drag.startClientY) <= 4) {
+ return
+ }
+
+ const dragDirection = image.layout === 'cover' ? -1 : 1
+ const nextPosition: ImageTilePosition = {
+ x: Math.max(
+ 0,
+ Math.min(
+ 100,
+ drag.startPosition.x +
+ ((event.clientX - drag.startClientX) / drag.previewWidth) *
+ 100 *
+ IMAGE_TILE_HORIZONTAL_DRAG_FACTOR *
+ dragDirection
+ )
+ ),
+ y: Math.max(
+ 0,
+ Math.min(
+ 100,
+ drag.startPosition.y +
+ ((event.clientY - drag.startClientY) / drag.previewHeight) * 100 * dragDirection
+ )
+ ),
+ }
+ previewPositionRef.current = nextPosition
+ setPreviewPosition(nextPosition)
+ }
+
+ const finishPreviewDrag = (event: PointerEvent<HTMLElement>, commitPosition: boolean): void => {
+ const drag = previewDragRef.current
+ if (!drag || drag.pointerId !== event.pointerId) {
+ return
+ }
+
+ const position = previewPositionRef.current
+ previewDragRef.current = null
+ setIsDragging(false)
+ if (commitPosition && !imageOperationInProgressRef.current && position) {
+ updatePosition(position)
+ } else {
+ previewPositionRef.current = null
+ setPreviewPosition(null)
+ }
+ if (event.currentTarget.hasPointerCapture?.(event.pointerId)) {
+ event.currentTarget.releasePointerCapture?.(event.pointerId)
+ }
+ }
+
+ const handlePreviewPointerEnd = (event: PointerEvent<HTMLElement>): void => {
+ finishPreviewDrag(event, true)
+ }
+
+ const handlePreviewPointerCancel = (event: PointerEvent<HTMLElement>): void => {
+ finishPreviewDrag(event, false)
+ }
+
+ const handlePreviewKeyDown = (event: KeyboardEvent<HTMLButtonElement>): void => {
+ if (!image || imageOperationInProgress) {
+ return
+ }
+
+ let nextPosition: ImageTilePosition | null = null
+ if (event.key === 'ArrowLeft') {
+ nextPosition = { ...image.position, x: image.position.x - IMAGE_TILE_POSITION_STEP }
+ } else if (event.key === 'ArrowRight') {
+ nextPosition = { ...image.position, x: image.position.x + IMAGE_TILE_POSITION_STEP }
+ } else if (event.key === 'ArrowUp') {
+ nextPosition = { ...image.position, y: image.position.y - IMAGE_TILE_POSITION_STEP }
+ } else if (event.key === 'ArrowDown') {
+ nextPosition = { ...image.position, y: image.position.y + IMAGE_TILE_POSITION_STEP }
+ }
+
+ if (nextPosition) {
+ event.preventDefault()
+ updatePosition(nextPosition)
+ }
+ }
+
+ const bodyError = textTileValidationErrors.body as string | null
+ let saveDisabledReason: string | null = bodyError
+ if (uploading) {
+ saveDisabledReason = 'Wait for image upload to finish'
+ } else if (!image) {
+ saveDisabledReason = 'Upload an image first'
+ }
+ let uploadDisabledReason: string | null = 'Image uploads are unavailable right now'
+ if (isTextTileSubmitting) {
+ uploadDisabledReason = 'Wait for image save to finish'
+ } else if (uploading) {
+ uploadDisabledReason = 'Wait for image upload to finish'
+ } else if (objectStorageAvailable) {
+ uploadDisabledReason = null
+ }
+ const handleImageSelection = (): void => {
+ if (uploadDisabledReason) {
+ return
+ }
+
+ fileInputRef.current?.click()
+ }
+ const handleFilesToUpload = (files: File[]): void => {
+ if (files.length === 0 || imageOperationInProgressRef.current || uploadRequestedRef.current) {
+ return
+ }
+
+ uploadRequestedRef.current = true
+ setFilesToUpload(files)
+ }
+ const previewClassName = clsx(
+ 'flex aspect-video min-h-48 max-h-64 items-center justify-center overflow-hidden rounded border border-dashed border-primary bg-surface-secondary p-4 touch-none',
+ image && (isDragging ? 'cursor-grabbing' : 'cursor-grab'),
+ !image && (uploadDisabledReason ? 'cursor-not-allowed' : 'cursor-pointer')
+ )
+
+ return (
+ <LemonModal
+ isOpen={isOpen}
+ onClose={handleClose}
+ hasUnsavedInput={hasUnsavedInput || isTextTileSubmitting || uploading}
+ title={isNewTile ? 'Add image' : 'Edit image'}
+ description="Upload one image, choose how it appears in the tile, and reposition it."
+ width={640}
+ data-attr="image-tile-modal"
+ footer={
+ <>
+ <LemonButton
+ type="secondary"
+ onClick={handleClose}
+ disabledReason={imageOperationInProgress ? 'Wait for the image operation to finish' : null}
+ >
+ Cancel
+ </LemonButton>
+ <LemonButton
+ type="primary"
+ form="image-tile-form"
+ htmlType="submit"
+ loading={isTextTileSubmitting || uploading}
+ disabledReason={saveDisabledReason}
+ data-attr={isNewTile ? 'save-new-image-tile' : 'edit-image-tile'}
+ >
+ Save
+ </LemonButton>
+ </>
+ }
+ >
+ <Form
+ logic={textCardModalLogic}
+ props={modalLogicProps}
+ formKey="textTile"
+ id="image-tile-form"
+ enableFormOnSubmit
+ >
+ <div className="flex flex-col gap-4">
+ {image ? (
+ <button
+ ref={setPreviewRef}
+ type="button"
+ className={previewClassName}
+ tabIndex={imageOperationInProgress ? -1 : 0}
+ aria-label="Drag to reposition the image"
+ aria-disabled={imageOperationInProgress || undefined}
+ onPointerDown={handlePreviewPointerDown}
+ onPointerMove={handlePreviewPointerMove}
+ onPointerUp={handlePreviewPointerEnd}
+ onPointerCancel={handlePreviewPointerCancel}
+ onLostPointerCapture={handlePreviewPointerCancel}
+ onKeyDown={handlePreviewKeyDown}
+ data-attr="image-tile-preview"
+ >
+ <img
+ src={previewImage?.src}
+ alt={previewImage?.alt || 'Dashboard image'}
+ draggable={false}
+ className={clsx(
+ 'pointer-events-none h-full w-full',
+ previewImage?.layout === 'cover' ? 'object-cover' : 'object-contain'
+ )}
+ style={{
+ objectPosition: imageTilePositionToCss(previewImage?.position ?? image.position),
+ }}
+ data-attr="image-tile-preview-image"
+ />
+ </button>
+ ) : (
+ <button
+ ref={setPreviewRef}
+ type="button"
+ className={clsx(previewClassName, 'text-secondary')}
+ onClick={handleImageSelection}
+ disabled={!!uploadDisabledReason}
+ data-attr="image-tile-preview"
+ >
+ <span className="flex flex-col items-center gap-2">
+ <IconImage className="text-3xl" />
+ <span>Drag and drop an image or click here to upload an image</span>
+ </span>
+ </button>
+ )}
+ {image && (
+ <LemonButton
+ type="secondary"
+ size="small"
+ className="self-start"
+ onClick={handleImageSelection}
+ disabledReason={uploadDisabledReason}
+ data-attr="replace-image-tile-image"
+ >
+ Replace image
+ </LemonButton>
+ )}
+ {!objectStorageAvailable && !imageOperationInProgress && (
+ <span className="text-sm text-danger" role="alert">
+ Image uploads are unavailable right now.
+ </span>
+ )}
+ {!image && (
+ <span className="text-xs text-secondary">
+ PNG, JPG, GIF, WebP, or AVIF. Maximum size: 4 MB.
+ </span>
+ )}
+ {image && (
+ <>
+ <div className="flex flex-col gap-1">
+ <LemonLabel htmlFor="image-tile-layout">Image display</LemonLabel>
+ <LemonSelect<ImageTileImage['layout']>
+ id="image-tile-layout"
+ value={image.layout}
+ options={IMAGE_TILE_LAYOUT_OPTIONS}
+ onChange={updateLayout}
+ disabledReason={
+ imageOperationInProgress
+ ? 'Wait for the current image operation to finish'
+ : null
+ }
+ fullWidth
+ data-attr="image-tile-layout"
+ />
+ </div>
+ <Field name="transparent_background" label="">
+ {({ value, onChange }) => (
+ <LemonSwitch
+ checked={value}
+ onChange={onChange}
+ label="Transparent card background"
+ disabledReason={
+ imageOperationInProgress
+ ? 'Wait for the current image operation to finish'
+ : null
+ }
+ data-attr="image-tile-transparent-background"
+ />
+ )}
+ </Field>
+ <div className="flex flex-col gap-1">
+ <LemonLabel htmlFor="image-tile-alt">Alt text</LemonLabel>
+ <LemonInput
+ id="image-tile-alt"
+ value={image.alt}
+ onChange={(alt) => updateImageBody({ ...image, alt })}
+ disabledReason={
+ imageOperationInProgress
+ ? 'Wait for the current image operation to finish'
+ : null
+ }
+ fullWidth
+ data-attr="image-tile-alt"
+ />
+ <span className="text-xs text-secondary">
+ Used by screen readers. This text does not display on the image. Leave blank for a
+ decorative image.
+ </span>
+ </div>
+ </>
+ )}
+ <div className="hidden">
+ <LemonFileInput
+ accept={SUPPORTED_IMAGE_UPLOAD_TYPES.join(',')}
+ multiple={false}
+ inputRef={fileInputRef}
+ alternativeDropTargetRef={previewRef as RefObject<HTMLElement>}
+ onChange={handleFilesToUpload}
+ loading={uploading}
+ value={filesToUpload}
+ showUploadedFiles={false}
+ disabledReason={uploadDisabledReason}
+ />
+ </div>
+ {uploadComplete && (
+ <span className="sr-only" role="status">
+ Image uploaded.
+ </span>
+ )}
+ </div>
+ </Form>
+ </LemonModal>
+ )
+}
diff --git a/products/dashboards/frontend/components/ImageTile/imageTileMarkdown.ts b/products/dashboards/frontend/components/ImageTile/imageTileMarkdown.ts
new file mode 100644
index 000000000000..6fd75fb4508c
--- /dev/null
+++ b/products/dashboards/frontend/components/ImageTile/imageTileMarkdown.ts
@@ -0,0 +1,109 @@
+import { Image } from '@tiptap/extension-image'
+
+import { getImageTilePosition, isDefaultImageTilePosition } from './imageTileUtils'
+import type { ImageTileLayout, ImageTilePosition } from './imageTileUtils'
+
+function escapeHtmlAttribute(value: string): string {
+ return value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
+}
+
+function escapeMarkdownImageAlt(value: string): string {
+ return value.replace(/\[/g, '\\[').replace(/\]/g, '\\]')
+}
+
+function requiresHtmlImage(alt: string, title: string): boolean {
+ return /[\\\r\n]/.test(alt) || /[\\"\r\n]/.test(title)
+}
+
+const ImageTileMarkdownExtension = Image.extend({
+ addAttributes() {
+ return {
+ ...this.parent?.(),
+ layout: {
+ default: null,
+ parseHTML: (element: HTMLElement) => (element.getAttribute('data-layout') === 'cover' ? 'cover' : null),
+ renderHTML: (attributes: { layout?: ImageTileLayout | null }) =>
+ attributes.layout === 'cover' ? { 'data-layout': 'cover' } : {},
+ },
+ position: {
+ default: null,
+ parseHTML: (element: HTMLElement) => {
+ const x = element.getAttribute('data-position-x')
+ const y = element.getAttribute('data-position-y')
+
+ return x === null || y === null ? null : { x: Number(x), y: Number(y) }
+ },
+ renderHTML: (attributes: { position?: ImageTilePosition | null }) => {
+ const position = getImageTilePosition(attributes.position)
+
+ return isDefaultImageTilePosition(position)
+ ? {}
+ : {
+ 'data-position-x': String(position.x),
+ 'data-position-y': String(position.y),
+ }
+ },
+ },
+ }
+ },
+
+ renderMarkdown(node) {
+ const attrs = node.attrs || {}
+ const src = attrs.src || ''
+ const alt = attrs.alt || ''
+ const title = attrs.title || ''
+ const layout = attrs.layout === 'cover' ? 'cover' : 'contain'
+ const position = getImageTilePosition(attrs.position)
+ const width = attrs.width
+ const height = attrs.height
+
+ const stringAlt = String(alt)
+ const stringTitle = String(title)
+ const escapedAlt = escapeMarkdownImageAlt(stringAlt)
+ const hasCustomPosition = !isDefaultImageTilePosition(position)
+
+ if (
+ layout === 'contain' &&
+ !width &&
+ !height &&
+ !hasCustomPosition &&
+ !requiresHtmlImage(stringAlt, stringTitle)
+ ) {
+ return title ? `![${escapedAlt}](${src} "${stringTitle}")` : `![${escapedAlt}](${src})`
+ }
+
+ const htmlAttrs = [
+ `src="${escapeHtmlAttribute(String(src))}"`,
+ `alt="${escapeHtmlAttribute(String(alt))}"`,
+ ...(layout === 'cover' ? ['data-layout="cover"'] : []),
+ ...(hasCustomPosition ? [`data-position-x="${position.x}"`, `data-position-y="${position.y}"`] : []),
+ ...(title ? [`title="${escapeHtmlAttribute(stringTitle)}"`] : []),
+ ...(width ? [`width="${escapeHtmlAttribute(String(width))}"`] : []),
+ ...(height ? [`height="${escapeHtmlAttribute(String(height))}"`] : []),
+ ]
+
+ return `<img ${htmlAttrs.join(' ')} />`
+ },
+})
+
+export const IMAGE_TILE_MARKDOWN_EDITABLE_EXTENSION = ImageTileMarkdownExtension.configure({
+ HTMLAttributes: {
+ draggable: 'true',
+ },
+ resize: {
+ enabled: true,
+ directions: ['top', 'bottom', 'left', 'right'],
+ minWidth: 50,
+ minHeight: 50,
+ alwaysPreserveAspectRatio: true,
+ },
+})
+
+export const IMAGE_TILE_MARKDOWN_READONLY_EXTENSION = ImageTileMarkdownExtension.configure({
+ HTMLAttributes: {
+ draggable: 'false',
+ },
+ resize: {
+ enabled: false,
+ },
+})
diff --git a/products/dashboards/frontend/components/ImageTile/imageTileUtils.test.ts b/products/dashboards/frontend/components/ImageTile/imageTileUtils.test.ts
new file mode 100644
index 000000000000..869b3ac48e2b
--- /dev/null
+++ b/products/dashboards/frontend/components/ImageTile/imageTileUtils.test.ts
@@ -0,0 +1,79 @@
+import { textCardConverter } from 'lib/components/Cards/TextCard/textCardMarkdown'
+
+import { getImageOnlyTextCardImage, imageTileToMarkdown } from './imageTileUtils'
+
+describe('imageTileUtils', () => {
+ it.each([
+ ['markdown image', '![A diagram](https://example.com/diagram.png)', 'A diagram', 'contain'],
+ ['HTML image', '<img src="https://example.com/diagram.png" alt="A diagram" />', 'A diagram', 'contain'],
+ ])('detects an image-only text card from %s', (_name, markdown, alt, layout) => {
+ expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({
+ src: 'https://example.com/diagram.png',
+ alt,
+ layout,
+ })
+ })
+
+ it.each([
+ ['plain text', 'A diagram'],
+ ['image caption', '![A diagram](https://example.com/diagram.png)\n\nA caption'],
+ ['multiple images', '![First](https://example.com/first.png)\n\n![Second](https://example.com/second.png)'],
+ ['malformed image markdown', '![A diagram](https://example.com/diagram.png'],
+ ])('keeps %s as a text card', (_name, markdown) => {
+ expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toBeNull()
+ })
+
+ it('creates image markdown through the text card converter', () => {
+ const markdown = imageTileToMarkdown(textCardConverter, {
+ src: 'https://example.com/diagram.png',
+ alt: 'A diagram',
+ })
+
+ expect(markdown).toBe('![A diagram](https://example.com/diagram.png)')
+ })
+
+ it('preserves a cover layout through the text card converter', () => {
+ const markdown = imageTileToMarkdown(textCardConverter, {
+ src: 'https://example.com/diagram.png',
+ alt: 'A diagram',
+ layout: 'cover',
+ })
+
+ expect(markdown).toBe('<img src="https://example.com/diagram.png" alt="A diagram" data-layout="cover" />')
+ expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({ layout: 'cover' })
+ expect(textCardConverter.isRoundTripSafe(markdown)).toBe(true)
+ })
+
+ it('preserves a custom image position through the text card converter', () => {
+ const markdown = imageTileToMarkdown(textCardConverter, {
+ src: 'https://example.com/diagram.png',
+ alt: 'A diagram',
+ layout: 'cover',
+ position: { x: 25, y: 75 },
+ })
+
+ expect(markdown).toBe(
+ '<img src="https://example.com/diagram.png" alt="A diagram" data-layout="cover" data-position-x="25" data-position-y="75" />'
+ )
+ expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({ position: { x: 25, y: 75 } })
+ expect(textCardConverter.isRoundTripSafe(markdown)).toBe(true)
+ })
+
+ it('clamps malformed image positions to the frame', () => {
+ expect(
+ getImageOnlyTextCardImage(
+ textCardConverter,
+ '<img src="https://example.com/diagram.png" alt="A diagram" data-position-x="120" data-position-y="-20" />'
+ )
+ ).toMatchObject({ position: { x: 100, y: 0 } })
+ })
+
+ it.each(['A ] diagram', 'A \\ diagram'])('preserves punctuation in image descriptions: %s', (alt) => {
+ const markdown = imageTileToMarkdown(textCardConverter, {
+ src: 'https://example.com/diagram.png',
+ alt,
+ })
+
+ expect(getImageOnlyTextCardImage(textCardConverter, markdown)).toMatchObject({ alt })
+ })
+})
diff --git a/products/dashboards/frontend/components/ImageTile/imageTileUtils.ts b/products/dashboards/frontend/components/ImageTile/imageTileUtils.ts
new file mode 100644
index 000000000000..0ebf019e71b0
--- /dev/null
+++ b/products/dashboards/frontend/components/ImageTile/imageTileUtils.ts
@@ -0,0 +1,171 @@
+import type { JSONContent } from '@tiptap/core'
+
+import type { TiptapMarkdownConverter } from 'lib/utils/markdown'
+
+export type ImageTileLayout = 'contain' | 'cover'
+
+export interface ImageTilePosition {
+ x: number
+ y: number
+}
+
+export interface ImageTileImage {
+ src: string
+ alt: string
+ title: string
+ layout: ImageTileLayout
+ position: ImageTilePosition
+ width?: number | string | null
+ height?: number | string | null
+}
+
+export const DEFAULT_IMAGE_TILE_POSITION: ImageTilePosition = { x: 50, y: 50 }
+
+const IMAGE_TILE_POSITION_MIN = 0
+const IMAGE_TILE_POSITION_MAX = 100
+const IMAGE_ONLY_TEXT_CARD_CACHE_LIMIT = 100
+const imageOnlyTextCardImageCache = new Map<string, ImageTileImage | null>()
+
+function clampImageTilePosition(value: number): number {
+ if (!Number.isFinite(value)) {
+ return 50
+ }
+
+ return Math.max(IMAGE_TILE_POSITION_MIN, Math.min(IMAGE_TILE_POSITION_MAX, value))
+}
+
+export function getImageTilePosition(value: unknown): ImageTilePosition {
+ const position = value as Partial<ImageTilePosition> | null | undefined
+
+ return {
+ x: clampImageTilePosition(Number(position?.x)),
+ y: clampImageTilePosition(Number(position?.y)),
+ }
+}
+
+export function getImageTileLayout(value: ImageTileLayout | null | undefined): ImageTileLayout {
+ return value === 'cover' ? 'cover' : 'contain'
+}
+
+export function isDefaultImageTilePosition(position: ImageTilePosition): boolean {
+ return position.x === DEFAULT_IMAGE_TILE_POSITION.x && position.y === DEFAULT_IMAGE_TILE_POSITION.y
+}
+
+export function imageTilePositionToCss(position: ImageTilePosition): string {
+ const normalizedPosition = getImageTilePosition(position)
+ return `${normalizedPosition.x}% ${normalizedPosition.y}%`
+}
+
+export function getImageOnlyTextCardImage(
+ converter: TiptapMarkdownConverter,
+ markdown: string | null | undefined
+): ImageTileImage | null {
+ const cacheKey = markdown ?? ''
+ if (imageOnlyTextCardImageCache.has(cacheKey)) {
+ return imageOnlyTextCardImageCache.get(cacheKey) ?? null
+ }
+
+ let doc: JSONContent
+ try {
+ doc = converter.markdownToDoc(markdown)
+ } catch {
+ cacheImageOnlyTextCardImage(cacheKey, null)
+ return null
+ }
+
+ let image: ImageTileImage | null = null
+ let imageCount = 0
+ let hasOtherContent = false
+
+ const visit = (node: JSONContent): void => {
+ if (node.type === 'image') {
+ imageCount += 1
+ const parsedImage = getImageTile(node)
+ if (parsedImage) {
+ image = parsedImage
+ } else {
+ hasOtherContent = true
+ }
+ return
+ }
+
+ if (node.type === 'text') {
+ if (node.text?.trim()) {
+ hasOtherContent = true
+ }
+ return
+ }
+
+ if (node.type === 'doc' || node.type === 'paragraph') {
+ node.content?.forEach(visit)
+ return
+ }
+
+ hasOtherContent = true
+ }
+
+ visit(doc)
+
+ const result = imageCount === 1 && !hasOtherContent ? image : null
+ cacheImageOnlyTextCardImage(cacheKey, result)
+
+ return result
+}
+
+export function imageTileToMarkdown(
+ converter: TiptapMarkdownConverter,
+ image: Pick<ImageTileImage, 'src' | 'alt'> & Partial<ImageTileImage>
+): string {
+ const attrs: Record<string, string | number | ImageTilePosition> = {
+ src: image.src,
+ alt: image.alt,
+ }
+
+ if (image.title) {
+ attrs.title = image.title
+ }
+ if (image.layout === 'cover') {
+ attrs.layout = 'cover'
+ }
+ if (image.position) {
+ attrs.position = getImageTilePosition(image.position)
+ }
+ if (image.width !== undefined && image.width !== null) {
+ attrs.width = image.width
+ }
+ if (image.height !== undefined && image.height !== null) {
+ attrs.height = image.height
+ }
+
+ return converter.docToMarkdown({
+ type: 'doc',
+ content: [{ type: 'image', attrs }],
+ })
+}
+
+function getImageTile(node: JSONContent): ImageTileImage | null {
+ const src = String(node.attrs?.src ?? '').trim()
+ if (!src) {
+ return null
+ }
+
+ return {
+ src,
+ alt: String(node.attrs?.alt ?? ''),
+ title: String(node.attrs?.title ?? ''),
+ layout: getImageTileLayout(node.attrs?.layout),
+ position: getImageTilePosition(node.attrs?.position),
+ width: node.attrs?.width,
+ height: node.attrs?.height,
+ }
+}
+
+function cacheImageOnlyTextCardImage(key: string, image: ImageTileImage | null): void {
+ if (imageOnlyTextCardImageCache.size >= IMAGE_ONLY_TEXT_CARD_CACHE_LIMIT) {
+ const oldestKey = imageOnlyTextCardImageCache.keys().next().value
+ if (oldestKey !== undefined) {
+ imageOnlyTextCardImageCache.delete(oldestKey)
+ }
+ }
+ imageOnlyTextCardImageCache.set(key, image)
+}
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index f3e51c26d4b2..3f13fe0a74ee 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -1164,6 +1164,18 @@ export interface CopyDashboardTileRequestApi {
tileId: number
}
+/**
+ * * `text` - text
+ * * `image` - image
+ */
+export type CreateTextTileRequestTypeEnumApi =
+ (typeof CreateTextTileRequestTypeEnumApi)[keyof typeof CreateTextTileRequestTypeEnumApi]
+
+export const CreateTextTileRequestTypeEnumApi = {
+ Text: 'text',
+ Image: 'image',
+} as const
+
export interface TileLayoutBoxApi {
/** Column position in the dashboard grid (0-indexed). */
x?: number
@@ -1183,8 +1195,13 @@ export interface TileLayoutsApi {
}
export interface CreateTextTileRequestApi {
+ /** Tile type. Use image for a body with exactly one Markdown image. Defaults to text.
+ *
+ * * `text` - text
+ * * `image` - image */
+ type?: CreateTextTileRequestTypeEnumApi
/**
- * Markdown body for the text tile. Supports headings, lists, and inline formatting. Useful as a dashboard section heading, divider, or annotation between insights. Max 4000 characters.
+ * Markdown body for the dashboard tile. Text tiles support headings, lists, and inline formatting. Image tiles require exactly one Markdown image. Max 4000 characters.
* @minLength 1
* @maxLength 4000
*/
diff --git a/products/dashboards/frontend/generated/api.zod.ts b/products/dashboards/frontend/generated/api.zod.ts
index 8326fdafb8f4..ea6bbb01280a 100644
--- a/products/dashboards/frontend/generated/api.zod.ts
+++ b/products/dashboards/frontend/generated/api.zod.ts
@@ -1250,17 +1250,25 @@ export const DashboardsCopyTileCreateBody = /* @__PURE__ */ zod.object({
* Text tiles render as markdown blocks on the dashboard — useful as section headings, dividers,
* or annotations between insight tiles to give the dashboard structure.
*/
+export const dashboardsCreateTextTileCreateBodyTypeDefault = `text`
export const dashboardsCreateTextTileCreateBodyBodyMax = 4000
export const dashboardsCreateTextTileCreateBodyColorMax = 400
export const DashboardsCreateTextTileCreateBody = /* @__PURE__ */ zod.object({
+ type: zod
+ .enum(['text', 'image'])
+ .describe('\* `text` - text\n\* `image` - image')
+ .default(dashboardsCreateTextTileCreateBodyTypeDefault)
+ .describe(
+ 'Tile type. Use image for a body with exactly one Markdown image. Defaults to text.\n\n\* `text` - text\n\* `image` - image'
+ ),
body: zod
.string()
.min(1)
.max(dashboardsCreateTextTileCreateBodyBodyMax)
.describe(
- 'Markdown body for the text tile. Supports headings, lists, and inline formatting. Useful as a dashboard section heading, divider, or annotation between insights. Max 4000 characters.'
+ 'Markdown body for the dashboard tile. Text tiles support headings, lists, and inline formatting. Image tiles require exactly one Markdown image. Max 4000 characters.'
),
layouts: zod
.object({
diff --git a/products/dashboards/frontend/types.ts b/products/dashboards/frontend/types.ts
index 278d0a379759..c6ad97c78716 100644
--- a/products/dashboards/frontend/types.ts
+++ b/products/dashboards/frontend/types.ts
@@ -1,3 +1,5 @@
+export type DashboardAddTileType = 'insight' | 'text_card' | 'image' | 'button' | 'widget'
+
/**
* Product RBAC for gated widget types. New types: extend union here — see products/dashboards/CONTRIBUTING.md.
*/
diff --git a/products/dashboards/manifest.tsx b/products/dashboards/manifest.tsx
index 4d434ba08cb8..96e125007df8 100644
--- a/products/dashboards/manifest.tsx
+++ b/products/dashboards/manifest.tsx
@@ -12,10 +12,8 @@ export const manifest: ProductManifest = {
dashboards: (): string => '/dashboard',
dashboard: (id: string | number, highlightInsightId?: string): string =>
combineUrl(`/dashboard/${id}`, highlightInsightId ? { highlightInsightId } : {}).url,
- dashboardTextTile: (id: string | number, textTileId: string | number): string =>
- `${urls.dashboard(id)}/text-tiles/${textTileId}`,
- dashboardButtonTile: (id: string | number, buttonTileId: string | number): string =>
- `${urls.dashboard(id)}/button-tiles/${buttonTileId}`,
+ dashboardTile: (id: string | number, tileId: string | number): string =>
+ `${urls.dashboard(id)}/tiles/${tileId}`,
dashboardSharing: (id: string | number): string => `/dashboard/${id}/sharing`,
dashboardSubscriptions: (id: string | number): string => `/dashboard/${id}/subscriptions`,
dashboardSubscription: (id: string | number, subscriptionId: string): string =>
diff --git a/products/dashboards/mcp/tools.yaml b/products/dashboards/mcp/tools.yaml
index 2d4fd7192037..0ec597e54cd3 100644
--- a/products/dashboards/mcp/tools.yaml
+++ b/products/dashboards/mcp/tools.yaml
@@ -96,7 +96,7 @@ tools:
- tiles.*.insight.last_viewed_at
- tiles.*.insight.timezone
- tiles.*.insight.resolved_date_range
- dashboard-create-text-tile:
+ dashboard-create-tile:
operation: dashboards_create_text_tile_create
enabled: true
scopes:
@@ -105,17 +105,16 @@ tools:
readOnly: false
destructive: false
idempotent: false
+ input_schema: DashboardTileCreateSchema
enrich_url: '{params.id}'
- title: Create dashboard text tile
+ title: Create dashboard tile
description: >
- Add a markdown text tile to a dashboard. Text tiles render as markdown blocks — useful as section headings,
- dividers, or annotations between insight tiles to give a dashboard structure. The desktop grid is 12 columns
- wide; a typical heading uses a thin full-width banner (e.g. `layouts.sm = {x: 0, y: 0, w: 12, h: 1}`). If
- `layouts` is omitted, the tile is placed using the default layout — use dashboard-reorder-tiles afterwards
- if you need precise placement.
- param_overrides:
- id:
- cast: string-int
+ Add a dashboard tile. Set `type` to text or image. Use Markdown headings, dividers, or notes for a text
+ tile. The desktop grid is 12 columns wide. A typical text heading uses a thin full-width banner (e.g.
+ `layouts.sm = {x: 0, y: 0, w: 12, h: 1}`). If `layouts` is omitted, the dashboard places the tile at the
+ bottom with the default size. Use dashboard-reorder-tiles for precise placement. An image tile body must
+ contain exactly one Markdown image, such as `![Accessible description](https://example.com/image.png)`. The
+ image URL must be reachable by dashboard viewers. Use `layouts` to control the tile size.
dashboard-delete:
operation: dashboards_destroy
enabled: true
diff --git a/products/dashboards/package.json b/products/dashboards/package.json
index d27f1896a001..01ccb593ea3d 100644
--- a/products/dashboards/package.json
+++ b/products/dashboards/package.json
@@ -6,6 +6,7 @@
"dependencies": {
"fast-equals": "catalog:",
"kea": "catalog:",
+ "kea-forms": "catalog:",
"kea-loaders": "catalog:",
"kea-router": "catalog:",
"posthog-js": "catalog:",
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.test.ts b/products/posthog_ai/frontend/policy/toolPolicy.test.ts
index d8300277df7a..dd71ffe5010d 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.test.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.test.ts
@@ -194,8 +194,8 @@ describe('toolPolicy', () => {
true,
],
[
- 'dashboard-create-text-tile',
- makeRecord({ input: { command: 'call dashboard-create-text-tile {"dashboard_id":1}' } }),
+ 'dashboard-create-tile',
+ makeRecord({ input: { command: 'call dashboard-create-tile {"dashboard_id":1}' } }),
true,
],
['dashboard-tile-copy', makeRecord({ input: { command: 'call dashboard-tile-copy {"id":1}' } }), true],
diff --git a/products/posthog_ai/frontend/policy/toolPolicy.ts b/products/posthog_ai/frontend/policy/toolPolicy.ts
index 6d4b545af47d..ba1b327c60b6 100644
--- a/products/posthog_ai/frontend/policy/toolPolicy.ts
+++ b/products/posthog_ai/frontend/policy/toolPolicy.ts
@@ -151,6 +151,7 @@ export function defaultPermissionDecision(record: PermissionRequestRecord): Perm
*/
const PERSIST_PROMPT_SUB_TOOLS = new Set([
'dashboard-create',
+ 'dashboard-create-tile',
'dashboard-create-text-tile',
'dashboard-tile-copy',
'dashboard-widgets-batch-add',
diff --git a/products/tasks/backend/constants.py b/products/tasks/backend/constants.py
index c698a9d119ff..5e0d3c5f0f5c 100644
--- a/products/tasks/backend/constants.py
+++ b/products/tasks/backend/constants.py
@@ -295,6 +295,7 @@ POSTHOG_EXEC_DESTRUCTIVE_SUB_TOOLS: tuple[str, ...] = (
# foreground streams.
POSTHOG_EXEC_PERSIST_SUB_TOOLS: tuple[str, ...] = (
"dashboard-create",
+ "dashboard-create-tile",
"dashboard-create-text-tile",
"dashboard-tile-copy",
"dashboard-widgets-batch-add",
diff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.json
index 8b37504f3a85..7833bfb1f146 100644
--- a/services/mcp/schema/generated-tool-definitions.json
+++ b/services/mcp/schema/generated-tool-definitions.json
@@ -2276,12 +2276,12 @@
"readOnlyHint": false
}
},
- "dashboard-create-text-tile": {
- "description": "Add a markdown text tile to a dashboard. Text tiles render as markdown blocks — useful as section headings, dividers, or annotations between insight tiles to give a dashboard structure. The desktop grid is 12 columns wide; a typical heading uses a thin full-width banner (e.g. `layouts.sm = {x: 0, y: 0, w: 12, h: 1}`). If `layouts` is omitted, the tile is placed using the default layout — use dashboard-reorder-tiles afterwards if you need precise placement.",
+ "dashboard-create-tile": {
+ "description": "Add a dashboard tile. Set `type` to text or image. Use Markdown headings, dividers, or notes for a text tile. The desktop grid is 12 columns wide. A typical text heading uses a thin full-width banner (e.g. `layouts.sm = {x: 0, y: 0, w: 12, h: 1}`). If `layouts` is omitted, the dashboard places the tile at the bottom with the default size. Use dashboard-reorder-tiles for precise placement. An image tile body must contain exactly one Markdown image, such as `![Accessible description](https://example.com/image.png)`. The image URL must be reachable by dashboard viewers. Use `layouts` to control the tile size.",
"category": "Dashboards",
"feature": "dashboards",
- "summary": "Create dashboard text tile",
- "title": "Create dashboard text tile",
+ "summary": "Create dashboard tile",
+ "title": "Create dashboard tile",
"required_scopes": ["dashboard:write"],
"annotations": {
"destructiveHint": false,
diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.json
index b319260933b1..d68ad53851b3 100644
--- a/services/mcp/schema/tool-definitions-all.json
+++ b/services/mcp/schema/tool-definitions-all.json
@@ -2291,12 +2291,12 @@
"readOnlyHint": false
}
},
- "dashboard-create-text-tile": {
- "description": "Add a markdown text tile to a dashboard. Text tiles render as markdown blocks — useful as section headings, dividers, or annotations between insight tiles to give a dashboard structure. The desktop grid is 12 columns wide; a typical heading uses a thin full-width banner (e.g. `layouts.sm = {x: 0, y: 0, w: 12, h: 1}`). If `layouts` is omitted, the tile is placed using the default layout — use dashboard-reorder-tiles afterwards if you need precise placement.",
+ "dashboard-create-tile": {
+ "description": "Add a dashboard tile. Set `type` to text or image. Use Markdown headings, dividers, or notes for a text tile. The desktop grid is 12 columns wide. A typical text heading uses a thin full-width banner (e.g. `layouts.sm = {x: 0, y: 0, w: 12, h: 1}`). If `layouts` is omitted, the dashboard places the tile at the bottom with the default size. Use dashboard-reorder-tiles for precise placement. An image tile body must contain exactly one Markdown image, such as `![Accessible description](https://example.com/image.png)`. The image URL must be reachable by dashboard viewers. Use `layouts` to control the tile size.",
"category": "Dashboards",
"feature": "dashboards",
- "summary": "Create dashboard text tile",
- "title": "Create dashboard text tile",
+ "summary": "Create dashboard tile",
+ "title": "Create dashboard tile",
"required_scopes": ["dashboard:write"],
"annotations": {
"destructiveHint": false,
diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.json
index 9f5c7f1ec3a6..0a31ca8a74eb 100644
--- a/services/mcp/schema/tool-inputs.json
+++ b/services/mcp/schema/tool-inputs.json
@@ -55,6 +55,97 @@
"maximum": 9007199254740991,
"description": "Version returned by channel-instructions-retrieve. Use 0 when the channel has no instructions."
},
+ "DashboardTileCreateSchema": {
+ "type": "object",
+ "properties": {
+ "id": {
+ "type": "integer",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991,
+ "description": "Dashboard ID. Use dashboard-get or dashboards-get-all to find it."
+ },
+ "type": {
+ "type": "string",
+ "enum": ["text", "image"],
+ "description": "Tile type. Use text for Markdown content. Use image for a body with exactly one Markdown image."
+ },
+ "body": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 4000,
+ "description": "Markdown body. For image, provide exactly one Markdown image. For text, provide Markdown content that is not an image-only body."
+ },
+ "layouts": {
+ "description": "Optional dashboard-grid layout for desktop (sm) and mobile (xs).",
+ "type": "object",
+ "properties": {
+ "sm": {
+ "type": "object",
+ "properties": {
+ "x": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991
+ },
+ "y": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991
+ },
+ "w": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 9007199254740991
+ },
+ "h": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 9007199254740991
+ }
+ }
+ },
+ "xs": {
+ "type": "object",
+ "properties": {
+ "x": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991
+ },
+ "y": {
+ "type": "integer",
+ "minimum": 0,
+ "maximum": 9007199254740991
+ },
+ "w": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 9007199254740991
+ },
+ "h": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 9007199254740991
+ }
+ }
+ }
+ }
+ },
+ "color": {
+ "description": "Optional tile accent color.",
+ "anyOf": [
+ {
+ "type": "string",
+ "maxLength": 400
+ },
+ {
+ "type": "null"
+ }
+ ]
+ }
+ },
+ "required": ["id", "type", "body"]
+ },
"DebugMcpUiAppsSchema": {
"type": "object",
"properties": {
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 97fcbf0af163..2d651d4d880a 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -19752,6 +19752,18 @@ export namespace Schemas {
always_include?: boolean;
}
+ /**
+ * * `text` - text
+ * * `image` - image
+ */
+ export type CreateTextTileRequestTypeEnum = typeof CreateTextTileRequestTypeEnum[keyof typeof CreateTextTileRequestTypeEnum];
+
+
+ export const CreateTextTileRequestTypeEnum = {
+ Text: 'text',
+ Image: 'image',
+ } as const;
+
export interface TileLayoutBox {
/** Column position in the dashboard grid (0-indexed). */
x?: number;
@@ -19771,8 +19783,13 @@ export namespace Schemas {
}
export interface CreateTextTileRequest {
+ /** Tile type. Use image for a body with exactly one Markdown image. Defaults to text.
+ *
+ * * `text` - text
+ * * `image` - image */
+ type?: CreateTextTileRequestTypeEnum;
/**
- * Markdown body for the text tile. Supports headings, lists, and inline formatting. Useful as a dashboard section heading, divider, or annotation between insights. Max 4000 characters.
+ * Markdown body for the dashboard tile. Text tiles support headings, lists, and inline formatting. Image tiles require exactly one Markdown image. Max 4000 characters.
* @minLength 1
* @maxLength 4000
*/
diff --git a/services/mcp/src/generated/dashboards/api.ts b/services/mcp/src/generated/dashboards/api.ts
index 7c641cb4a3c1..371e9ac7796f 100644
--- a/services/mcp/src/generated/dashboards/api.ts
+++ b/services/mcp/src/generated/dashboards/api.ts
@@ -1102,17 +1102,25 @@ export const DashboardsCreateTextTileCreateQueryParams = () => zod.object({
format: zod.enum(['json', 'txt']).optional(),
})
+export const dashboardsCreateTextTileCreateBodyTypeDefault = `text`
export const dashboardsCreateTextTileCreateBodyBodyMax = 4000
export const dashboardsCreateTextTileCreateBodyColorMax = 400
export const DashboardsCreateTextTileCreateBody = () => zod.object({
+ type: zod
+ .enum(['text', 'image'])
+ .describe('\* `text` - text\n\* `image` - image')
+ .default(dashboardsCreateTextTileCreateBodyTypeDefault)
+ .describe(
+ 'Tile type. Use image for a body with exactly one Markdown image. Defaults to text.\n\n\* `text` - text\n\* `image` - image'
+ ),
body: zod
.string()
.min(1)
.max(dashboardsCreateTextTileCreateBodyBodyMax)
.describe(
- 'Markdown body for the text tile. Supports headings, lists, and inline formatting. Useful as a dashboard section heading, divider, or annotation between insights. Max 4000 characters.'
+ 'Markdown body for the dashboard tile. Text tiles support headings, lists, and inline formatting. Image tiles require exactly one Markdown image. Max 4000 characters.'
),
layouts: zod
.object({
diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.ts
index 706ef21940fe..7c1d8bd433ff 100644
--- a/services/mcp/src/schema/tool-inputs.ts
+++ b/services/mcp/src/schema/tool-inputs.ts
@@ -11,6 +11,35 @@ export const ChannelInstructionsBaseVersionSchema = z
.max(9007199254740991)
.describe('Version returned by channel-instructions-retrieve. Use 0 when the channel has no instructions.')
+const DashboardTileLayoutSchema = z.object({
+ x: z.number().int().min(0).optional(),
+ y: z.number().int().min(0).optional(),
+ w: z.number().int().min(1).optional(),
+ h: z.number().int().min(1).optional(),
+})
+
+export const DashboardTileCreateSchema = z.object({
+ id: z.number().int().positive().describe('Dashboard ID. Use dashboard-get or dashboards-get-all to find it.'),
+ type: z
+ .enum(['text', 'image'])
+ .describe('Tile type. Use text for Markdown content. Use image for a body with exactly one Markdown image.'),
+ body: z
+ .string()
+ .min(1)
+ .max(4000)
+ .describe(
+ 'Markdown body. For image, provide exactly one Markdown image. For text, provide Markdown content that is not an image-only body.'
+ ),
+ layouts: z
+ .object({
+ sm: DashboardTileLayoutSchema.optional(),
+ xs: DashboardTileLayoutSchema.optional(),
+ })
+ .optional()
+ .describe('Optional dashboard-grid layout for desktop (sm) and mobile (xs).'),
+ color: z.string().max(400).nullable().optional().describe('Optional tile accent color.'),
+})
+
export const BusinessKnowledgeUrlSourceCreateSchema = z.object({
name: z
.string()
diff --git a/services/mcp/src/tools/generated/dashboards.ts b/services/mcp/src/tools/generated/dashboards.ts
index fe63f2b4c885..deb95e7a11ec 100644
--- a/services/mcp/src/tools/generated/dashboards.ts
+++ b/services/mcp/src/tools/generated/dashboards.ts
@@ -3,6 +3,7 @@ import { z } from 'zod'
import type { Schemas } from '@/api/generated'
import * as orvalSchemas from '@/generated/dashboards/api'
+import { DashboardTileCreateSchema } from '@/schema/tool-inputs'
import { castStringToInt } from '@/tools/cast-helpers'
import {
withPostHogUrl,
@@ -123,35 +124,18 @@ const dashboardCreate = (): ToolBase<
},
})
-const DashboardCreateTextTileSchema = () => {
- const DashboardsCreateTextTileCreateBody = orvalSchemas.DashboardsCreateTextTileCreateBody()
- const DashboardsCreateTextTileCreateParams = orvalSchemas.DashboardsCreateTextTileCreateParams()
- return DashboardsCreateTextTileCreateParams.omit({ project_id: true })
- .extend(DashboardsCreateTextTileCreateBody.shape)
- .extend({ id: z.preprocess(castStringToInt, DashboardsCreateTextTileCreateParams.shape['id']) })
-}
+const DashboardCreateTileSchema = () => DashboardTileCreateSchema
-const dashboardCreateTextTile = (): ToolBase<
- ReturnType<typeof DashboardCreateTextTileSchema>,
- WithPostHogUrl<Schemas.DashboardTile>
-> => ({
- name: 'dashboard-create-text-tile',
- schema: DashboardCreateTextTileSchema(),
- handler: async (context: Context, params: z.infer<ReturnType<typeof DashboardCreateTextTileSchema>>) => {
+const dashboardCreateTile = (): ToolBase<ReturnType<typeof DashboardCreateTileSchema>, Schemas.DashboardTile> => ({
+ name: 'dashboard-create-tile',
+ schema: DashboardCreateTileSchema(),
+ handler: async (context: Context, params: z.infer<ReturnType<typeof DashboardCreateTileSchema>>) => {
const projectId = await context.stateManager.getProjectId()
- const body: Record<string, unknown> = {}
- if (params.body !== undefined) {
- body['body'] = params.body
- }
- if (params.layouts !== undefined) {
- body['layouts'] = params.layouts
- }
- if (params.color !== undefined) {
- body['color'] = params.color
- }
+ const parsedParams = DashboardCreateTileSchema().parse(params)
+ const { id, ...body } = parsedParams
const result = await context.api.request<Schemas.DashboardTile>({
method: 'POST',
- path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/${encodeURIComponent(String(params.id))}/create_text_tile/`,
+ path: `/api/projects/${encodeURIComponent(String(projectId))}/dashboards/${encodeURIComponent(String(id))}/create_text_tile/`,
body,
})
return await withPostHogUrl(context, result, `/dashboard/${params.id}`)
@@ -782,7 +766,7 @@ const dashboardsMoveTilePartialUpdate = (): ToolBase<
export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {
'dashboard-create': dashboardCreate,
- 'dashboard-create-text-tile': dashboardCreateTextTile,
+ 'dashboard-create-tile': dashboardCreateTile,
'dashboard-delete': dashboardDelete,
'dashboard-delete-tile': dashboardDeleteTile,
'dashboard-get': dashboardGet,
diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.json
index 9699e99b28f3..43b328fa7be2 100644
--- a/services/mcp/src/tools/links/app-url-manifest.json
+++ b/services/mcp/src/tools/links/app-url-manifest.json
@@ -419,11 +419,6 @@
"params": ["id"],
"scope": "project"
},
- "dashboardButtonTile": {
- "template": "/dashboard/{id}/button-tiles/{buttonTileId}",
- "params": ["id", "buttonTileId"],
- "scope": "project"
- },
"dashboardSharing": {
"template": "/dashboard/{id}/sharing",
"params": ["id"],
@@ -444,9 +439,9 @@
"params": ["templateId"],
"scope": "project"
},
- "dashboardTextTile": {
- "template": "/dashboard/{id}/text-tiles/{textTileId}",
- "params": ["id", "textTileId"],
+ "dashboardTile": {
+ "template": "/dashboard/{id}/tiles/{tileId}",
+ "params": ["id", "tileId"],
"scope": "project"
},
"dashboards": {
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create-text-tile.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create-text-tile.json
deleted file mode 100644
index 6a6ec9210b73..000000000000
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create-text-tile.json
+++ /dev/null
@@ -1,79 +0,0 @@
-{
- "$schema": "https://json-schema.org/draft/2020-12/schema",
- "properties": {
- "body": {
- "description": "Markdown body for the text tile. Supports headings, lists, and inline formatting. Useful as a dashboard section heading, divider, or annotation between insights. Max 4000 characters.",
- "maxLength": 4000,
- "minLength": 1,
- "type": "string"
- },
- "color": {
- "anyOf": [
- {
- "maxLength": 400,
- "type": "string"
- },
- {
- "type": "null"
- }
- ],
- "description": "Optional accent color name (e.g. 'blue', 'green', 'purple', 'black')."
- },
- "id": {
- "description": "A unique integer value identifying this dashboard.",
- "type": "number"
- },
- "layouts": {
- "description": "Optional grid layout per breakpoint. If omitted, the tile is placed at the bottom of the dashboard using the default size. Text tiles typically use a thin full-width banner (e.g. w=12, h=1).",
- "properties": {
- "sm": {
- "description": "Layout for the standard (desktop) breakpoint. The grid is 12 columns wide.",
- "properties": {
- "h": {
- "description": "Height in grid rows.",
- "type": "number"
- },
- "w": {
- "description": "Width in grid columns. The desktop grid is 12 columns wide.",
- "type": "number"
- },
- "x": {
- "description": "Column position in the dashboard grid (0-indexed).",
- "type": "number"
- },
- "y": {
- "description": "Row position in the dashboard grid (0-indexed).",
- "type": "number"
- }
- },
- "type": "object"
- },
- "xs": {
- "description": "Layout for the small (mobile) breakpoint. The grid is 1 column wide.",
- "properties": {
- "h": {
- "description": "Height in grid rows.",
- "type": "number"
- },
- "w": {
- "description": "Width in grid columns. The desktop grid is 12 columns wide.",
- "type": "number"
- },
- "x": {
- "description": "Column position in the dashboard grid (0-indexed).",
- "type": "number"
- },
- "y": {
- "description": "Row position in the dashboard grid (0-indexed).",
- "type": "number"
- }
- },
- "type": "object"
- }
- },
- "type": "object"
- }
- },
- "required": ["id", "body"],
- "type": "object"
-}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create-tile.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create-tile.json
new file mode 100644
index 000000000000..e15fb2e5b324
--- /dev/null
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/dashboard-create-tile.json
@@ -0,0 +1,92 @@
+{
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "properties": {
+ "body": {
+ "description": "Markdown body. For image, provide exactly one Markdown image. For text, provide Markdown content that is not an image-only body.",
+ "maxLength": 4000,
+ "minLength": 1,
+ "type": "string"
+ },
+ "color": {
+ "anyOf": [
+ {
+ "maxLength": 400,
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Optional tile accent color."
+ },
+ "id": {
+ "description": "Dashboard ID. Use dashboard-get or dashboards-get-all to find it.",
+ "exclusiveMinimum": 0,
+ "maximum": 9007199254740991,
+ "type": "integer"
+ },
+ "layouts": {
+ "description": "Optional dashboard-grid layout for desktop (sm) and mobile (xs).",
+ "properties": {
+ "sm": {
+ "properties": {
+ "h": {
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "w": {
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "x": {
+ "maximum": 9007199254740991,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "y": {
+ "maximum": 9007199254740991,
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "type": "object"
+ },
+ "xs": {
+ "properties": {
+ "h": {
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "w": {
+ "maximum": 9007199254740991,
+ "minimum": 1,
+ "type": "integer"
+ },
+ "x": {
+ "maximum": 9007199254740991,
+ "minimum": 0,
+ "type": "integer"
+ },
+ "y": {
+ "maximum": 9007199254740991,
+ "minimum": 0,
+ "type": "integer"
+ }
+ },
+ "type": "object"
+ }
+ },
+ "type": "object"
+ },
+ "type": {
+ "description": "Tile type. Use text for Markdown content. Use image for a body with exactly one Markdown image.",
+ "enum": ["text", "image"],
+ "type": "string"
+ }
+ },
+ "required": ["id", "type", "body"],
+ "type": "object"
+}
diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
index b3b37159abbe..70d0af9d006b 100644
--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json
@@ -13,7 +13,7 @@
"type": "object"
},
"url": {
- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/button-tiles/{buttonTileId}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/text-tiles/{textTileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/billing/authorization_status\n/business-knowledge\n/canvas\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/comments\n/data-management/comments/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors/{handle}\n/engineering-analytics/health\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/test-health\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/error_tracking/{id}/fingerprints\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/themes/custom-css\n/toolbar\n/tracing\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",
"type": "string"
}
},