: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-catalog): create markdown metrics from the modal, author on the metric page (#79834)
Thiago Salvatoree7d41c82e440
diff --git a/products/data_catalog/frontend/components/NewMetricModal.tsx b/products/data_catalog/frontend/components/NewMetricModal.tsxindex e52667ed26c5..66dee890d6bd 100644--- a/products/data_catalog/frontend/components/NewMetricModal.tsx+++ b/products/data_catalog/frontend/components/NewMetricModal.tsx@@ -8,15 +8,14 @@ import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelectimport { LemonModal } from 'lib/lemon-ui/LemonModal'import { LemonSegmentedButton } from 'lib/lemon-ui/LemonSegmentedButton'import { LemonTextArea } from 'lib/lemon-ui/LemonTextArea'-import { LemonTextAreaMarkdown } from 'lib/lemon-ui/LemonTextArea/LemonTextAreaMarkdown'import { validateMetricDescription, validateMetricName } from '../common'import { metricsLogic, NewMetricDefinitionType } from '../metricsLogic'-// The Text (markdown) option is hidden until its editor UI is polished.const DEFINITION_TYPE_OPTIONS: { value: NewMetricDefinitionType; label: string }[] = [{ value: 'sql', label: 'SQL' },{ value: 'insight', label: 'Insight' },+ { value: 'markdown', label: 'Markdown' },]export function NewMetricModal(): JSX.Element {@@ -37,9 +36,7 @@ export function NewMetricModal(): JSX.Element {? 'Create SQL metrics from the SQL editor': newMetricForm.definitionType === 'insight' && !newMetricForm.sourceInsightShortId? 'Choose an insight'- : newMetricForm.definitionType === 'markdown' && !newMetricForm.markdown.trim()- ? 'Add the markdown definition'- : undefined+ : undefinedreturn (<LemonModal isOpen={newMetricModalOpen} onClose={closeNewMetricModal} width={640} title="New metric">@@ -96,13 +93,9 @@ export function NewMetricModal(): JSX.Element {</LemonField.Pure>{newMetricForm.definitionType === 'markdown' && (- <LemonField.Pure label="Text">- <LemonTextAreaMarkdown- value={newMetricForm.markdown}- onChange={(markdown) => setNewMetricForm({ markdown })}- placeholder="Numbered steps describing how to calculate this metric"- />- </LemonField.Pure>+ <LemonBanner type="info">+ You'll write the definition on the metric page after creating it.+ </LemonBanner>)}{newMetricForm.definitionType === 'sql' && (diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.tsindex a38cb923bf27..7311bab4deca 100644--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.test.ts@@ -1,5 +1,8 @@+import { router } from 'kea-router'+import { ApiError } from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'@@ -171,6 +174,24 @@ describe('dataCatalogMetricSceneLogic', () => {stubLogic.unmount()})+ it('opens the markdown editor once loaded when arriving with ?edit=definition', async () => {+ jest.clearAllMocks()+ ;(dataCatalogMetricsRetrieve as jest.Mock).mockResolvedValue(+ buildMetric({ name: 'stub_metric', definition_kind: null, definition: null, status: 'proposed' })+ )+ const stubLogic = dataCatalogMetricSceneLogic({ name: 'stub_metric' })+ stubLogic.mount()+ await expectLogic(stubLogic).toDispatchActions(['loadMetricSuccess'])++ router.actions.push(urls.dataCatalogMetric('stub_metric'), { edit: 'definition' })+ await expectLogic(stubLogic).toDispatchActions(['loadMetricSuccess'])++ expect(stubLogic.values.editingDefinition).toBe(true)+ expect(stubLogic.values.draftMarkdown).toEqual(MARKDOWN_DEFINITION_TEMPLATE)+ expect(router.values.searchParams.edit).toBeUndefined()+ stubLogic.unmount()+ })+it('issues no requests for a traversal-shaped metric name', async () => {// props.name is interpolated unencoded into the request path, so a "../"-shaped route// value must never reach retrieve/run/approve/refresh/update/delete.diff --git a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsxindex f7f2cfc97220..6d222c98bab4 100644--- a/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx+++ b/products/data_catalog/frontend/dataCatalogMetricSceneLogic.tsx@@ -59,6 +59,7 @@ export interface dataCatalogMetricSceneLogicValues {metric: DataCatalogMetricApi | nullmetricLoading: booleanmutating: boolean+ pendingDefinitionEdit: booleanrunResult: DataCatalogMetricRunApi | nullrunResultLoading: boolean}@@ -137,6 +138,9 @@ export interface dataCatalogMetricSceneLogicActions {setMutating: (mutating: boolean) => {mutating: boolean}+ setPendingDefinitionEdit: (pendingDefinitionEdit: boolean) => {+ pendingDefinitionEdit: boolean+ }startEditingMarkdown: () => {value: true}@@ -175,6 +179,7 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(setDraftSql: (draftSql: string) => ({ draftSql }),setDraftMarkdown: (draftMarkdown: string) => ({ draftMarkdown }),startEditingMarkdown: true,+ setPendingDefinitionEdit: (pendingDefinitionEdit: boolean) => ({ pendingDefinitionEdit }),}),loaders(({ props }) => ({metric: [@@ -227,6 +232,12 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(setDraftMarkdown: (_, { draftMarkdown }) => draftMarkdown,},],+ pendingDefinitionEdit: [+ false,+ {+ setPendingDefinitionEdit: (_, { pendingDefinitionEdit }) => pendingDefinitionEdit,+ },+ ],}),selectors({breadcrumbs: [@@ -246,6 +257,11 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(}actions.setDraftSql(definitionField(metric, 'query'))actions.setDraftMarkdown(definitionField(metric, 'markdown'))+ // Deferred until the metric is loaded, otherwise the draft sync above would wipe the seeded template.+ if (values.pendingDefinitionEdit) {+ actions.setPendingDefinitionEdit(false)+ actions.startEditingMarkdown()+ }},setMetric: ({ metric }) => {actions.setDraftSql(definitionField(metric, 'query'))@@ -330,7 +346,12 @@ export const dataCatalogMetricSceneLogic = kea<dataCatalogMetricSceneLogicType>(},})),urlToAction(({ actions }) => ({- [urls.dataCatalogMetric(':name')]: () => {+ [urls.dataCatalogMetric(':name')]: (_, searchParams) => {+ if (searchParams.edit === 'definition') {+ actions.setPendingDefinitionEdit(true)+ // Consume the param so refresh or back does not reopen the editor.+ router.actions.replace(router.values.location.pathname)+ }actions.loadMetric()},})),diff --git a/products/data_catalog/frontend/metricsLogic.test.ts b/products/data_catalog/frontend/metricsLogic.test.tsindex d9e5bcc4084c..2924f2fbe202 100644--- a/products/data_catalog/frontend/metricsLogic.test.ts+++ b/products/data_catalog/frontend/metricsLogic.test.ts@@ -1,5 +1,8 @@+import { router } from 'kea-router'+import { ApiError } from 'lib/api'import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'+import { urls } from 'scenes/urls'import { initKeaTests } from '~/test/init'import { expectLogic } from '~/test/keaTestUtils'@@ -115,6 +118,26 @@ describe('metricsLogic', () => {expect(logic.values.allMetrics.map((metric) => metric.name)).toContain('monthly_active_users')})+ it('creates a markdown metric as a stub and routes to the metric page to author it', async () => {+ ;(dataCatalogMetricsCreate as jest.Mock).mockResolvedValue(+ buildMetric({ id: 'metric-4', name: 'mrr', definition_kind: null })+ )++ logic.actions.openNewMetricModal()+ logic.actions.setNewMetricForm({+ name: 'mrr',+ description: 'Monthly recurring revenue',+ definitionType: 'markdown',+ })+ logic.actions.createMetric()+ await expectLogic(logic).toFinishAllListeners()++ const body = (dataCatalogMetricsCreate as jest.Mock).mock.calls.at(-1)?.[1]+ expect(body.definition).toBeUndefined()+ expect(router.values.location.pathname).toContain(urls.dataCatalogMetric('mrr'))+ expect(router.values.searchParams.edit).toEqual('definition')+ })+it('does not create a SQL metric from the modal', async () => {logic.actions.openNewMetricModal()logic.actions.setNewMetricForm({diff --git a/products/data_catalog/frontend/metricsLogic.tsx b/products/data_catalog/frontend/metricsLogic.tsxindex 7959b7750a8a..66ee60bb3193 100644--- a/products/data_catalog/frontend/metricsLogic.tsx+++ b/products/data_catalog/frontend/metricsLogic.tsx@@ -36,7 +36,6 @@ export interface NewMetricForm {description: stringunit: stringdefinitionType: NewMetricDefinitionType- markdown: stringsourceInsightShortId: string}@@ -46,7 +45,6 @@ export const EMPTY_NEW_METRIC_FORM: NewMetricForm = {description: '',unit: '',definitionType: 'sql',- markdown: '',sourceInsightShortId: '',}@@ -62,16 +60,10 @@ export interface MetricFromInsightRequest {source_insight_short_id: string}-const MARKDOWN_DEFINITION_KIND = 'MarkdownDefinition'-function projectId(): string {return String(ApiConfig.getCurrentTeamId())}-function buildMarkdownDefinition(markdown: string): Record<string, unknown> {- return { kind: MARKDOWN_DEFINITION_KIND, markdown }-}-function apiErrorDetail(error: unknown): string | null {return error instanceof ApiError ? error.detail : null}@@ -342,12 +334,13 @@ export const metricsLogic = kea<metricsLogicType>([}const form = values.newMetricFormif (form.definitionType === 'sql') {- // SQL metrics are defined from the SQL editor, so the else branch below only handles markdown.lemonToast.error('Create SQL metrics from the SQL editor.')return}actions.setCreatingMetric(true)try {+ // A markdown metric is created as a stub; its definition is authored on the+ // metric page, where the editor has room.const created = await dataCatalogMetricsCreate(projectId(), {name: form.name,display_name: form.display_name || undefined,@@ -355,12 +348,15 @@ export const metricsLogic = kea<metricsLogicType>([unit: form.unit || undefined,...(form.definitionType === 'insight'? { source_insight_short_id: form.sourceInsightShortId }- : { definition: buildMarkdownDefinition(form.markdown) }),+ : {}),created_source: 'user',})actions.loadMetricsSuccess([created, ...values.allMetrics])actions.closeNewMetricModal()lemonToast.success('Metric created')+ if (form.definitionType === 'markdown') {+ router.actions.push(urls.dataCatalogMetric(created.name), { edit: 'definition' })+ }} catch (error) {lemonToast.error(apiErrorDetail(error) || 'Could not create the metric. Check the fields and try again.'