: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): slash commands and catalog references in the markdown editor (#79836)
Thiago Salvatore128807f9ad37
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 357bbb4ee88b..75611d98aaed 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -1216,6 +1216,14 @@ snapshots:hash: v1.k794b7964.d0e2ad002bf6d7126c2939fcf65a95ad02f915061ac39616f897c4c8f0b9cdef.Rlro8jpQStkVB6I7sLqygnNvq6WiVlgWK8XFlbLSyy0components-markdown-editor-inline--with-slash-commands--light:hash: v1.k794b7964.8b10234bf99bc2e9b1bae52af562885e611b6e65f8849e91545db592f90d4fbb.lIly8VIiaje29Y8EYFuK5AZ9WKskSJqe97MmbpjLbDo+ components-markdown-editor-metric-definition--default--dark:+ hash: v1.k794b7964.06b0579ec23e05a6250c87e79ed080c2e4fb2b7296979f06186fb31e47ae12fd.bXC6YLv3mFz35mSChoJX0grLmFhHkpFf3N55gVBWE_4+ components-markdown-editor-metric-definition--default--light:+ hash: v1.k794b7964.e34ddb04224c266b3e93d0c499e6acf383fd3aca74960b966118a4ffa6d8eaae.1TXDvKjupqBFjvwmcaSyDe5fKClqcUUnOfZ2XbCq6fQ+ components-markdown-editor-metric-definition--legacy-fallback-for-unsafe-markdown--dark:+ hash: v1.k794b7964.a5f1064ac0311683379bb9ee08d430c942aa64229389777a18881bf0320f23b0.6Za8l5LnjHlxjS0drxiCPjdfyfdgQLbsWLxTccDc-Cs+ components-markdown-editor-metric-definition--legacy-fallback-for-unsafe-markdown--light:+ hash: v1.k794b7964.7bac2079ca7516ff5a4d7acd277641bb090377073e8ffbc380c487c870956581.Xl8nazpgWFzOevGh9CHrilQkf_QPuv_BZbV3gRJmEDscomponents-markdown-editor-rich--with-markdown--dark:hash: v1.k794b7964.b933911885203330331bde8bd799fd74fcd4e5964ba7fba4538dd075f07e32dc.QhPFXSfVCoIMya1xKmHLdyh3P9dJf-zNL4_zLUNqgqUcomponents-markdown-editor-rich--with-markdown--light:diff --git a/products/data_catalog/frontend/components/CatalogReferencePickerModal.tsx b/products/data_catalog/frontend/components/CatalogReferencePickerModal.tsxnew file mode 100644index 000000000000..65c463520707--- /dev/null+++ b/products/data_catalog/frontend/components/CatalogReferencePickerModal.tsx@@ -0,0 +1,43 @@+import { useValues } from 'kea'++import { LemonInputSelect } from 'lib/lemon-ui/LemonInputSelect/LemonInputSelect'+import { LemonModal } from 'lib/lemon-ui/LemonModal'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'++import { metricsLogic } from '../metricsLogic'+import type { CatalogReferenceKind } from './metricMarkdownSlashCommands'++export function CatalogReferencePickerModal({+ kind,+ onSelect,+ onClose,+}: {+ kind: CatalogReferenceKind+ onSelect: (name: string) => void+ onClose: () => void+}): JSX.Element {+ const { allMetrics, allMetricsLoading } = useValues(metricsLogic)+ const { allTables, databaseLoading } = useValues(databaseTableListLogic)++ const isMetric = kind === 'metric'+ const options = isMetric+ ? allMetrics.map((metric) => ({ key: metric.name, label: metric.name }))+ : allTables.map((table) => ({ key: table.name, label: table.name }))++ return (+ <LemonModal isOpen onClose={onClose} width={480} title={isMetric ? 'Reference a metric' : 'Reference a table'}>+ <LemonModal.Content>+ <LemonInputSelect+ mode="single"+ value={[]}+ onChange={(values) => values[0] && onSelect(values[0])}+ options={options}+ loading={isMetric ? allMetricsLoading : databaseLoading}+ placeholder={isMetric ? 'Search metrics' : 'Search tables'}+ autoFocus+ data-attr="data-catalog-reference-picker"+ />+ </LemonModal.Content>+ </LemonModal>+ )+}diff --git a/products/data_catalog/frontend/components/MetricMarkdownEditor.stories.tsx b/products/data_catalog/frontend/components/MetricMarkdownEditor.stories.tsxnew file mode 100644index 000000000000..f2603d0b3f40--- /dev/null+++ b/products/data_catalog/frontend/components/MetricMarkdownEditor.stories.tsx@@ -0,0 +1,30 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import { MetricMarkdownEditor, MetricMarkdownEditorProps } from './MetricMarkdownEditor'++type Story = StoryObj<MetricMarkdownEditorProps>++const meta: Meta<MetricMarkdownEditorProps> = {+ title: 'Components/Markdown editor/Metric definition',+ component: MetricMarkdownEditor,+ tags: ['autodocs'],+ render: (props) => {+ const [value, setValue] = useState(props.value ?? '')+ return <MetricMarkdownEditor {...props} value={value} onChange={setValue} />+ },+}++export default meta++export const Default: Story = {+ args: {+ value: '1. Sum `amount` for the current month\n\n```sql\nSELECT sum(amount) FROM payments\n```',+ },+}++export const LegacyFallbackForUnsafeMarkdown: Story = {+ args: {+ value: 'This definition embeds an image, which the rich editor would drop: ',+ },+}diff --git a/products/data_catalog/frontend/components/MetricMarkdownEditor.tsx b/products/data_catalog/frontend/components/MetricMarkdownEditor.tsxindex ac932993bb4f..4c1fcf0bab14 100644--- a/products/data_catalog/frontend/components/MetricMarkdownEditor.tsx+++ b/products/data_catalog/frontend/components/MetricMarkdownEditor.tsx@@ -1,18 +1,27 @@+import type { Editor } from '@tiptap/core'import { Placeholder } from '@tiptap/extension-placeholder'+import { PluginKey } from '@tiptap/pm/state'import { Extensions } from '@tiptap/react'-import { useState } from 'react'+import { useActions } from 'kea'+import { useRef, useState } from 'react'+import { createInlineMarkdownSlashCommandsExtension } from 'lib/components/MarkdownEditor/inline/inlineMarkdownSlashCommands'import { RichMarkdownEditor } from 'lib/components/MarkdownEditor/rich/RichMarkdownEditor'import { LemonMarkdown } from 'lib/lemon-ui/LemonMarkdown'import { LemonTextAreaMarkdown } from 'lib/lemon-ui/LemonTextArea/LemonTextAreaMarkdown'+import { databaseTableListLogic } from 'scenes/data-management/database/databaseTableListLogic'import { METRIC_MARKDOWN_MAX_LENGTH } from '../common'+import { CatalogReferencePickerModal } from './CatalogReferencePickerModal'import { METRIC_MARKDOWN_EXTENSIONS, metricMarkdownConverter } from './metricMarkdown'+import {+ CatalogReferenceKind,+ CatalogReferencePickerHost,+ createMetricMarkdownSlashCommands,+ insertCatalogReference,+} from './metricMarkdownSlashCommands'-const METRIC_MARKDOWN_EDITOR_EXTENSIONS: Extensions = [- ...METRIC_MARKDOWN_EXTENSIONS,- Placeholder.configure({ placeholder: 'Describe how to calculate this metric, step by step' }),-]+const METRIC_MARKDOWN_SLASH_COMMANDS_PLUGIN_KEY = new PluginKey('metricMarkdownSlashCommands')export interface MetricMarkdownEditorProps {value: string | undefined@@ -24,6 +33,30 @@ export function MetricMarkdownEditor({ value, onChange }: MetricMarkdownEditorPr// drops, and editing those in ProseMirror would silently rewrite the saved definition,// so they stay on the plain textarea.const [useLegacyEditor] = useState(() => !metricMarkdownConverter.isRoundTripSafe(value))+ const [pickerState, setPickerState] = useState<{ kind: CatalogReferenceKind; editor: Editor } | null>(null)+ const pickerHostRef = useRef<CatalogReferencePickerHost | null>(null)+ const { loadDatabase } = useActions(databaseTableListLogic)++ pickerHostRef.current = {+ open: (kind, editor) => {+ if (kind === 'table') {+ loadDatabase({})+ }+ setPickerState({ kind, editor })+ },+ }++ // Built once per mount: the slash extension captures the host ref, which stays stable.+ const [editorExtensions] = useState<Extensions>(() => [+ ...METRIC_MARKDOWN_EXTENSIONS,+ Placeholder.configure({+ placeholder: 'Describe how to calculate this metric, step by step. Type / for commands',+ }),+ createInlineMarkdownSlashCommandsExtension(+ METRIC_MARKDOWN_SLASH_COMMANDS_PLUGIN_KEY,+ createMetricMarkdownSlashCommands(pickerHostRef)+ ),+ ])if (useLegacyEditor) {return (@@ -39,20 +72,32 @@ export function MetricMarkdownEditor({ value, onChange }: MetricMarkdownEditorPr}return (- <RichMarkdownEditor- value={value}- onChange={onChange}- minRows={8}- maxRows={30}- maxLength={METRIC_MARKDOWN_MAX_LENGTH}- dataAttr="data-catalog-metric-markdown-editor"- extensions={METRIC_MARKDOWN_EDITOR_EXTENSIONS}- markdownToDoc={metricMarkdownConverter.markdownToDoc}- docToMarkdown={metricMarkdownConverter.docToMarkdown}- renderPreview={(markdown) => <LemonMarkdown disableImages>{markdown}</LemonMarkdown>}- controls={{ imageUpload: false }}- tabs={['write', 'preview']}- autoFocus- />+ <>+ <RichMarkdownEditor+ value={value}+ onChange={onChange}+ minRows={8}+ maxRows={30}+ maxLength={METRIC_MARKDOWN_MAX_LENGTH}+ dataAttr="data-catalog-metric-markdown-editor"+ extensions={editorExtensions}+ markdownToDoc={metricMarkdownConverter.markdownToDoc}+ docToMarkdown={metricMarkdownConverter.docToMarkdown}+ renderPreview={(markdown) => <LemonMarkdown disableImages>{markdown}</LemonMarkdown>}+ controls={{ imageUpload: false }}+ tabs={['write', 'preview']}+ autoFocus+ />+ {pickerState && (+ <CatalogReferencePickerModal+ kind={pickerState.kind}+ onSelect={(name) => {+ insertCatalogReference(pickerState.editor, name)+ setPickerState(null)+ }}+ onClose={() => setPickerState(null)}+ />+ )}+ </>)}diff --git a/products/data_catalog/frontend/components/metricMarkdownSlashCommands.test.ts b/products/data_catalog/frontend/components/metricMarkdownSlashCommands.test.tsnew file mode 100644index 000000000000..614b8c06f26f--- /dev/null+++ b/products/data_catalog/frontend/components/metricMarkdownSlashCommands.test.ts@@ -0,0 +1,37 @@+import { Editor } from '@tiptap/core'++import { METRIC_MARKDOWN_EXTENSIONS, metricMarkdownConverter } from './metricMarkdown'+import { createMetricMarkdownSlashCommands, insertCatalogReference } from './metricMarkdownSlashCommands'++function buildEditor(): Editor {+ return new Editor({+ extensions: METRIC_MARKDOWN_EXTENSIONS,+ content: metricMarkdownConverter.markdownToDoc(''),+ })+}++describe('metricMarkdownSlashCommands', () => {+ it('the SQL block command serializes to a sql fence', () => {+ const editor = buildEditor()+ const sqlItem = createMetricMarkdownSlashCommands({ current: null }).find((item) => item.title === 'SQL block')+ expect(sqlItem).not.toBeUndefined()++ sqlItem?.command(editor)+ editor.commands.insertContent('SELECT count() FROM events')++ const markdown = metricMarkdownConverter.docToMarkdown(editor.getJSON())+ expect(markdown).toContain('```sql')+ expect(markdown).toContain('SELECT count() FROM events')+ editor.destroy()+ })++ it('an inserted catalog reference reads as inline code and round-trips', () => {+ const editor = buildEditor()+ insertCatalogReference(editor, 'monthly_active_users')++ const markdown = metricMarkdownConverter.docToMarkdown(editor.getJSON())+ expect(markdown).toContain('`monthly_active_users`')+ expect(metricMarkdownConverter.isRoundTripSafe(markdown)).toBe(true)+ editor.destroy()+ })+})diff --git a/products/data_catalog/frontend/components/metricMarkdownSlashCommands.tsx b/products/data_catalog/frontend/components/metricMarkdownSlashCommands.tsxnew file mode 100644index 000000000000..90e97006ff24--- /dev/null+++ b/products/data_catalog/frontend/components/metricMarkdownSlashCommands.tsx@@ -0,0 +1,64 @@+import type { Editor } from '@tiptap/core'+import type { MutableRefObject } from 'react'++import { IconCode, IconGraph, IconServer } from '@posthog/icons'++import {+ DEFAULT_INLINE_MARKDOWN_SLASH_COMMANDS,+ InlineMarkdownSlashCommandItem,+} from 'lib/components/MarkdownEditor/inline/inlineMarkdownSlashCommands'++export type CatalogReferenceKind = 'metric' | 'table'++export type CatalogReferencePickerHost = {+ open: (kind: CatalogReferenceKind, editor: Editor) => void+}++const CATALOG_SECTION = 'Catalog'++// Image needs an upload host and the metric schema has no image node; Link stays reachable from the toolbar.+const BASE_ITEMS = DEFAULT_INLINE_MARKDOWN_SLASH_COMMANDS.filter((item) => !item.isImagePick && !item.isLinkPopover)++export function insertCatalogReference(editor: Editor, name: string): void {+ editor+ .chain()+ .focus()+ .insertContent([+ { type: 'text', text: name, marks: [{ type: 'code' }] },+ // The trailing space ends the code mark so typing continues as plain text.+ { type: 'text', text: ' ' },+ ])+ .run()+}++export function createMetricMarkdownSlashCommands(+ pickerHostRef: MutableRefObject<CatalogReferencePickerHost | null>+): InlineMarkdownSlashCommandItem[] {+ return [+ ...BASE_ITEMS,+ {+ title: 'SQL block',+ description: 'Fenced SQL code block',+ icon: <IconCode />,+ keywords: ['sql', 'query', 'hogql', 'fence'],+ section: CATALOG_SECTION,+ command: (editor) => editor.chain().focus().setCodeBlock({ language: 'sql' }).run(),+ },+ {+ title: 'Reference metric',+ description: 'Insert the name of a catalog metric',+ icon: <IconGraph />,+ keywords: ['metric', 'reference', 'catalog'],+ section: CATALOG_SECTION,+ command: (editor) => pickerHostRef.current?.open('metric', editor),+ },+ {+ title: 'Reference table',+ description: 'Insert the name of a warehouse table',+ icon: <IconServer />,+ keywords: ['table', 'reference', 'warehouse'],+ section: CATALOG_SECTION,+ command: (editor) => pickerHostRef.current?.open('table', editor),+ },+ ]+}