Open History to see the last commit
1/** Android never repositions children after maxWidth clamps; wide blocks and ordered lists need definite width. */
2
3const FENCED_CODE_BLOCK = /^ {0,3}(?:```|~~~)/m;
4const ORDERED_LIST_ITEM = /^ {0,3}\d{1,9}[.)](?:[ \t]+|$)/;
5const INDENTED_ORDERED_LIST_ITEM = /^( {4,})\d{1,9}[.)](?:[ \t]+|$)/;
6const ANY_LIST_ITEM = /^( *)(?:[-+*]|\d{1,9}[.)])(?:[ \t]+|$)/;
7const BLOCKQUOTE_PREFIX = /^ {0,3}>[ \t]?/;
8
9export interface WideMarkdownBlockOptions {
10 readonly includeOrderedLists?: boolean;
11 readonly includeBlockquotes?: boolean;
12}
13
14function stripBlockquotePrefixes(line: string): string {
15 let content = line;
16 while (BLOCKQUOTE_PREFIX.test(content)) {
17 content = content.replace(BLOCKQUOTE_PREFIX, "");
18 }
19 return content;
20}
21
22function hasIndentedCodeBlock(lines: ReadonlyArray<string>): boolean {
23 return lines.some((rawLine) => {
24 const line = stripBlockquotePrefixes(rawLine);
25 let column = 0;
26 let index = 0;
27
28 // Markdown tabs advance to the next four-column stop.
29 while (index < line.length) {
30 if (line[index] === " ") {
31 column += 1;
32 } else if (line[index] === "\t") {
33 column += 4 - (column % 4);
34 } else {
35 break;
36 }
37 index += 1;
38 }
39
40 return column >= 4 && index < line.length && line[index] !== "\r";
41 });
42}
43
44function hasOrderedListItem(lines: ReadonlyArray<string>): boolean {
45 let previousNonEmptyLine: string | null = null;
46
47 for (const rawLine of lines) {
48 const line = stripBlockquotePrefixes(rawLine);
49 if (ORDERED_LIST_ITEM.test(line)) {
50 return true;
51 }
52
53 const nestedMatch = INDENTED_ORDERED_LIST_ITEM.exec(line);
54 const parentMatch =
55 nestedMatch === null || previousNonEmptyLine === null
56 ? null
57 : ANY_LIST_ITEM.exec(previousNonEmptyLine);
58 if (
59 nestedMatch?.[1] !== undefined &&
60 parentMatch?.[1] !== undefined &&
61 parentMatch[1].length < nestedMatch[1].length
62 ) {
63 return true;
64 }
65
66 if (line.trim().length > 0) {
67 previousNonEmptyLine = line;
68 }
69 }
70
71 return false;
72}
73
74function isTableDelimiterRow(line: string): boolean {
75 const trimmed = line.trim();
76 if (!trimmed.includes("|") || !trimmed.includes("-")) {
77 return false;
78 }
79 return /^[|\-: \t]+$/.test(trimmed);
80}
81
82export function hasWideMarkdownBlock(
83 text: string,
84 options: WideMarkdownBlockOptions = {},
85): boolean {
86 if (FENCED_CODE_BLOCK.test(text)) {
87 return true;
88 }
89 const lines = text.split("\n");
90 if (options.includeBlockquotes === true && lines.some((line) => BLOCKQUOTE_PREFIX.test(line))) {
91 return true;
92 }
93 if (hasIndentedCodeBlock(lines)) {
94 return true;
95 }
96 if (options.includeOrderedLists !== false && hasOrderedListItem(lines)) {
97 return true;
98 }
99 if (!text.includes("|")) {
100 return false;
101 }
102 return lines.some(isTableDelimiterRow);
103}