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.

fix(notebooks): render multiline component props (#94310)

Marius Andrac0359cca9268
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index e93e6d1571bf..193b6daf907a 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -748,19 +748,84 @@ continued line
expect(serializeMarkdownNotebook(document)).toEqual(markdown)
})
- it('round-trips multiline string component props', () => {
- const markdown = `<SummaryCard id="${TEST_AI_CONVERSATION_ID}" summary=${JSON.stringify('## Summary\nDone')} />`
+ it.each([
+ [
+ 'escaped line breaks',
+ `<SummaryCard id="${TEST_AI_CONVERSATION_ID}" summary=${JSON.stringify('## Summary\nDone')} />`,
+ 'SummaryCard',
+ { id: TEST_AI_CONVERSATION_ID, summary: '## Summary\nDone' },
+ ],
+ [
+ 'literal line breaks',
+ `<PythonV2 title="Event galaxy" code="import pandas as pd
+
+points = pd.DataFrame()" />`,
+ 'PythonV2',
+ { title: 'Event galaxy', code: 'import pandas as pd\n\npoints = pd.DataFrame()' },
+ ],
+ ])('round-trips component string props with %s', (_name, markdown, tagName, props) => {
+ const document = parseMarkdownNotebook(markdown)
+
+ expect(document.nodes[0]).toMatchObject({
+ type: 'component',
+ tagName,
+ props,
+ })
+ expect(serializeMarkdownNotebook(document)).toEqual(markdown)
+ })
+
+ it.each([
+ ['an escaped tag', '\\<'],
+ ['an unescaped tag with escaped prop source', '<'],
+ ])('recovers a multiline component produced by the prose serializer with %s', (_name, tagStart) => {
+ const markdown = `${tagStart}PythonV2 title="Chart" code="import pandas as pd
+
+\\# Prepare values
+labels = \\[f\\\\"<b>{row}</b>\\\\" for row in rows\\]
+values = rows\\[0\\] \\* 2" />`
+ const recoveredMarkdown = `<PythonV2 title="Chart" code="import pandas as pd
+
+# Prepare values
+labels = [f\\"<b>{row}</b>\\" for row in rows]
+values = rows[0] * 2" />`
const document = parseMarkdownNotebook(markdown)
expect(document.nodes[0]).toMatchObject({
type: 'component',
- tagName: 'SummaryCard',
+ tagName: 'PythonV2',
props: {
- id: TEST_AI_CONVERSATION_ID,
- summary: '## Summary\nDone',
+ title: 'Chart',
+ code: 'import pandas as pd\n\n# Prepare values\nlabels = [f"<b>{row}</b>" for row in rows]\nvalues = rows[0] * 2',
},
})
- expect(serializeMarkdownNotebook(document)).toEqual(markdown)
+ expect(serializeMarkdownNotebook(document)).toEqual(recoveredMarkdown)
+ })
+
+ it.each([
+ [
+ 'an unquoted prop',
+ `<PythonV2 nodeId=p
+
+code=print(1) />`,
+ ],
+ [
+ 'an unterminated quoted prop',
+ `<PythonV2 nodeId="p
+
+Following paragraph`,
+ ],
+ ])('does not cross a blank-line boundary for a malformed component with %s', (_name, markdown) => {
+ const document = parseMarkdownNotebook(markdown)
+
+ expect(document.nodes).not.toContainEqual(expect.objectContaining({ type: 'component' }))
+ expect(serializeMarkdownNotebook(document)).toEqual(`\\${markdown}`)
+ })
+
+ it('does not scan past the multiline component limit', () => {
+ const markdown = [`<PythonV2 nodeId="p" code="`, ...Array.from({ length: 1_001 }, () => 'x'), `" />`].join('\n')
+ const document = parseMarkdownNotebook(markdown)
+
+ expect(document.nodes).not.toContainEqual(expect.objectContaining({ type: 'component' }))
})
it('serializes bold links in a stable mark order', () => {
diff --git a/frontend/src/lib/components/MarkdownNotebook/markdown.ts b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
index 2705456cf785..69d858ca5d1a 100644
--- a/frontend/src/lib/components/MarkdownNotebook/markdown.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/markdown.ts
@@ -36,7 +36,24 @@ type PropParseResult = {
errors: string[]
}
+type ComponentScanResult = {
+ raw: string
+ nextLineIndex: number
+ foundTerminator: boolean
+}
+
+type ComponentScanState = {
+ quote: string | null
+ expressionDepth: number
+ escapeNext: boolean
+ awaitingPropValue: boolean
+ openingTagClosed: boolean
+}
+
const COMPONENT_START_REGEX = /^<[A-Z][A-Za-z0-9]*(\s|>|\/)/
+const ESCAPED_COMPONENT_START_REGEX = /^\\<[A-Z][A-Za-z0-9]*(\s|>|\/)/
+const MAX_COMPONENT_BLOCK_LINES = 1_000
+const MAX_COMPONENT_BLOCK_CHARACTERS = 256 * 1024
const ORDERED_LIST_REGEX = /^\s*\d+[.)](?:\s+|$)/
const BULLET_LIST_REGEX = /^\s*[-*+•](?:\s+|$)/
const LIST_ITEM_REGEX = /^(\s*)(\d+[.)]|[-*+•])(?:\s+(.*))?$/
@@ -268,6 +285,10 @@ function serializeNodeUncached(node: NotebookBlockNode): string {
return serializeImageNode(node)
}
if (node.type === 'component') {
+ const multilineSource = getUnchangedMultilineComponentSource(node)
+ if (multilineSource) {
+ return multilineSource
+ }
return `<${node.tagName}${serializeComponentProps(node.props)} />`
}
return ''
@@ -601,7 +622,19 @@ function parseBlock(lines: string[], lineIndex: number): BlockParseResult {
}
if (COMPONENT_START_REGEX.test(trimmed)) {
- return parseComponentBlock(lines, lineIndex)
+ const parsedComponent = parseComponentBlock(lines, lineIndex)
+ const parsedNode = parsedComponent.node
+ if (parsedNode?.type === 'component' && !parsedNode.errors?.length) {
+ return parsedComponent
+ }
+ return parseRecoveredMultilineComponentBlock(lines, lineIndex) ?? parsedComponent
+ }
+
+ if (ESCAPED_COMPONENT_START_REGEX.test(trimmed)) {
+ const recoveredComponent = parseRecoveredMultilineComponentBlock(lines, lineIndex)
+ if (recoveredComponent) {
+ return recoveredComponent
+ }
}
const headingMatch = line.match(HEADING_REGEX)
@@ -673,6 +706,16 @@ function parseBlock(lines: string[], lineIndex: number): BlockParseResult {
return parseParagraphBlock(lines, lineIndex)
}
+function parseRecoveredMultilineComponentBlock(lines: string[], lineIndex: number): BlockParseResult | null {
+ const recoveredComponent = parseComponentBlock(lines, lineIndex, true)
+ const recoveredNode = recoveredComponent.node
+ return recoveredNode?.type === 'component' &&
+ recoveredComponent.nextLineIndex > lineIndex + 1 &&
+ !recoveredNode.errors?.length
+ ? recoveredComponent
+ : null
+}
+
function parseParagraphBlock(lines: string[], lineIndex: number): BlockParseResult {
const paragraphLines: string[] = []
let nextLineIndex = lineIndex
@@ -1084,44 +1127,240 @@ function parseImageBlock(lines: string[], lineIndex: number): BlockParseResult {
}
}
-function parseComponentBlock(lines: string[], lineIndex: number): BlockParseResult {
- const rawLines: string[] = []
- const firstLine = lines[lineIndex].trim()
+function parseComponentBlock(
+ lines: string[],
+ lineIndex: number,
+ recoverEscapedSource: boolean = false
+): BlockParseResult {
+ const firstLine = getComponentSourceLine(lines[lineIndex], recoverEscapedSource).trim()
const tagName = firstLine.match(/^<([A-Z][A-Za-z0-9]*)/)?.[1]
- let nextLineIndex = lineIndex
- let foundTerminator = false
-
- // Components are block-level: a blank line ends the scan so an unterminated tag can
- // never swallow the rest of the document
- while (nextLineIndex < lines.length && (nextLineIndex === lineIndex || lines[nextLineIndex].trim())) {
- rawLines.push(lines[nextLineIndex])
- const raw = rawLines.join('\n').trim()
- if (raw.endsWith('/>') || (tagName && raw.includes(`</${tagName}>`))) {
- foundTerminator = true
- break
- }
- nextLineIndex += 1
- }
- const raw = rawLines.join('\n').trim()
- if (!foundTerminator) {
+ if (!tagName) {
+ const raw = firstLine
return {
node: makeComponentFallbackParagraph(raw),
- nextLineIndex,
+ nextLineIndex: lineIndex + 1,
error: { message: 'Unclosed component tag', raw, line: lineIndex + 1 },
}
}
- const parsed = parseComponentTag(raw)
+ const scan = scanComponentBlock(lines, lineIndex, tagName, recoverEscapedSource)
+ if (!scan.foundTerminator) {
+ const singleLineComponent = parseComponentTag(firstLine)
+ if (singleLineComponent.node) {
+ return {
+ node: singleLineComponent.node,
+ nextLineIndex: lineIndex + 1,
+ }
+ }
+
+ return {
+ node: makeComponentFallbackParagraph(scan.raw),
+ nextLineIndex: scan.nextLineIndex,
+ error: { message: 'Unclosed component tag', raw: scan.raw, line: lineIndex + 1 },
+ }
+ }
+
+ const parsed = parseComponentTag(scan.raw)
return {
// A malformed tag degrades to a paragraph holding the raw source — source text must
// never be dropped from the node tree, or the next save destroys it
- node: parsed.node ?? makeComponentFallbackParagraph(raw),
- nextLineIndex: nextLineIndex + 1,
+ node: parsed.node ?? makeComponentFallbackParagraph(scan.raw),
+ nextLineIndex: scan.nextLineIndex,
error: parsed.error ? { ...parsed.error, line: lineIndex + 1 } : undefined,
}
}
+function scanComponentBlock(
+ lines: string[],
+ lineIndex: number,
+ tagName: string,
+ recoverEscapedSource: boolean
+): ComponentScanResult {
+ const rawLines: string[] = []
+ const state: ComponentScanState = {
+ quote: null,
+ expressionDepth: 0,
+ escapeNext: false,
+ awaitingPropValue: false,
+ openingTagClosed: false,
+ }
+ let characterCount = 0
+ let nextLineIndex = lineIndex
+ let fallbackRawLineCount: number | null = null
+ let fallbackNextLineIndex: number | null = null
+ const lineLimit = Math.min(lines.length, lineIndex + MAX_COMPONENT_BLOCK_LINES)
+
+ while (nextLineIndex < lineLimit) {
+ const line = getComponentSourceLine(lines[nextLineIndex], recoverEscapedSource)
+ if (nextLineIndex > lineIndex && !line.trim() && fallbackNextLineIndex === null) {
+ fallbackRawLineCount = rawLines.length
+ fallbackNextLineIndex = nextLineIndex
+ }
+ if (isComponentBlankLineBoundary(line, nextLineIndex, lineIndex, state)) {
+ break
+ }
+
+ const separatorLength = rawLines.length ? 1 : 0
+ if (isComponentCharacterLimitReached(rawLines, characterCount, separatorLength, line)) {
+ break
+ }
+ characterCount += separatorLength + line.length
+ rawLines.push(line)
+
+ let characterIndex = 0
+ while (characterIndex < line.length) {
+ const character = line[characterIndex]
+
+ if (state.openingTagClosed) {
+ if (isComponentClosingTag(line, characterIndex, tagName)) {
+ return {
+ raw: rawLines.join('\n').trim(),
+ nextLineIndex: nextLineIndex + 1,
+ foundTerminator: true,
+ }
+ }
+ characterIndex += 1
+ continue
+ }
+
+ if (isComponentSelfClosingTag(line, characterIndex, state)) {
+ return {
+ raw: rawLines.join('\n').trim(),
+ nextLineIndex: nextLineIndex + 1,
+ foundTerminator: true,
+ }
+ }
+ advanceComponentScan(state, character)
+ characterIndex += 1
+ }
+
+ // Joined source contains a newline here. It consumes a pending escape without closing
+ // the quoted value, matching the prop parser's treatment of backslash-newline.
+ consumeComponentScanLineBreak(state)
+ nextLineIndex += 1
+ }
+
+ const fallbackRawLines = fallbackRawLineCount === null ? rawLines : rawLines.slice(0, fallbackRawLineCount)
+ return {
+ raw: fallbackRawLines.join('\n').trim(),
+ nextLineIndex: fallbackNextLineIndex ?? nextLineIndex,
+ foundTerminator: false,
+ }
+}
+
+function getComponentSourceLine(line: string, recoverEscapedSource: boolean): string {
+ if (!recoverEscapedSource) {
+ return line
+ }
+
+ let source = ''
+ let index = 0
+ while (index < line.length) {
+ const character = line[index]
+ const nextCharacter = line[index + 1]
+ if (character === '\\' && nextCharacter !== undefined && INLINE_ESCAPABLE_CHARS.has(nextCharacter)) {
+ source += nextCharacter
+ index += 2
+ } else {
+ source += character
+ index += 1
+ }
+ }
+ return source
+}
+
+function isComponentBlankLineBoundary(
+ line: string,
+ nextLineIndex: number,
+ lineIndex: number,
+ state: ComponentScanState
+): boolean {
+ return nextLineIndex > lineIndex && !line.trim() && state.quote === null && state.expressionDepth === 0
+}
+
+function isComponentCharacterLimitReached(
+ rawLines: string[],
+ characterCount: number,
+ separatorLength: number,
+ line: string
+): boolean {
+ return rawLines.length > 0 && characterCount + separatorLength + line.length > MAX_COMPONENT_BLOCK_CHARACTERS
+}
+
+function isComponentClosingTag(line: string, characterIndex: number, tagName: string): boolean {
+ const closingTag = `</${tagName}>`
+ return line.startsWith(closingTag, characterIndex) && !line.slice(characterIndex + closingTag.length).trim()
+}
+
+function isComponentSelfClosingTag(line: string, characterIndex: number, state: ComponentScanState): boolean {
+ return (
+ state.quote === null &&
+ state.expressionDepth === 0 &&
+ line.startsWith('/>', characterIndex) &&
+ !line.slice(characterIndex + 2).trim()
+ )
+}
+
+function advanceComponentScan(state: ComponentScanState, character: string): void {
+ if (state.quote !== null) {
+ advanceComponentQuote(state, character)
+ return
+ }
+
+ if (state.expressionDepth > 0) {
+ advanceComponentExpression(state, character)
+ return
+ }
+
+ if (state.awaitingPropValue) {
+ if (/\s/.test(character)) {
+ return
+ }
+ state.awaitingPropValue = false
+ if (character === '"' || character === "'") {
+ state.quote = character
+ return
+ }
+ if (character === '{') {
+ state.expressionDepth = 1
+ return
+ }
+ }
+
+ if (character === '=') {
+ state.awaitingPropValue = true
+ } else if (character === '>') {
+ state.openingTagClosed = true
+ }
+}
+
+function advanceComponentQuote(state: ComponentScanState, character: string): void {
+ if (state.escapeNext) {
+ state.escapeNext = false
+ } else if (character === '\\') {
+ state.escapeNext = true
+ } else if (character === state.quote) {
+ state.quote = null
+ }
+}
+
+function advanceComponentExpression(state: ComponentScanState, character: string): void {
+ if (character === '"' || character === "'") {
+ state.quote = character
+ } else if (character === '{') {
+ state.expressionDepth += 1
+ } else if (character === '}') {
+ state.expressionDepth -= 1
+ }
+}
+
+function consumeComponentScanLineBreak(state: ComponentScanState): void {
+ if (state.quote !== null && state.escapeNext) {
+ state.escapeNext = false
+ }
+}
+
function makeComponentFallbackParagraph(raw: string): NotebookTextBlockNode {
const children: NotebookInlineNode[] = []
raw.split('\n').forEach((line, index) => {
@@ -1344,6 +1583,19 @@ function serializeComponentProps(props: NotebookComponentProps): string {
return serialized
}
+function getUnchangedMultilineComponentSource(node: NotebookComponentBlockNode): string | null {
+ if (!node.raw?.includes('\n')) {
+ return null
+ }
+
+ const parsed = parseComponentTag(node.raw)
+ if (!parsed.node || parsed.node.errors?.length) {
+ return null
+ }
+
+ return getNodeFingerprint(parsed.node) === getNodeFingerprint(node) ? node.raw : null
+}
+
function getSerializableComponentProps(props: NotebookComponentProps): NotebookComponentProps {
const nextProps = Object.entries(props).reduce<NotebookComponentProps>((accumulator, [key, value]) => {
if (
diff --git a/playwright/e2e/data-quality-overview.spec.ts b/playwright/e2e/data-quality-overview.spec.ts
index 36679277c0db..245c1505d08b 100644
--- a/playwright/e2e/data-quality-overview.spec.ts
+++ b/playwright/e2e/data-quality-overview.spec.ts
@@ -52,9 +52,16 @@ test('edits and deletes a check from Data Ops', async ({ page, playwrightSetup }
await expect(page.getByText(CHECK_NAME)).toBeVisible()
await page.getByLabel(`Actions for check ${CHECK_NAME}`).click()
+ const metadataResponse = page.waitForResponse(
+ (response) =>
+ response.url().includes('/query/HogQLMetadata/') && response.request().method() === 'POST' && response.ok()
+ )
await page.getByRole('menuitem', { name: 'Edit' }).click()
+ await metadataResponse
await page.getByLabel('Description').fill('Every order keeps a positive id')
- await page.getByTestId('data-quality-check-save').click()
+ const saveButton = page.getByTestId('data-quality-check-save')
+ await expect(saveButton).toBeEnabled()
+ await saveButton.click()
await expect(page.getByText('Check saved')).toBeVisible()
const edited = await page.request.get(
diff --git a/products/notebooks/backend/test/test_sql_v2_state.py b/products/notebooks/backend/test/test_sql_v2_state.py
index 36a2ba1995cb..55f11049cf8b 100644
--- a/products/notebooks/backend/test/test_sql_v2_state.py
+++ b/products/notebooks/backend/test/test_sql_v2_state.py
@@ -35,6 +35,8 @@ class TestCellExtractionAndEdges(SimpleTestCase):
"# Doc\n\n"
'<SQLV2 nodeId="s1" code="select 1" returnVariable="df" />\n\n'
'<PythonV2 nodeId="p1" code="out = df.head()" returnVariable="out" />\n\n'
+ '<PythonV2 nodeId="p2" code="import pandas as pd\n\nout = pd.DataFrame()" returnVariable="multiline" />\n\n'
+ '\\<PythonV2 nodeId="p3" code="\\# Build the frame\n\nout = df.head()" returnVariable="recovered" />\n\n'
'<Query nodeId="q1" query={{"kind":"SavedInsightNode","shortId":"abc"}} />\n\n'
'<SQLV2 code="select 2" returnVariable="anon" />\n\n'
'<RevenueCard metric="arr" />\n'
@@ -43,8 +45,40 @@ class TestCellExtractionAndEdges(SimpleTestCase):
assert [(c.node_id, c.cell_type, c.dataframe_name) for c in cells] == [
("s1", "sql", "df"),
("p1", "python", "out"),
+ ("p2", "python", "multiline"),
+ ("p3", "python", "recovered"),
("q1", "saved_insight", ""),
]
+ assert cells[2].code == "import pandas as pd\n\nout = pd.DataFrame()"
+ assert cells[3].code == "# Build the frame\n\nout = df.head()"
+
+ @parameterized.expand(
+ [
+ ("unquoted_prop", "<PythonV2 nodeId=p\n\ncode=print(1) />", []),
+ (
+ "unterminated_quoted_prop",
+ '<PythonV2 nodeId="p\n\nFollowing paragraph',
+ [],
+ ),
+ ]
+ )
+ def test_malformed_component_does_not_cross_a_blank_line(
+ self, _name: str, markdown: str, expected_node_ids: list[str]
+ ) -> None:
+ content = markdown_content(markdown)
+
+ assert [cell.node_id for cell in extract_cells(content)] == expected_node_ids
+
+ def test_malformed_single_line_component_keeps_parsed_props(self) -> None:
+ content = markdown_content('<PythonV2 nodeId="p" code="print(1)" returnVariable="out" broken="unterminated />')
+
+ cells = extract_cells(content)
+ assert [(cell.node_id, cell.code, cell.dataframe_name) for cell in cells] == [("p", "print(1)", "out")]
+
+ def test_component_scan_is_bounded(self) -> None:
+ markdown = "\n".join(['<PythonV2 nodeId="p" code="', *(["x"] * 1_001), '" />'])
+
+ assert extract_cells(markdown_content(markdown)) == []
def test_rich_text_content_yields_no_cells(self) -> None:
assert extract_cells({"type": "doc", "content": [{"type": "paragraph"}]}) == []
diff --git a/products/notebooks/backend/util.py b/products/notebooks/backend/util.py
index c2d7342c04fe..fbc768399c38 100644
--- a/products/notebooks/backend/util.py
+++ b/products/notebooks/backend/util.py
@@ -5,6 +5,8 @@ import uuid
from collections.abc import Iterator
from typing import Any
+from posthog.dataclasses import frozen
+
# Type aliases for TipTap editor nodes
TipTapNode = dict[str, Any]
TipTapContent = list[TipTapNode]
@@ -67,6 +69,26 @@ _MARKDOWN_COMPONENT_TAG_REGEX = re.compile(r"^<([A-Z][A-Za-z0-9]*)([\s\S]*?)(?:/
_MARKDOWN_COMPONENT_PROP_NAME_REGEX = re.compile(r"^([A-Za-z_][A-Za-z0-9_-]*)")
_MARKDOWN_COMPONENT_RAW_PROP_VALUE_REGEX = re.compile(r"^([^\s/>]+)")
_MARKDOWN_COMPONENT_NUMBER_REGEX = re.compile(r"^-?\d+(\.\d+)?$")
+_MARKDOWN_ESCAPED_COMPONENT_START_REGEX = re.compile(r"^\\<[A-Z][A-Za-z0-9]*(\s|>|/)")
+_MARKDOWN_INLINE_ESCAPABLE_CHARACTERS = frozenset("\\`*_~[]()<>#+-.|!")
+_MAX_MARKDOWN_COMPONENT_LINES = 1_000
+_MAX_MARKDOWN_COMPONENT_CHARACTERS = 256 * 1024
+
+
+@frozen
+class _MarkdownComponentScan:
+ raw: str
+ next_line_index: int
+ found_terminator: bool
+
+
+@frozen(frozen=False)
+class _MarkdownComponentScanState:
+ quote: str | None = None
+ expression_depth: int = 0
+ escape_next: bool = False
+ awaiting_prop_value: bool = False
+ opening_tag_closed: bool = False
def filter_notebook_content_for_sharing(content: Any) -> Any:
@@ -368,6 +390,9 @@ def _get_markdown_code_block_end(lines: list[str], line_index: int) -> int:
def _read_markdown_component_block(lines: list[str], line_index: int) -> tuple[str, str, int] | None:
first_line = lines[line_index].strip()
+ recover_escaped_source = bool(_MARKDOWN_ESCAPED_COMPONENT_START_REGEX.match(first_line))
+ if recover_escaped_source:
+ first_line = _unescape_markdown_inline_source(first_line)
if not _MARKDOWN_COMPONENT_START_REGEX.match(first_line):
return None
@@ -376,21 +401,149 @@ def _read_markdown_component_block(lines: list[str], line_index: int) -> tuple[s
if not tag_name:
return None
+ scan = _scan_markdown_component_block(lines, line_index, tag_name, recover_escaped_source)
+ if recover_escaped_source and scan.next_line_index <= line_index + 1:
+ return None
+ if not scan.found_terminator:
+ if _MARKDOWN_COMPONENT_TAG_REGEX.match(first_line):
+ return tag_name, first_line, line_index + 1
+ return None
+
+ return tag_name, scan.raw, scan.next_line_index
+
+
+def _scan_markdown_component_block(
+ lines: list[str], line_index: int, tag_name: str, recover_escaped_source: bool = False
+) -> _MarkdownComponentScan:
raw_lines: list[str] = []
+ state = _MarkdownComponentScanState()
+ character_count = 0
next_line_index = line_index
- found_terminator = False
- while next_line_index < len(lines) and (next_line_index == line_index or lines[next_line_index].strip()):
- raw_lines.append(lines[next_line_index])
- raw = "\n".join(raw_lines).strip()
- if raw.endswith("/>") or f"</{tag_name}>" in raw:
- found_terminator = True
+ fallback_raw_line_count: int | None = None
+ fallback_next_line_index: int | None = None
+ line_limit = min(len(lines), line_index + _MAX_MARKDOWN_COMPONENT_LINES)
+
+ while next_line_index < line_limit:
+ line = (
+ _unescape_markdown_inline_source(lines[next_line_index])
+ if recover_escaped_source
+ else lines[next_line_index]
+ )
+ if next_line_index > line_index and not line.strip() and fallback_next_line_index is None:
+ fallback_raw_line_count = len(raw_lines)
+ fallback_next_line_index = next_line_index
+ if next_line_index > line_index and not line.strip() and state.quote is None and state.expression_depth == 0:
+ break
+
+ separator_length = 1 if raw_lines else 0
+ if raw_lines and character_count + separator_length + len(line) > _MAX_MARKDOWN_COMPONENT_CHARACTERS:
break
+ character_count += separator_length + len(line)
+ raw_lines.append(line)
+
+ character_index = 0
+ while character_index < len(line):
+ character = line[character_index]
+
+ if state.opening_tag_closed:
+ closing_tag = f"</{tag_name}>"
+ if (
+ line.startswith(closing_tag, character_index)
+ and not line[character_index + len(closing_tag) :].strip()
+ ):
+ return _MarkdownComponentScan(
+ raw="\n".join(raw_lines).strip(),
+ next_line_index=next_line_index + 1,
+ found_terminator=True,
+ )
+ character_index += 1
+ continue
+
+ if (
+ state.quote is None
+ and state.expression_depth == 0
+ and line.startswith("/>", character_index)
+ and not line[character_index + 2 :].strip()
+ ):
+ return _MarkdownComponentScan(
+ raw="\n".join(raw_lines).strip(),
+ next_line_index=next_line_index + 1,
+ found_terminator=True,
+ )
+ _advance_markdown_component_scan(state, character)
+ character_index += 1
+
+ # Joined source contains a newline here. It consumes a pending escape without closing
+ # the quoted value, matching the prop parser's treatment of backslash-newline.
+ if state.quote is not None and state.escape_next:
+ state.escape_next = False
next_line_index += 1
- if not found_terminator:
- return None
+ fallback_raw_lines = raw_lines if fallback_raw_line_count is None else raw_lines[:fallback_raw_line_count]
+ return _MarkdownComponentScan(
+ raw="\n".join(fallback_raw_lines).strip(),
+ next_line_index=fallback_next_line_index if fallback_next_line_index is not None else next_line_index,
+ found_terminator=False,
+ )
+
+
+def _unescape_markdown_inline_source(source: str) -> str:
+ unescaped: list[str] = []
+ index = 0
+ while index < len(source):
+ character = source[index]
+ next_character = source[index + 1] if index + 1 < len(source) else None
+ if character == "\\" and next_character in _MARKDOWN_INLINE_ESCAPABLE_CHARACTERS:
+ unescaped.append(next_character)
+ index += 2
+ else:
+ unescaped.append(character)
+ index += 1
+ return "".join(unescaped)
+
+
+def _advance_markdown_component_scan(state: _MarkdownComponentScanState, character: str) -> None:
+ if state.quote is not None:
+ _advance_markdown_component_quote(state, character)
+ return
+
+ if state.expression_depth > 0:
+ _advance_markdown_component_expression(state, character)
+ return
+
+ if state.awaiting_prop_value:
+ if character.isspace():
+ return
+ state.awaiting_prop_value = False
+ if character in {"'", '"'}:
+ state.quote = character
+ return
+ if character == "{":
+ state.expression_depth = 1
+ return
- return tag_name, "\n".join(raw_lines).strip(), next_line_index + 1
+ if character == "=":
+ state.awaiting_prop_value = True
+ elif character == ">":
+ state.opening_tag_closed = True
+
+
+def _advance_markdown_component_quote(state: _MarkdownComponentScanState, character: str) -> None:
+ if state.escape_next:
+ state.escape_next = False
+ elif character == "\\":
+ state.escape_next = True
+ elif character == state.quote:
+ state.quote = None
+
+
+def _advance_markdown_component_expression(state: _MarkdownComponentScanState, character: str) -> None:
+ if character in {"'", '"'}:
+ state.quote = character
+ elif character == "{":
+ state.expression_depth += 1
+ elif character == "}":
+ state.expression_depth -= 1
def _parse_markdown_component_props(raw: str) -> dict[str, Any]:
@@ -402,8 +555,7 @@ def _parse_markdown_component_props(raw: str) -> dict[str, Any]:
source = match.group(2) or ""
index = 0
while index < len(source):
- while index < len(source) and source[index].isspace():
- index += 1
+ index = _skip_markdown_component_whitespace(source, index)
if index >= len(source):
break
@@ -413,16 +565,14 @@ def _parse_markdown_component_props(raw: str) -> dict[str, Any]:
name = name_match.group(1)
index += len(name)
- while index < len(source) and source[index].isspace():
- index += 1
+ index = _skip_markdown_component_whitespace(source, index)
if index >= len(source) or source[index] != "=":
props[name] = True
continue
index += 1
- while index < len(source) and source[index].isspace():
- index += 1
+ index = _skip_markdown_component_whitespace(source, index)
value, index = _read_markdown_component_prop_value(source, index)
if _is_markdown_notebook_prop_value(value):
@@ -431,6 +581,12 @@ def _parse_markdown_component_props(raw: str) -> dict[str, Any]:
return props
+def _skip_markdown_component_whitespace(source: str, index: int) -> int:
+ while index < len(source) and source[index].isspace():
+ index += 1
+ return index
+
+
def _read_markdown_component_prop_value(source: str, index: int) -> tuple[Any, int]:
first_char = source[index] if index < len(source) else ""