Skip to content
TypeScript

fix(mobile): a table right under a line of text renders as a table (#20120)

shivamdcdb0348e409
diff --git a/apps/mobile/src/lib/markdownDocument.ts b/apps/mobile/src/lib/markdownDocument.ts
index f69dd416925..e690e5c5901 100644
--- a/apps/mobile/src/lib/markdownDocument.ts
+++ b/apps/mobile/src/lib/markdownDocument.ts
@@ -141,6 +141,68 @@ export function markdownWithHtml(markdown: string): string {
return markdown;
}
+// A delimiter row such as `|---|:--:|`, possibly inside a blockquote or list item.
+function isTableDelimiterRow(line: string): boolean {
+ if (!line.includes("-")) return false;
+ const row = line.replace(/^[ \t>]+/, "").trim();
+ return row
+ .replace(/^\||\|$/g, "")
+ .split("|")
+ .every((cell) => /^:?-+:?$/.test(cell.trim()));
+}
+
+// Cheap pre-check for a delimiter row two lines below text, so most messages skip the parse.
+function mayHaveTableUnderText(markdown: string): boolean {
+ if (!markdown.includes("|")) return false;
+ const lines = markdown.split(/\r\n|\r|\n/);
+ for (let index = 2; index < lines.length; index += 1) {
+ if (isTableDelimiterRow(lines[index]!) && /[^\s>]/.test(lines[index - 2]!)) return true;
+ }
+ return false;
+}
+
+/**
+ * GFM lets a table interrupt a paragraph, but the native parser (md4c) only starts a table
+ * on a paragraph's first line, so a table right under a line of text renders as one
+ * run-on paragraph. Insert the blank line md4c needs before each such table.
+ */
+export function markdownWithTableBreaks(markdown: string): string {
+ if (!mayHaveTableUnderText(markdown)) return markdown;
+ const lineStarts: number[] = [];
+ const visit = (node: MarkdownNode) => {
+ if (!("children" in node)) return;
+ node.children.forEach((child, index) => {
+ const previous = node.children[index - 1];
+ const start = child.position?.start;
+ if (
+ child.type === "table" &&
+ previous?.type === "paragraph" &&
+ start?.offset !== undefined &&
+ previous.position?.end.line === start.line - 1
+ )
+ lineStarts.push(
+ Math.max(
+ markdown.lastIndexOf("\n", start.offset - 1),
+ markdown.lastIndexOf("\r", start.offset - 1),
+ ) + 1,
+ );
+ visit(child);
+ });
+ };
+ visit(parser.parse(markdown));
+ for (const lineStart of lineStarts.reverse()) {
+ // The header row may be a lazy line without its container markers (`>` or list indent),
+ // so copy the delimiter row's markers onto the blank line and the header row.
+ const [, header = "", cells = "", ending = "\n", markers = ""] =
+ /^([ \t>]*)([^\r\n]*)(\r\n|\r|\n)([ \t>]*)/.exec(markdown.slice(lineStart)) ?? [];
+ markdown =
+ markdown.slice(0, lineStart) +
+ `${markers.trimEnd()}${ending}${markers}${cells}` +
+ markdown.slice(lineStart + header.length + cells.length);
+ }
+ return markdown;
+}
+
export function parseMarkdownDocument(markdown: string): Root {
return parser.parse(markdownWithHtml(markdown));
}
diff --git a/apps/mobile/src/lib/markdownTableBreaks.test.ts b/apps/mobile/src/lib/markdownTableBreaks.test.ts
new file mode 100644
index 00000000000..5e78904d12b
--- /dev/null
+++ b/apps/mobile/src/lib/markdownTableBreaks.test.ts
@@ -0,0 +1,56 @@
+import { describe, expect, it } from "vite-plus/test";
+import { markdownWithTableBreaks } from "./markdownDocument";
+
+const table = "| Company | Fit |\n|---|---|\n| Acme | A |";
+
+describe("tables right under a line of text", () => {
+ it("separates a table from the paragraph it interrupts", () => {
+ expect(markdownWithTableBreaks(`Companies on file\n${table}`)).toBe(
+ `Companies on file\n\n${table}`,
+ );
+ });
+
+ it("handles CRLF and CR line endings", () => {
+ const crlf = table.replaceAll("\n", "\r\n");
+ expect(markdownWithTableBreaks(`Companies on file\r\n${crlf}`)).toBe(
+ `Companies on file\r\n\r\n${crlf}`,
+ );
+ const cr = table.replaceAll("\n", "\r");
+ expect(markdownWithTableBreaks(`Companies on file\r${cr}`)).toBe(`Companies on file\r\r${cr}`);
+ });
+
+ it("keeps the blank line inside a blockquote", () => {
+ const quoted = table.replace(/^/gm, "> ");
+ expect(markdownWithTableBreaks(`> Companies on file\n${quoted}`)).toBe(
+ `> Companies on file\n>\n${quoted}`,
+ );
+ });
+
+ it("keeps a table with a lazy header row inside its container", () => {
+ expect(markdownWithTableBreaks("> Intro\n| a | b |\n> | - | - |\n> | c | d |")).toBe(
+ "> Intro\n>\n> | a | b |\n> | - | - |\n> | c | d |",
+ );
+ expect(markdownWithTableBreaks("- Intro\n| a | b |\n | - | - |\n | c | d |")).toBe(
+ "- Intro\n\n | a | b |\n | - | - |\n | c | d |",
+ );
+ });
+
+ it("separates every interrupting table, including ones in list items", () => {
+ const indented = table.replace(/^/gm, " ");
+ expect(markdownWithTableBreaks(`Intro\n${table}\n\n- Item\n${indented}`)).toBe(
+ `Intro\n\n${table}\n\n- Item\n\n${indented}`,
+ );
+ });
+
+ it("leaves Markdown that already renders alone", () => {
+ for (const markdown of [
+ `Companies on file\n\n${table}`,
+ `# Companies\n${table}`,
+ `\`\`\`md\nCompanies on file\n${table}\n\`\`\``,
+ "Not a table\n| a | b |\n|---|",
+ "a | b\nplain text",
+ ]) {
+ expect(markdownWithTableBreaks(markdown)).toBe(markdown);
+ }
+ });
+});
diff --git a/apps/mobile/src/native/EnrichedMarkdownText.tsx b/apps/mobile/src/native/EnrichedMarkdownText.tsx
index 0e0dada46b9..7fb3a51281e 100644
--- a/apps/mobile/src/native/EnrichedMarkdownText.tsx
+++ b/apps/mobile/src/native/EnrichedMarkdownText.tsx
@@ -4,7 +4,7 @@ import {
formatComposerContextHref,
formatComposerContextReference,
} from "@t3tools/shared/composerContextReferences";
-import { markdownWithHtml } from "../lib/markdownDocument";
+import { markdownWithHtml, markdownWithTableBreaks } from "../lib/markdownDocument";
import { useCallback, useMemo, useState, type ReactNode } from "react";
import { Platform, Share, StyleSheet, View } from "react-native";
import {
@@ -140,7 +140,10 @@ function enrichedStyle(
export function MobileEnrichedMarkdownText(props: SelectableMarkdownTextProps) {
const { renderImage, resolveImageSource } = props;
- const markdown = useMemo(() => markdownWithHtml(props.markdown), [props.markdown]);
+ const markdown = useMemo(
+ () => markdownWithTableBreaks(markdownWithHtml(props.markdown)),
+ [props.markdown],
+ );
const { themeAppearance } = useAppearancePreferences();
const [documentAssets, setDocumentAssets] = useState<DocumentAssetsEvent["assets"]>([]);
const onDocumentAssets = useCallback(({ assets }: DocumentAssetsEvent) => {