: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
fix(notebooks): expand flattened markdown tables on paste (#60143)
Arno Hillen37581acd1532
diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 2d661a6a8124..6b64045cbe64 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -5282,6 +5282,10 @@ snapshots:hash: v1.k794b7964.b00940cc29726772696d04db5f58fe0b8ebeb11d2643ba65c3bed080bc55eb5d.jXw3V-2tga1_FAEhQjYsaIkunwsiM1ccaE33_lgp7kgscenes-app-notebooks--empty-notebook--light:hash: v1.k794b7964.9bf82ac6758244b95a879f4a769d00c754f27ac36506b971c07e04b9b4a35c1d.op9Xc1Gjc6lnCkD3h17q2uDTgS7AZHXloLnuvSnQNiM+ scenes-app-notebooks--flattened-table--dark:+ hash: v1.k794b7964.eaa34d86aefb62c52d685a9c3be94a6045094b68e473d5e7294df92f3bb35923.koveEyDQwlGnUrpHFKFRLp4EpWCu5o-tN45MWQsdygo+ scenes-app-notebooks--flattened-table--light:+ hash: v1.k794b7964.fbcae42e4dd9ba20f25b60e2449abba61065a12aa9eedf22638f97f30f097544.2NKqdlPNGVwyblmx6kBWNbBpvT0xX7U4MOMxQcvwKS4scenes-app-notebooks--headings--dark:hash: v1.k794b7964.2f3e9aa392609eb1f32c41877dbcd8a3d3ebb6f8ff83e6560a6b65e1286b5af0.S3DDIrN9dTMMcuWvlJadkTNGDz77GX2fhn3TbByILmIscenes-app-notebooks--headings--light:diff --git a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.tsindex c4c2d9ac4630..6775b205e06a 100644--- a/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts+++ b/frontend/src/lib/components/Cards/TextCard/textCardMarkdown.ts@@ -5,6 +5,8 @@ import { TaskItem, TaskList } from '@tiptap/extension-list'import { MarkdownManager } from '@tiptap/markdown'import StarterKit from '@tiptap/starter-kit'+import { expandFlattenedMarkdownTables } from 'lib/utils/expandFlattenedMarkdownTables'+function escapeHtmlAttribute(value: string): string {return value.replace(/&/g, '&').replace(/"/g, '"')}@@ -125,7 +127,7 @@ export function markdownToTextCardDoc(markdown: string | null | undefined): JSON}try {- const parsed = markdownManager.parse(markdown) as JSONContent+ const parsed = markdownManager.parse(expandFlattenedMarkdownTables(markdown)) as JSONContentif (parsed.type === 'doc') {return parsed}@@ -166,7 +168,8 @@ export function isTextCardMarkdownRoundTripSafe(markdown: string | null | undefi}try {- const originalDoc = markdownManager.parse(markdown) as JSONContent+ const expanded = expandFlattenedMarkdownTables(markdown)+ const originalDoc = markdownManager.parse(expanded) as JSONContentconst roundTripDoc = markdownManager.parse(markdownManager.serialize(originalDoc).trimEnd()) as JSONContentreturn JSON.stringify(originalDoc) === JSON.stringify(roundTripDoc)} catch {diff --git a/frontend/src/lib/utils/expandFlattenedMarkdownTables.test.ts b/frontend/src/lib/utils/expandFlattenedMarkdownTables.test.tsnew file mode 100644index 000000000000..e42d5c89318a--- /dev/null+++ b/frontend/src/lib/utils/expandFlattenedMarkdownTables.test.ts@@ -0,0 +1,42 @@+import { expandFlattenedMarkdownTables } from './expandFlattenedMarkdownTables'++describe('expandFlattenedMarkdownTables', () => {+ it('expands a flattened table into separate rows', () => {+ const input = '| a | b | |---|---| | 1 | 2 |'+ expect(expandFlattenedMarkdownTables(input)).toBe(['| a | b |', '|---|---|', '| 1 | 2 |'].join('\n'))+ })++ it('expands a flattened table embedded between other markdown lines', () => {+ const input = ['# Heading', '| a | b | |---|---| | 1 | 2 |', 'trailing paragraph'].join('\n')+ expect(expandFlattenedMarkdownTables(input)).toBe(+ ['# Heading', '| a | b |', '|---|---|', '| 1 | 2 |', 'trailing paragraph'].join('\n')+ )+ })++ it('handles alignment markers in the delimiter row', () => {+ const input = '| a | b | c | | :--- | :---: | ---: | | 1 | 2 | 3 |'+ expect(expandFlattenedMarkdownTables(input)).toBe(+ ['| a | b | c |', '| :--- | :---: | ---: |', '| 1 | 2 | 3 |'].join('\n')+ )+ })++ it('expands a header + delimiter row table with no data rows', () => {+ const input = '| a | b | |---|---|'+ expect(expandFlattenedMarkdownTables(input)).toBe(['| a | b |', '|---|---|'].join('\n'))+ })++ it('leaves a well-formed multi-line table untouched', () => {+ const input = ['| a | b |', '|---|---|', '| 1 | 2 |'].join('\n')+ expect(expandFlattenedMarkdownTables(input)).toBe(input)+ })++ it.each([+ { input: 'just a plain paragraph of text', desc: 'plain prose' },+ { input: 'see |foo| and |bar| for details', desc: 'inline pipes without a delimiter row' },+ { input: '| a | | b |', desc: 'two glued segments without a delimiter row' },+ { input: '', desc: 'empty string' },+ { input: '# Heading\n\nplain paragraph', desc: 'markdown without any pipes' },+ ])('leaves $desc untouched', ({ input }) => {+ expect(expandFlattenedMarkdownTables(input)).toBe(input)+ })+})diff --git a/frontend/src/lib/utils/expandFlattenedMarkdownTables.ts b/frontend/src/lib/utils/expandFlattenedMarkdownTables.tsnew file mode 100644index 000000000000..f519bbe5359b--- /dev/null+++ b/frontend/src/lib/utils/expandFlattenedMarkdownTables.ts@@ -0,0 +1,17 @@+const TABLE_DELIMITER_SEGMENT_RE = /^\|(?:\s*:?-{2,}:?\s*\|)+\s*$/+const FLATTENED_TABLE_ROW_BOUNDARY_RE = /(?<=\|)\s+(?=\|)/++// Slack, ChatGPT, Notion etc. strip newlines between table rows on plain-text copy.+// Only splits when a delimiter row (`|---|---|`) is present, so prose with `|` is safe.+export function expandFlattenedMarkdownTables(text: string): string {+ return text+ .split('\n')+ .flatMap((line) => {+ const segments = line.split(FLATTENED_TABLE_ROW_BOUNDARY_RE).map((s) => s.trim())+ if (segments.length < 2 || !segments.some((s) => TABLE_DELIMITER_SEGMENT_RE.test(s))) {+ return [line]+ }+ return segments+ })+ .join('\n')+}diff --git a/frontend/src/scenes/max/utils/markdownToTiptap.ts b/frontend/src/scenes/max/utils/markdownToTiptap.tsindex 367ba2b40058..178e9359a0da 100644--- a/frontend/src/scenes/max/utils/markdownToTiptap.ts+++ b/frontend/src/scenes/max/utils/markdownToTiptap.ts@@ -3,6 +3,7 @@ import { MarkdownManager } from '@tiptap/markdown'import StarterKit from '@tiptap/starter-kit'import { JSONContent } from 'lib/components/RichContentEditor/types'+import { expandFlattenedMarkdownTables } from 'lib/utils/expandFlattenedMarkdownTables'const markdownManager = new MarkdownManager({extensions: [StarterKit, Table, TableRow, TableHeader, TableCell],@@ -16,7 +17,7 @@ export function markdownToTiptap(markdown: string): JSONContent[] {return []}- const doc = markdownManager.parse(markdown)+ const doc = markdownManager.parse(expandFlattenedMarkdownTables(markdown))// The parser returns a doc node with content array, we want just the contentreturn (doc.content as JSONContent[]) || []diff --git a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.test.ts b/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.test.tsindex e3d02a4f100f..915c1fc8fd51 100644--- a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.test.ts@@ -217,5 +217,17 @@ describe('DropAndPasteHandlerExtension', () => {expect(result[0].type).toBe('codeBlock')expect(result[0].content?.[0].text).toBe('const x = 1')})++ it('parses a flattened table whose rows were joined on a single line', () => {+ const result = parseMarkdownToTipTap('| a | b | |---|---| | 1 | 2 | | 3 | 4 |')++ expect(result[0].type).toBe('table')+ expect(result[0].content).toHaveLength(3)+ const headerRow = result[0].content?.[0]+ expect(headerRow?.content?.[0].type).toBe('tableHeader')+ expect(headerRow?.content?.[0].content?.[0].content?.[0].text).toBe('a')+ const lastRow = result[0].content?.[2]+ expect(lastRow?.content?.[1].content?.[0].content?.[0].text).toBe('4')+ })})})diff --git a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.tsx b/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.tsxindex 7fd853056c6a..02536d4d53f2 100644--- a/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.tsx+++ b/frontend/src/scenes/notebooks/Notebook/DropAndPasteHandlerExtension.tsx@@ -11,6 +11,8 @@ import posthog from 'posthog-js'import { lemonToast } from '@posthog/lemon-ui'+import { expandFlattenedMarkdownTables } from 'lib/utils/expandFlattenedMarkdownTables'+import { NotebookNodeType } from '../types'export type TabularFormat = 'tsv' | 'csv'@@ -100,7 +102,7 @@ export function parseMarkdownToTipTap(markdown: string): JSONContent[] {if (!markdown || markdown.trim() === '') {return []}- const doc = markdownManager.parse(markdown) as JSONContent+ const doc = markdownManager.parse(expandFlattenedMarkdownTables(markdown)) as JSONContentreturn (doc.content as JSONContent[]) || []}diff --git a/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsx b/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsxindex 9089e2b0a958..7120af71e36f 100644--- a/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsx+++ b/frontend/src/scenes/notebooks/Notebook/Notebook.stories.tsx@@ -253,6 +253,28 @@ const testCases: Record<string, NotebookType> = {},]),'api/projects/:team_id/notebooks/empty': notebookTestTemplate('empty', []),+ 'api/projects/:team_id/notebooks/flattened-table': notebookTestTemplate('flattened-table', [+ {+ type: 'heading',+ attrs: { level: 1 },+ content: [{ type: 'text', text: 'Flattened table recovery' }],+ },+ {+ type: 'paragraph',+ content: [+ { type: 'text', text: 'Stored as a literal paragraph; migration should render it as a real table:' },+ ],+ },+ {+ type: 'paragraph',+ content: [+ {+ type: 'text',+ text: '| Content type | Tab opens | Unique users | |---|---|---| | Session replay | 287K (32%) | 58K | | New/blank tab | 248K (27%) | 53K | | Dashboard | 53K (6%) | 14K |',+ },+ ],+ },+ ]),}const meta: Meta = {@@ -420,6 +442,7 @@ export const NumberedList: Story = { parameters: { pageUrl: urls.notebook('numbeexport const BulletList: Story = { parameters: { pageUrl: urls.notebook('bullet-list') } }export const TextOnlyNotebook: Story = { parameters: { pageUrl: urls.notebook('12345') } }export const EmptyNotebook: Story = { parameters: { pageUrl: urls.notebook('empty') } }+export const FlattenedTable: Story = { parameters: { pageUrl: urls.notebook('flattened-table') } }export const NotebookNotFound: Story = { parameters: { pageUrl: urls.notebook('abcde') } }export const RecordingsPlaylist: Story = {diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/expandFlattenedTablesInContent.test.ts b/frontend/src/scenes/notebooks/Notebook/migrations/expandFlattenedTablesInContent.test.tsnew file mode 100644index 000000000000..20f598b0d5f0--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/migrations/expandFlattenedTablesInContent.test.ts@@ -0,0 +1,64 @@+import { JSONContent } from '@tiptap/core'++import { expandFlattenedTablesInContent } from './expandFlattenedTablesInContent'++function paragraph(text: string): JSONContent {+ return { type: 'paragraph', content: [{ type: 'text', text }] }+}++describe('expandFlattenedTablesInContent', () => {+ it('rewrites a paragraph that contains a flattened table into a real table node', () => {+ const result = expandFlattenedTablesInContent([paragraph('| a | b | |---|---| | 1 | 2 |')])++ expect(result).toHaveLength(1)+ expect(result[0].type).toBe('table')+ expect(result[0].content).toHaveLength(2)+ expect(result[0].content?.[0].content?.[0].type).toBe('tableHeader')+ expect(result[0].content?.[1].content?.[1].content?.[0].content?.[0].text).toBe('2')+ })++ it('preserves surrounding nodes and only rewrites the flattened paragraph', () => {+ const heading: JSONContent = {+ type: 'heading',+ attrs: { level: 2 },+ content: [{ type: 'text', text: 'Title' }],+ }+ const trailing = paragraph('trailing paragraph')++ const result = expandFlattenedTablesInContent([heading, paragraph('| a | b | |---|---| | 1 | 2 |'), trailing])++ expect(result).toHaveLength(3)+ expect(result[0]).toBe(heading)+ expect(result[1].type).toBe('table')+ expect(result[2]).toBe(trailing)+ })++ it.each([+ { node: paragraph('plain prose with no table'), desc: 'plain prose' },+ { node: paragraph('see |foo| and |bar|'), desc: 'inline pipes without a delimiter row' },+ {+ node: { type: 'heading', attrs: { level: 1 }, content: [{ type: 'text', text: '# heading' }] },+ desc: 'non-paragraph node',+ },+ {+ node: {+ type: 'paragraph',+ content: [{ type: 'text', text: '| a | b | |---|---| | 1 | 2 |', marks: [{ type: 'bold' }] }],+ },+ desc: 'flattened table inside a marked text run',+ },+ {+ node: {+ type: 'paragraph',+ content: [+ { type: 'text', text: '| a | b |' },+ { type: 'hardBreak' },+ { type: 'text', text: '|---|---|' },+ ],+ },+ desc: 'paragraph with mixed non-text children',+ },+ ])('leaves $desc untouched', ({ node }) => {+ expect(expandFlattenedTablesInContent([node])).toEqual([node])+ })+})diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/expandFlattenedTablesInContent.ts b/frontend/src/scenes/notebooks/Notebook/migrations/expandFlattenedTablesInContent.tsnew file mode 100644index 000000000000..31a8c91fe0f7--- /dev/null+++ b/frontend/src/scenes/notebooks/Notebook/migrations/expandFlattenedTablesInContent.ts@@ -0,0 +1,46 @@+import { JSONContent } from '@tiptap/core'+import { Table, TableCell, TableHeader, TableRow } from '@tiptap/extension-table'+import { MarkdownManager } from '@tiptap/markdown'+import StarterKit from '@tiptap/starter-kit'++import { expandFlattenedMarkdownTables } from 'lib/utils/expandFlattenedMarkdownTables'++const markdownManager = new MarkdownManager({+ extensions: [StarterKit, Table, TableRow, TableHeader, TableCell],+})++function paragraphPlainText(node: JSONContent): string | null {+ if (node.type !== 'paragraph' || !Array.isArray(node.content)) {+ return null+ }+ let out = ''+ for (const child of node.content) {+ if (child.type !== 'text' || typeof child.text !== 'string') {+ return null+ }+ if (child.marks && child.marks.length > 0) {+ return null+ }+ out += child.text+ }+ return out+}++export function expandFlattenedTablesInContent(content: JSONContent[]): JSONContent[] {+ return content.flatMap((node) => {+ const text = paragraphPlainText(node)+ if (text === null) {+ return [node]+ }+ const expanded = expandFlattenedMarkdownTables(text)+ if (expanded === text) {+ return [node]+ }+ const parsed = markdownManager.parse(expanded) as JSONContent+ const parsedContent = (parsed.content as JSONContent[] | undefined) ?? []+ if (parsedContent.length === 0) {+ return [node]+ }+ return parsedContent+ })+}diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.tsindex 29cf0fae6db4..9b1e184600ba 100644--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts@@ -60,6 +60,43 @@ describe('migrate()', () => {const contentToExpected: [string, JSONContent[], JSONContent[]][] = [['migrates node without changes', [{ type: 'paragraph' }], [{ type: 'paragraph' }]],+ [+ 'recovers a flattened markdown table from a literal paragraph',+ [{ type: 'paragraph', content: [{ type: 'text', text: '| a | b | |---|---| | 1 | 2 |' }] }],+ [+ {+ type: 'table',+ content: [+ {+ type: 'tableRow',+ content: [+ {+ type: 'tableHeader',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'a' }] }],+ },+ {+ type: 'tableHeader',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: 'b' }] }],+ },+ ],+ },+ {+ type: 'tableRow',+ content: [+ {+ type: 'tableCell',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '1' }] }],+ },+ {+ type: 'tableCell',+ content: [{ type: 'paragraph', content: [{ type: 'text', text: '2' }] }],+ },+ ],+ },+ ],+ },+ ],+ ],['migrates query node with string content to object content',[diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.tsindex 3985b3959fd3..d02f33270900 100644--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.ts@@ -39,11 +39,13 @@ import {import { checkLatestVersionsOnQuery } from '~/queries/utils'import { FunnelExclusionLegacy, LegacyRecordingFilters } from '~/types'+import { expandFlattenedTablesInContent } from './expandFlattenedTablesInContent'+// NOTE: Increment this number when you add a new content migration// It will bust the cache on the localContent in the notebookLogic// so that the latest content will fall back to the remote content which// is filtered through the migrate function below that ensures integrity-export const NOTEBOOKS_VERSION = '1'+export const NOTEBOOKS_VERSION = '2'export interface MigrateOptions {/**@@ -64,6 +66,7 @@ export async function migrate(notebook: NotebookType, options: MigrateOptions =content = convertInsightQueryStringsToObjects(content)content = convertInsightQueriesToNewSchema(content)content = convertPlaylistFiltersToUniversalFilters(content)+ content = expandFlattenedTablesInContent(content)if (!options.skipApiUpgrade) {content = await upgradeQueryNode(content)}