markdown.test.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. import assert from "node:assert";
  2. import { afterEach, describe, it } from "node:test";
  3. import type { Terminal as XtermTerminalType } from "@xterm/headless";
  4. import { Chalk } from "chalk";
  5. import { Markdown } from "../src/components/markdown.ts";
  6. import { resetCapabilitiesCache, setCapabilities } from "../src/terminal-image.ts";
  7. import { type Component, TUI } from "../src/tui.ts";
  8. import { defaultMarkdownTheme } from "./test-themes.ts";
  9. import { VirtualTerminal } from "./virtual-terminal.ts";
  10. // Force full color in CI so ANSI assertions are deterministic
  11. const chalk = new Chalk({ level: 3 });
  12. function getCellItalic(terminal: VirtualTerminal, row: number, col: number): number {
  13. const xterm = (terminal as unknown as { xterm: XtermTerminalType }).xterm;
  14. const buffer = xterm.buffer.active;
  15. const line = buffer.getLine(buffer.viewportY + row);
  16. assert.ok(line, `Missing buffer line at row ${row}`);
  17. const cell = line.getCell(col);
  18. assert.ok(cell, `Missing cell at row ${row} col ${col}`);
  19. return cell.isItalic();
  20. }
  21. function getCellUnderline(terminal: VirtualTerminal, row: number, col: number): number {
  22. const xterm = (terminal as unknown as { xterm: XtermTerminalType }).xterm;
  23. const buffer = xterm.buffer.active;
  24. const line = buffer.getLine(buffer.viewportY + row);
  25. assert.ok(line, `Missing buffer line at row ${row}`);
  26. const cell = line.getCell(col);
  27. assert.ok(cell, `Missing cell at row ${row} col ${col}`);
  28. return cell.isUnderline();
  29. }
  30. function stripAnsi(line: string): string {
  31. return line.replace(/\x1b\[[0-9;]*m/g, "");
  32. }
  33. describe("Markdown component", () => {
  34. describe("Lists", () => {
  35. it("should render simple nested list", () => {
  36. const markdown = new Markdown(
  37. `- Item 1
  38. - Nested 1.1
  39. - Nested 1.2
  40. - Item 2`,
  41. 0,
  42. 0,
  43. defaultMarkdownTheme,
  44. );
  45. const lines = markdown.render(80);
  46. // Check that we have content
  47. assert.ok(lines.length > 0);
  48. // Strip ANSI codes for checking
  49. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  50. // Check structure
  51. assert.ok(plainLines.some((line) => line.includes("- Item 1")));
  52. assert.ok(plainLines.some((line) => line.includes(" - Nested 1.1")));
  53. assert.ok(plainLines.some((line) => line.includes(" - Nested 1.2")));
  54. assert.ok(plainLines.some((line) => line.includes("- Item 2")));
  55. });
  56. it("should render deeply nested list", () => {
  57. const markdown = new Markdown(
  58. `- Level 1
  59. - Level 2
  60. - Level 3
  61. - Level 4`,
  62. 0,
  63. 0,
  64. defaultMarkdownTheme,
  65. );
  66. const lines = markdown.render(80);
  67. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  68. // Check proper indentation
  69. assert.ok(plainLines.some((line) => line.includes("- Level 1")));
  70. assert.ok(plainLines.some((line) => line.includes(" - Level 2")));
  71. assert.ok(plainLines.some((line) => line.includes(" - Level 3")));
  72. assert.ok(plainLines.some((line) => line.includes(" - Level 4")));
  73. });
  74. it("should render ordered nested list", () => {
  75. const markdown = new Markdown(
  76. `1. First
  77. 1. Nested first
  78. 2. Nested second
  79. 2. Second`,
  80. 0,
  81. 0,
  82. defaultMarkdownTheme,
  83. );
  84. const lines = markdown.render(80);
  85. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  86. assert.ok(plainLines.some((line) => line.includes("1. First")));
  87. assert.ok(plainLines.some((line) => line.includes(" 1. Nested first")));
  88. assert.ok(plainLines.some((line) => line.includes(" 2. Nested second")));
  89. assert.ok(plainLines.some((line) => line.includes("2. Second")));
  90. });
  91. it("should normalize ordered list markers by default", () => {
  92. const markdown = new Markdown("1. alpha\n1. beta\n1. gamma", 0, 0, defaultMarkdownTheme);
  93. const lines = markdown.render(80).map((line) => stripAnsi(line).trimEnd());
  94. assert.deepStrictEqual(lines, ["1. alpha", "2. beta", "3. gamma"]);
  95. });
  96. it("should preserve source ordered list markers when configured", () => {
  97. const markdown = new Markdown(
  98. " 4. forth\n 3. third\n\n10) ten\n7) seven",
  99. 0,
  100. 0,
  101. defaultMarkdownTheme,
  102. undefined,
  103. {
  104. preserveOrderedListMarkers: true,
  105. },
  106. );
  107. const lines = markdown.render(80).map((line) => stripAnsi(line).trimEnd());
  108. assert.deepStrictEqual(lines, ["4. forth", "3. third", "", "10) ten", "7) seven"]);
  109. });
  110. it("should render mixed ordered and unordered nested lists", () => {
  111. const markdown = new Markdown(
  112. `1. Ordered item
  113. - Unordered nested
  114. - Another nested
  115. 2. Second ordered
  116. - More nested`,
  117. 0,
  118. 0,
  119. defaultMarkdownTheme,
  120. );
  121. const lines = markdown.render(80);
  122. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  123. assert.ok(plainLines.some((line) => line.includes("1. Ordered item")));
  124. assert.ok(plainLines.some((line) => line.includes(" - Unordered nested")));
  125. assert.ok(plainLines.some((line) => line.includes("2. Second ordered")));
  126. });
  127. it("should render task list markers", () => {
  128. const markdown = new Markdown("- [ ] beep\n- [x] boop", 0, 0, defaultMarkdownTheme);
  129. const lines = markdown.render(80).map((line) => stripAnsi(line).trimEnd());
  130. assert.deepStrictEqual(lines, ["- [ ] beep", "- [x] boop"]);
  131. });
  132. it("should maintain numbering when code blocks are not indented (LLM output)", () => {
  133. // When code blocks aren't indented, marked parses each item as a separate list.
  134. // We use token.start to preserve the original numbering.
  135. const markdown = new Markdown(
  136. `1. First item
  137. \`\`\`typescript
  138. // code block
  139. \`\`\`
  140. 2. Second item
  141. \`\`\`typescript
  142. // another code block
  143. \`\`\`
  144. 3. Third item`,
  145. 0,
  146. 0,
  147. defaultMarkdownTheme,
  148. );
  149. const lines = markdown.render(80);
  150. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trim());
  151. // Find all lines that start with a number and period
  152. const numberedLines = plainLines.filter((line) => /^\d+\./.test(line));
  153. // Should have 3 numbered items
  154. assert.strictEqual(numberedLines.length, 3, `Expected 3 numbered items, got: ${numberedLines.join(", ")}`);
  155. // Check the actual numbers
  156. assert.ok(numberedLines[0].startsWith("1."), `First item should be "1.", got: ${numberedLines[0]}`);
  157. assert.ok(numberedLines[1].startsWith("2."), `Second item should be "2.", got: ${numberedLines[1]}`);
  158. assert.ok(numberedLines[2].startsWith("3."), `Third item should be "3.", got: ${numberedLines[2]}`);
  159. });
  160. it("should indent wrapped unordered list lines", () => {
  161. const markdown = new Markdown("- alpha beta gamma delta epsilon", 0, 0, defaultMarkdownTheme);
  162. const lines = markdown.render(20).map((line) => stripAnsi(line).trimEnd());
  163. assert.deepStrictEqual(lines, ["- alpha beta gamma", " delta epsilon"]);
  164. });
  165. it("should indent wrapped ordered list lines", () => {
  166. const markdown = new Markdown("1. alpha beta gamma delta epsilon", 0, 0, defaultMarkdownTheme);
  167. const lines = markdown.render(20).map((line) => stripAnsi(line).trimEnd());
  168. assert.deepStrictEqual(lines, ["1. alpha beta gamma", " delta epsilon"]);
  169. });
  170. it("should indent wrapped ordered list lines with multi-digit markers", () => {
  171. const markdown = new Markdown("10. alpha beta gamma delta epsilon", 0, 0, defaultMarkdownTheme);
  172. const lines = markdown.render(21).map((line) => stripAnsi(line).trimEnd());
  173. assert.deepStrictEqual(lines, ["10. alpha beta gamma", " delta epsilon"]);
  174. });
  175. it("should indent wrapped nested list lines", () => {
  176. const markdown = new Markdown(`- parent\n - alpha beta gamma delta epsilon`, 0, 0, defaultMarkdownTheme);
  177. const lines = markdown.render(24).map((line) => stripAnsi(line).trimEnd());
  178. assert.deepStrictEqual(lines, ["- parent", " - alpha beta gamma", " delta epsilon"]);
  179. });
  180. it("should indent wrapped nested list lines under ordered parents", () => {
  181. const markdown = new Markdown(`1. parent\n - alpha beta gamma delta epsilon`, 0, 0, defaultMarkdownTheme);
  182. const lines = markdown.render(24).map((line) => stripAnsi(line).trimEnd());
  183. assert.deepStrictEqual(lines, ["1. parent", " - alpha beta gamma", " delta epsilon"]);
  184. });
  185. it("should render and wrap blockquotes inside list items", () => {
  186. const markdown = new Markdown("- > alpha beta gamma delta epsilon zeta", 0, 0, defaultMarkdownTheme);
  187. const lines = markdown.render(24).map((line) => stripAnsi(line).trimEnd());
  188. assert.deepStrictEqual(lines, ["- │ alpha beta gamma", " │ delta epsilon zeta"]);
  189. });
  190. it("should render and wrap code blocks inside list items", () => {
  191. const markdown = new Markdown(
  192. "- ```ts\n alpha beta gamma delta epsilon zeta\n ```",
  193. 0,
  194. 0,
  195. defaultMarkdownTheme,
  196. );
  197. const lines = markdown.render(24).map((line) => stripAnsi(line).trimEnd());
  198. assert.deepStrictEqual(lines, ["- ```ts", " alpha beta gamma", " delta epsilon zeta", " ```"]);
  199. });
  200. });
  201. describe("Tables", () => {
  202. it("should render simple table", () => {
  203. const markdown = new Markdown(
  204. `| Name | Age |
  205. | --- | --- |
  206. | Alice | 30 |
  207. | Bob | 25 |`,
  208. 0,
  209. 0,
  210. defaultMarkdownTheme,
  211. );
  212. const lines = markdown.render(80);
  213. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  214. // Check table structure
  215. assert.ok(plainLines.some((line) => line.includes("Name")));
  216. assert.ok(plainLines.some((line) => line.includes("Age")));
  217. assert.ok(plainLines.some((line) => line.includes("Alice")));
  218. assert.ok(plainLines.some((line) => line.includes("Bob")));
  219. // Check for table borders
  220. assert.ok(plainLines.some((line) => line.includes("│")));
  221. assert.ok(plainLines.some((line) => line.includes("─")));
  222. });
  223. it("should render row dividers between data rows", () => {
  224. const markdown = new Markdown(
  225. `| Name | Age |
  226. | --- | --- |
  227. | Alice | 30 |
  228. | Bob | 25 |`,
  229. 0,
  230. 0,
  231. defaultMarkdownTheme,
  232. );
  233. const lines = markdown.render(80);
  234. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  235. const dividerLines = plainLines.filter((line) => line.includes("┼"));
  236. assert.strictEqual(dividerLines.length, 2, "Expected header + row divider");
  237. });
  238. it("should keep column width at least the longest word", () => {
  239. const longestWord = "superlongword";
  240. const markdown = new Markdown(
  241. `| Column One | Column Two |
  242. | --- | --- |
  243. | ${longestWord} short | otherword |
  244. | small | tiny |`,
  245. 0,
  246. 0,
  247. defaultMarkdownTheme,
  248. );
  249. const lines = markdown.render(32);
  250. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  251. const dataLine = plainLines.find((line) => line.includes(longestWord));
  252. assert.ok(dataLine, "Expected data row containing longest word");
  253. const segments = dataLine.split("│").slice(1, -1);
  254. const [firstSegment] = segments;
  255. assert.ok(firstSegment, "Expected first column segment");
  256. const firstColumnWidth = firstSegment.length - 2;
  257. assert.ok(
  258. firstColumnWidth >= longestWord.length,
  259. `Expected first column width >= ${longestWord.length}, got ${firstColumnWidth}`,
  260. );
  261. });
  262. it("should render table with alignment", () => {
  263. const markdown = new Markdown(
  264. `| Left | Center | Right |
  265. | :--- | :---: | ---: |
  266. | A | B | C |
  267. | Long text | Middle | End |`,
  268. 0,
  269. 0,
  270. defaultMarkdownTheme,
  271. );
  272. const lines = markdown.render(80);
  273. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  274. // Check headers
  275. assert.ok(plainLines.some((line) => line.includes("Left")));
  276. assert.ok(plainLines.some((line) => line.includes("Center")));
  277. assert.ok(plainLines.some((line) => line.includes("Right")));
  278. // Check content
  279. assert.ok(plainLines.some((line) => line.includes("Long text")));
  280. });
  281. it("should handle tables with varying column widths", () => {
  282. const markdown = new Markdown(
  283. `| Short | Very long column header |
  284. | --- | --- |
  285. | A | This is a much longer cell content |
  286. | B | Short |`,
  287. 0,
  288. 0,
  289. defaultMarkdownTheme,
  290. );
  291. const lines = markdown.render(80);
  292. // Should render without errors
  293. assert.ok(lines.length > 0);
  294. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  295. assert.ok(plainLines.some((line) => line.includes("Very long column header")));
  296. assert.ok(plainLines.some((line) => line.includes("This is a much longer cell content")));
  297. });
  298. it("should wrap table cells when table exceeds available width", () => {
  299. const markdown = new Markdown(
  300. `| Command | Description | Example |
  301. | --- | --- | --- |
  302. | npm install | Install all dependencies | npm install |
  303. | npm run build | Build the project | npm run build |`,
  304. 0,
  305. 0,
  306. defaultMarkdownTheme,
  307. );
  308. // Render at narrow width that forces wrapping
  309. const lines = markdown.render(50);
  310. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  311. // All lines should fit within width
  312. for (const line of plainLines) {
  313. assert.ok(line.length <= 50, `Line exceeds width 50: "${line}" (length: ${line.length})`);
  314. }
  315. // Content should still be present (possibly wrapped across lines)
  316. const allText = plainLines.join(" ");
  317. assert.ok(allText.includes("Command"), "Should contain 'Command'");
  318. assert.ok(allText.includes("Description"), "Should contain 'Description'");
  319. assert.ok(allText.includes("npm install"), "Should contain 'npm install'");
  320. assert.ok(allText.includes("Install"), "Should contain 'Install'");
  321. });
  322. it("should wrap long cell content to multiple lines", () => {
  323. const markdown = new Markdown(
  324. `| Header |
  325. | --- |
  326. | This is a very long cell content that should wrap |`,
  327. 0,
  328. 0,
  329. defaultMarkdownTheme,
  330. );
  331. // Render at width that forces the cell to wrap
  332. const lines = markdown.render(25);
  333. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  334. // Should have multiple data rows due to wrapping
  335. const dataRows = plainLines.filter((line) => line.startsWith("│") && !line.includes("─"));
  336. assert.ok(dataRows.length > 2, `Expected wrapped rows, got ${dataRows.length} rows`);
  337. // All content should be preserved (may be split across lines)
  338. const allText = plainLines.join(" ");
  339. assert.ok(allText.includes("very long"), "Should preserve 'very long'");
  340. assert.ok(allText.includes("cell content"), "Should preserve 'cell content'");
  341. assert.ok(allText.includes("should wrap"), "Should preserve 'should wrap'");
  342. });
  343. it("should wrap long unbroken tokens inside table cells (not only at line start)", () => {
  344. // Pin to no-hyperlinks so width checks work on plain text without OSC 8 sequences.
  345. setCapabilities({ images: null, trueColor: false, hyperlinks: false });
  346. const url = "https://example.com/this/is/a/very/long/url/that/should/wrap";
  347. const markdown = new Markdown(
  348. `| Value |
  349. | --- |
  350. | prefix ${url} |`,
  351. 0,
  352. 0,
  353. defaultMarkdownTheme,
  354. );
  355. const width = 30;
  356. const lines = markdown.render(width);
  357. resetCapabilitiesCache();
  358. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  359. for (const line of plainLines) {
  360. assert.ok(line.length <= width, `Line exceeds width ${width}: "${line}" (length: ${line.length})`);
  361. }
  362. // Borders should stay intact (exactly 2 vertical borders for a 1-col table)
  363. const tableLines = plainLines.filter((line) => line.startsWith("│"));
  364. assert.ok(tableLines.length > 0, "Expected table rows to render");
  365. for (const line of tableLines) {
  366. const borderCount = line.split("│").length - 1;
  367. assert.strictEqual(borderCount, 2, `Expected 2 borders, got ${borderCount}: "${line}"`);
  368. }
  369. // Strip box drawing characters + whitespace so we can assert the URL is preserved
  370. // even if it was split across multiple wrapped lines.
  371. const extracted = plainLines.join("").replace(/[│├┤─\s]/g, "");
  372. assert.ok(extracted.includes("prefix"), "Should preserve 'prefix'");
  373. assert.ok(extracted.includes(url), "Should preserve URL");
  374. });
  375. it("should wrap styled inline code inside table cells without breaking borders", () => {
  376. const markdown = new Markdown(
  377. `| Code |
  378. | --- |
  379. | \`averyveryveryverylongidentifier\` |`,
  380. 0,
  381. 0,
  382. defaultMarkdownTheme,
  383. );
  384. const width = 20;
  385. const lines = markdown.render(width);
  386. const joinedOutput = lines.join("\n");
  387. assert.ok(joinedOutput.includes("\x1b[33m"), "Inline code should be styled (yellow)");
  388. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  389. for (const line of plainLines) {
  390. assert.ok(line.length <= width, `Line exceeds width ${width}: "${line}" (length: ${line.length})`);
  391. }
  392. const tableLines = plainLines.filter((line) => line.startsWith("│"));
  393. for (const line of tableLines) {
  394. const borderCount = line.split("│").length - 1;
  395. assert.strictEqual(borderCount, 2, `Expected 2 borders, got ${borderCount}: "${line}"`);
  396. }
  397. });
  398. it("should handle extremely narrow width gracefully", () => {
  399. const markdown = new Markdown(
  400. `| A | B | C |
  401. | --- | --- | --- |
  402. | 1 | 2 | 3 |`,
  403. 0,
  404. 0,
  405. defaultMarkdownTheme,
  406. );
  407. // Very narrow width
  408. const lines = markdown.render(15);
  409. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  410. // Should not crash and should produce output
  411. assert.ok(lines.length > 0, "Should produce output");
  412. // Lines should not exceed width
  413. for (const line of plainLines) {
  414. assert.ok(line.length <= 15, `Line exceeds width 15: "${line}" (length: ${line.length})`);
  415. }
  416. });
  417. it("should render table correctly when it fits naturally", () => {
  418. const markdown = new Markdown(
  419. `| A | B |
  420. | --- | --- |
  421. | 1 | 2 |`,
  422. 0,
  423. 0,
  424. defaultMarkdownTheme,
  425. );
  426. // Wide width where table fits naturally
  427. const lines = markdown.render(80);
  428. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  429. // Should have proper table structure
  430. const headerLine = plainLines.find((line) => line.includes("A") && line.includes("B"));
  431. assert.ok(headerLine, "Should have header row");
  432. assert.ok(headerLine?.includes("│"), "Header should have borders");
  433. const separatorLine = plainLines.find((line) => line.includes("├") && line.includes("┼"));
  434. assert.ok(separatorLine, "Should have separator row");
  435. const dataLine = plainLines.find((line) => line.includes("1") && line.includes("2"));
  436. assert.ok(dataLine, "Should have data row");
  437. });
  438. it("should respect paddingX when calculating table width", () => {
  439. const markdown = new Markdown(
  440. `| Column One | Column Two |
  441. | --- | --- |
  442. | Data 1 | Data 2 |`,
  443. 2, // paddingX = 2
  444. 0,
  445. defaultMarkdownTheme,
  446. );
  447. // Width 40 with paddingX=2 means contentWidth=36
  448. const lines = markdown.render(40);
  449. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  450. // All lines should respect width
  451. for (const line of plainLines) {
  452. assert.ok(line.length <= 40, `Line exceeds width 40: "${line}" (length: ${line.length})`);
  453. }
  454. // Table rows should have left padding
  455. const tableRow = plainLines.find((line) => line.includes("│"));
  456. assert.ok(tableRow?.startsWith(" "), "Table should have left padding");
  457. });
  458. it("should not add a trailing blank line when table is the last rendered block", () => {
  459. const markdown = new Markdown(
  460. `| Name |
  461. | --- |
  462. | Alice |`,
  463. 0,
  464. 0,
  465. defaultMarkdownTheme,
  466. );
  467. const lines = markdown.render(80);
  468. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  469. assert.notStrictEqual(
  470. plainLines.at(-1),
  471. "",
  472. `Expected table to end without a blank line: ${JSON.stringify(plainLines)}`,
  473. );
  474. });
  475. });
  476. describe("Combined features", () => {
  477. it("should render lists and tables together", () => {
  478. const markdown = new Markdown(
  479. `# Test Document
  480. - Item 1
  481. - Nested item
  482. - Item 2
  483. | Col1 | Col2 |
  484. | --- | --- |
  485. | A | B |`,
  486. 0,
  487. 0,
  488. defaultMarkdownTheme,
  489. );
  490. const lines = markdown.render(80);
  491. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  492. // Check heading
  493. assert.ok(plainLines.some((line) => line.includes("Test Document")));
  494. // Check list
  495. assert.ok(plainLines.some((line) => line.includes("- Item 1")));
  496. assert.ok(plainLines.some((line) => line.includes(" - Nested item")));
  497. // Check table
  498. assert.ok(plainLines.some((line) => line.includes("Col1")));
  499. assert.ok(plainLines.some((line) => line.includes("│")));
  500. });
  501. });
  502. describe("Pre-styled text (thinking traces)", () => {
  503. it("should preserve gray italic styling after inline code", () => {
  504. // This replicates how thinking content is rendered in assistant-message.ts
  505. const markdown = new Markdown(
  506. "This is thinking with `inline code` and more text after",
  507. 1,
  508. 0,
  509. defaultMarkdownTheme,
  510. {
  511. color: (text) => chalk.gray(text),
  512. italic: true,
  513. },
  514. );
  515. const lines = markdown.render(80);
  516. const joinedOutput = lines.join("\n");
  517. // Should contain the inline code block
  518. assert.ok(joinedOutput.includes("inline code"));
  519. // The output should have ANSI codes for gray (90) and italic (3)
  520. assert.ok(joinedOutput.includes("\x1b[90m"), "Should have gray color code");
  521. assert.ok(joinedOutput.includes("\x1b[3m"), "Should have italic code");
  522. // Verify that inline code is styled (theme uses yellow)
  523. const hasCodeColor = joinedOutput.includes("\x1b[33m");
  524. assert.ok(hasCodeColor, "Should style inline code");
  525. });
  526. it("should preserve gray italic styling after bold text", () => {
  527. const markdown = new Markdown(
  528. "This is thinking with **bold text** and more after",
  529. 1,
  530. 0,
  531. defaultMarkdownTheme,
  532. {
  533. color: (text) => chalk.gray(text),
  534. italic: true,
  535. },
  536. );
  537. const lines = markdown.render(80);
  538. const joinedOutput = lines.join("\n");
  539. // Should contain bold text
  540. assert.ok(joinedOutput.includes("bold text"));
  541. // The output should have ANSI codes for gray (90) and italic (3)
  542. assert.ok(joinedOutput.includes("\x1b[90m"), "Should have gray color code");
  543. assert.ok(joinedOutput.includes("\x1b[3m"), "Should have italic code");
  544. // Should have bold codes (1 or 22 for bold on/off)
  545. assert.ok(joinedOutput.includes("\x1b[1m"), "Should have bold code");
  546. });
  547. it("should not leak styles into following lines when rendered in TUI", async () => {
  548. class MarkdownWithInput implements Component {
  549. public markdownLineCount = 0;
  550. private readonly markdown: Markdown;
  551. constructor(markdown: Markdown) {
  552. this.markdown = markdown;
  553. }
  554. render(width: number): string[] {
  555. const lines = this.markdown.render(width);
  556. this.markdownLineCount = lines.length;
  557. return [...lines, "INPUT"];
  558. }
  559. invalidate(): void {
  560. this.markdown.invalidate();
  561. }
  562. }
  563. const markdown = new Markdown("This is thinking with `inline code`", 1, 0, defaultMarkdownTheme, {
  564. color: (text) => chalk.gray(text),
  565. italic: true,
  566. });
  567. const terminal = new VirtualTerminal(80, 6);
  568. const tui = new TUI(terminal);
  569. const component = new MarkdownWithInput(markdown);
  570. tui.addChild(component);
  571. tui.start();
  572. await terminal.waitForRender();
  573. assert.ok(component.markdownLineCount > 0);
  574. const inputRow = component.markdownLineCount;
  575. assert.strictEqual(getCellItalic(terminal, inputRow, 0), 0);
  576. tui.stop();
  577. });
  578. });
  579. describe("Spacing after code blocks", () => {
  580. it("should have only one blank line between code block and following paragraph", () => {
  581. const markdown = new Markdown(
  582. `hello world
  583. \`\`\`js
  584. const hello = "world";
  585. \`\`\`
  586. again, hello world`,
  587. 0,
  588. 0,
  589. defaultMarkdownTheme,
  590. );
  591. const lines = markdown.render(80);
  592. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  593. const closingBackticksIndex = plainLines.indexOf("```");
  594. assert.ok(closingBackticksIndex !== -1, "Should have closing backticks");
  595. const afterBackticks = plainLines.slice(closingBackticksIndex + 1);
  596. const emptyLineCount = afterBackticks.findIndex((line) => line !== "");
  597. assert.strictEqual(
  598. emptyLineCount,
  599. 1,
  600. `Expected 1 empty line after code block, but found ${emptyLineCount}. Lines after backticks: ${JSON.stringify(afterBackticks.slice(0, 5))}`,
  601. );
  602. });
  603. it("should normalize paragraph and code block spacing to one blank line", () => {
  604. const cases = [
  605. `hello this is text
  606. \`\`\`
  607. code block
  608. \`\`\`
  609. more text`,
  610. `hello this is text
  611. \`\`\`
  612. code block
  613. \`\`\`
  614. more text`,
  615. ];
  616. const expectedLines = ["hello this is text", "", "```", " code block", "```", "", "more text"];
  617. for (const text of cases) {
  618. const markdown = new Markdown(text, 0, 0, defaultMarkdownTheme);
  619. const lines = markdown.render(80);
  620. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  621. assert.deepStrictEqual(
  622. plainLines,
  623. expectedLines,
  624. `Unexpected spacing for markdown: ${JSON.stringify(text)}`,
  625. );
  626. }
  627. });
  628. it("should not add a trailing blank line when code block is the last rendered block", () => {
  629. const cases = ["```js\nconst hello = 'world';\n```", "hello world\n\n```js\nconst hello = 'world';\n```"];
  630. for (const text of cases) {
  631. const markdown = new Markdown(text, 0, 0, defaultMarkdownTheme);
  632. const lines = markdown.render(80);
  633. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  634. assert.notStrictEqual(
  635. plainLines.at(-1),
  636. "",
  637. `Expected code block to end without a blank line: ${JSON.stringify(plainLines)}`,
  638. );
  639. }
  640. });
  641. });
  642. describe("Spacing after dividers", () => {
  643. it("should have only one blank line between divider and following paragraph", () => {
  644. const markdown = new Markdown(
  645. `hello world
  646. ---
  647. again, hello world`,
  648. 0,
  649. 0,
  650. defaultMarkdownTheme,
  651. );
  652. const lines = markdown.render(80);
  653. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  654. const dividerIndex = plainLines.findIndex((line) => line.includes("─"));
  655. assert.ok(dividerIndex !== -1, "Should have divider");
  656. const afterDivider = plainLines.slice(dividerIndex + 1);
  657. const emptyLineCount = afterDivider.findIndex((line) => line !== "");
  658. assert.strictEqual(
  659. emptyLineCount,
  660. 1,
  661. `Expected 1 empty line after divider, but found ${emptyLineCount}. Lines after divider: ${JSON.stringify(afterDivider.slice(0, 5))}`,
  662. );
  663. });
  664. it("should not add a trailing blank line when divider is the last rendered block", () => {
  665. const markdown = new Markdown("---", 0, 0, defaultMarkdownTheme);
  666. const lines = markdown.render(80);
  667. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  668. assert.notStrictEqual(
  669. plainLines.at(-1),
  670. "",
  671. `Expected divider to end without a blank line: ${JSON.stringify(plainLines)}`,
  672. );
  673. });
  674. });
  675. describe("Spacing after headings", () => {
  676. it("should have only one blank line between heading and following paragraph", () => {
  677. const markdown = new Markdown(
  678. `# Hello
  679. This is a paragraph`,
  680. 0,
  681. 0,
  682. defaultMarkdownTheme,
  683. );
  684. const lines = markdown.render(80);
  685. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  686. const headingIndex = plainLines.findIndex((line) => line.includes("Hello"));
  687. assert.ok(headingIndex !== -1, "Should have heading");
  688. const afterHeading = plainLines.slice(headingIndex + 1);
  689. const emptyLineCount = afterHeading.findIndex((line) => line !== "");
  690. assert.strictEqual(
  691. emptyLineCount,
  692. 1,
  693. `Expected 1 empty line after heading, but found ${emptyLineCount}. Lines after heading: ${JSON.stringify(afterHeading.slice(0, 5))}`,
  694. );
  695. });
  696. it("should not add a trailing blank line when heading is the last rendered block", () => {
  697. const markdown = new Markdown("# Hello", 0, 0, defaultMarkdownTheme);
  698. const lines = markdown.render(80);
  699. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  700. assert.notStrictEqual(
  701. plainLines.at(-1),
  702. "",
  703. `Expected heading to end without a blank line: ${JSON.stringify(plainLines)}`,
  704. );
  705. });
  706. });
  707. describe("Spacing after blockquotes", () => {
  708. it("should have only one blank line between blockquote and following paragraph", () => {
  709. const markdown = new Markdown(
  710. `hello world
  711. > This is a quote
  712. again, hello world`,
  713. 0,
  714. 0,
  715. defaultMarkdownTheme,
  716. );
  717. const lines = markdown.render(80);
  718. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  719. const quoteIndex = plainLines.findIndex((line) => line.includes("This is a quote"));
  720. assert.ok(quoteIndex !== -1, "Should have blockquote");
  721. const afterQuote = plainLines.slice(quoteIndex + 1);
  722. const emptyLineCount = afterQuote.findIndex((line) => line !== "");
  723. assert.strictEqual(
  724. emptyLineCount,
  725. 1,
  726. `Expected 1 empty line after blockquote, but found ${emptyLineCount}. Lines after quote: ${JSON.stringify(afterQuote.slice(0, 5))}`,
  727. );
  728. });
  729. it("should not add a trailing blank line when blockquote is the last rendered block", () => {
  730. const markdown = new Markdown("> This is a quote", 0, 0, defaultMarkdownTheme);
  731. const lines = markdown.render(80);
  732. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  733. assert.notStrictEqual(
  734. plainLines.at(-1),
  735. "",
  736. `Expected blockquote to end without a blank line: ${JSON.stringify(plainLines)}`,
  737. );
  738. });
  739. });
  740. describe("Blockquotes with multiline content", () => {
  741. it("should apply consistent styling to all lines in lazy continuation blockquote", () => {
  742. // Markdown "lazy continuation" - second line without > is still part of the quote
  743. const markdown = new Markdown(
  744. `>Foo
  745. bar`,
  746. 0,
  747. 0,
  748. defaultMarkdownTheme,
  749. {
  750. color: (text) => chalk.magenta(text), // This should NOT be applied to blockquotes
  751. },
  752. );
  753. const lines = markdown.render(80);
  754. // Both lines should have the quote border
  755. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  756. const quotedLines = plainLines.filter((line) => line.startsWith("│ "));
  757. assert.strictEqual(quotedLines.length, 2, `Expected 2 quoted lines, got: ${JSON.stringify(plainLines)}`);
  758. // Both lines should have italic (from theme.quote styling)
  759. const fooLine = lines.find((line) => line.includes("Foo"));
  760. const barLine = lines.find((line) => line.includes("bar"));
  761. assert.ok(fooLine, "Should have Foo line");
  762. assert.ok(barLine, "Should have bar line");
  763. // Check that both have italic (\x1b[3m) - blockquotes use theme styling, not default message color
  764. assert.ok(fooLine?.includes("\x1b[3m"), `Foo line should have italic: ${fooLine}`);
  765. assert.ok(barLine?.includes("\x1b[3m"), `bar line should have italic: ${barLine}`);
  766. // Blockquotes should NOT have the default message color (magenta)
  767. assert.ok(!fooLine?.includes("\x1b[35m"), `Foo line should NOT have magenta color: ${fooLine}`);
  768. assert.ok(!barLine?.includes("\x1b[35m"), `bar line should NOT have magenta color: ${barLine}`);
  769. });
  770. it("should apply consistent styling to explicit multiline blockquote", () => {
  771. const markdown = new Markdown(
  772. `>Foo
  773. >bar`,
  774. 0,
  775. 0,
  776. defaultMarkdownTheme,
  777. {
  778. color: (text) => chalk.cyan(text), // This should NOT be applied to blockquotes
  779. },
  780. );
  781. const lines = markdown.render(80);
  782. // Both lines should have the quote border
  783. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  784. const quotedLines = plainLines.filter((line) => line.startsWith("│ "));
  785. assert.strictEqual(quotedLines.length, 2, `Expected 2 quoted lines, got: ${JSON.stringify(plainLines)}`);
  786. // Both lines should have italic (from theme.quote styling)
  787. const fooLine = lines.find((line) => line.includes("Foo"));
  788. const barLine = lines.find((line) => line.includes("bar"));
  789. assert.ok(fooLine?.includes("\x1b[3m"), `Foo line should have italic: ${fooLine}`);
  790. assert.ok(barLine?.includes("\x1b[3m"), `bar line should have italic: ${barLine}`);
  791. // Blockquotes should NOT have the default message color (cyan)
  792. assert.ok(!fooLine?.includes("\x1b[36m"), `Foo line should NOT have cyan color: ${fooLine}`);
  793. assert.ok(!barLine?.includes("\x1b[36m"), `bar line should NOT have cyan color: ${barLine}`);
  794. });
  795. it("should render list content inside blockquotes", () => {
  796. const markdown = new Markdown(
  797. `> 1. bla bla
  798. > - nested bullet`,
  799. 0,
  800. 0,
  801. defaultMarkdownTheme,
  802. );
  803. const lines = markdown.render(80);
  804. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  805. const quotedLines = plainLines.filter((line) => line.startsWith("│ "));
  806. assert.ok(
  807. quotedLines.some((line) => line.includes("1. bla bla")),
  808. `Missing ordered list item: ${JSON.stringify(quotedLines)}`,
  809. );
  810. assert.ok(
  811. quotedLines.some((line) => line.includes("- nested bullet")),
  812. `Missing unordered list item: ${JSON.stringify(quotedLines)}`,
  813. );
  814. });
  815. it("should wrap long blockquote lines and add border to each wrapped line", () => {
  816. const longText = "This is a very long blockquote line that should wrap to multiple lines when rendered";
  817. const markdown = new Markdown(`> ${longText}`, 0, 0, defaultMarkdownTheme);
  818. // Render at narrow width to force wrapping
  819. const lines = markdown.render(30);
  820. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  821. // Filter to non-empty lines (exclude trailing blank line after blockquote)
  822. const contentLines = plainLines.filter((line) => line.length > 0);
  823. // Should have multiple lines due to wrapping
  824. assert.ok(contentLines.length > 1, `Expected multiple wrapped lines, got: ${JSON.stringify(contentLines)}`);
  825. // Every content line should start with the quote border
  826. for (const line of contentLines) {
  827. assert.ok(line.startsWith("│ "), `Wrapped line should have quote border: "${line}"`);
  828. }
  829. // All content should be preserved
  830. const allText = contentLines.join(" ");
  831. assert.ok(allText.includes("very long"), "Should preserve 'very long'");
  832. assert.ok(allText.includes("blockquote"), "Should preserve 'blockquote'");
  833. assert.ok(allText.includes("multiple"), "Should preserve 'multiple'");
  834. });
  835. it("should properly indent wrapped blockquote lines with styling", () => {
  836. const markdown = new Markdown(
  837. "> This is styled text that is long enough to wrap",
  838. 0,
  839. 0,
  840. defaultMarkdownTheme,
  841. {
  842. color: (text) => chalk.yellow(text), // This should NOT be applied to blockquotes
  843. italic: true,
  844. },
  845. );
  846. const lines = markdown.render(25);
  847. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "").trimEnd());
  848. // Filter to non-empty lines
  849. const contentLines = plainLines.filter((line) => line.length > 0);
  850. // All lines should have the quote border
  851. for (const line of contentLines) {
  852. assert.ok(line.startsWith("│ "), `Line should have quote border: "${line}"`);
  853. }
  854. // Check that italic is applied (from theme.quote)
  855. const allOutput = lines.join("\n");
  856. assert.ok(allOutput.includes("\x1b[3m"), "Should have italic");
  857. // Blockquotes should NOT have the default message color (yellow)
  858. assert.ok(!allOutput.includes("\x1b[33m"), "Should NOT have yellow color from default style");
  859. });
  860. it("should render inline formatting inside blockquotes and reapply quote styling after", () => {
  861. const markdown = new Markdown("> Quote with **bold** and `code`", 0, 0, defaultMarkdownTheme);
  862. const lines = markdown.render(80);
  863. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  864. // Should have the quote border
  865. assert.ok(
  866. plainLines.some((line) => line.startsWith("│ ")),
  867. "Should have quote border",
  868. );
  869. // Content should be preserved
  870. const allPlain = plainLines.join(" ");
  871. assert.ok(allPlain.includes("Quote with"), "Should preserve 'Quote with'");
  872. assert.ok(allPlain.includes("bold"), "Should preserve 'bold'");
  873. assert.ok(allPlain.includes("code"), "Should preserve 'code'");
  874. const allOutput = lines.join("\n");
  875. // Should have bold styling (\x1b[1m)
  876. assert.ok(allOutput.includes("\x1b[1m"), "Should have bold styling");
  877. // Should have code styling (yellow = \x1b[33m from defaultMarkdownTheme)
  878. assert.ok(allOutput.includes("\x1b[33m"), "Should have code styling (yellow)");
  879. // Should have italic from quote styling (\x1b[3m)
  880. assert.ok(allOutput.includes("\x1b[3m"), "Should have italic from quote styling");
  881. });
  882. });
  883. describe("Heading with inline code", () => {
  884. it("should preserve heading styling after inline code", () => {
  885. const markdown = new Markdown("### Why `sourceInfo` should not be optional", 0, 0, defaultMarkdownTheme);
  886. const lines = markdown.render(80);
  887. const joinedOutput = lines.join("\n");
  888. // The heading theme is bold+cyan. After the yellow inline code, the heading
  889. // styling (bold+cyan) must be restored so subsequent text is styled correctly.
  890. // bold = \x1b[1m, cyan = \x1b[36m, yellow = \x1b[33m
  891. assert.ok(joinedOutput.includes("\x1b[33m"), "Should have yellow for inline code");
  892. // Find the position of "should not be optional" in the raw output.
  893. // It must be preceded by heading style codes (bold+cyan), not appear unstyled.
  894. const afterCodeIndex = joinedOutput.indexOf("should not be optional");
  895. assert.ok(afterCodeIndex > 0, "Should contain text after inline code");
  896. // Look at the ANSI codes between the code span end and "should not be optional".
  897. // There should be bold (\x1b[1m) and cyan (\x1b[36m) re-applied.
  898. const precedingChunk = joinedOutput.slice(Math.max(0, afterCodeIndex - 40), afterCodeIndex);
  899. assert.ok(
  900. precedingChunk.includes("\x1b[1m"),
  901. `Should re-apply bold before text after code: ${precedingChunk}`,
  902. );
  903. assert.ok(
  904. precedingChunk.includes("\x1b[36m"),
  905. `Should re-apply cyan before text after code: ${precedingChunk}`,
  906. );
  907. });
  908. it("should preserve heading styling after inline code for h1", () => {
  909. const markdown = new Markdown("# Title with `code` inside", 0, 0, defaultMarkdownTheme);
  910. const lines = markdown.render(80);
  911. const joinedOutput = lines.join("\n");
  912. const afterCodeIndex = joinedOutput.indexOf("inside");
  913. assert.ok(afterCodeIndex > 0, "Should contain text after inline code");
  914. const precedingChunk = joinedOutput.slice(Math.max(0, afterCodeIndex - 40), afterCodeIndex);
  915. // H1 uses heading + bold + underline
  916. assert.ok(precedingChunk.includes("\x1b[1m"), `Should re-apply bold for h1: ${precedingChunk}`);
  917. assert.ok(precedingChunk.includes("\x1b[36m"), `Should re-apply cyan for h1: ${precedingChunk}`);
  918. assert.ok(precedingChunk.includes("\x1b[4m"), `Should re-apply underline for h1: ${precedingChunk}`);
  919. });
  920. it("should not leak h1 underline into padding when inline code is the last token", async () => {
  921. const markdown = new Markdown("# Important distinction from `open()`", 0, 0, defaultMarkdownTheme);
  922. const terminal = new VirtualTerminal(80, 4);
  923. const tui = new TUI(terminal);
  924. tui.addChild(markdown);
  925. tui.start();
  926. await terminal.waitForRender();
  927. const renderedLine = markdown.render(80)[0];
  928. assert.ok(renderedLine, "Should render heading line");
  929. const contentWidth = renderedLine.replace(/\x1b\[[0-9;]*m/g, "").trimEnd().length;
  930. assert.ok(contentWidth > 0, "Should have visible heading content");
  931. for (let col = contentWidth; col < 80; col++) {
  932. assert.strictEqual(getCellUnderline(terminal, 0, col), 0, `Expected no underline in padding at col ${col}`);
  933. }
  934. tui.stop();
  935. });
  936. it("should preserve heading styling after bold text", () => {
  937. const markdown = new Markdown("## Heading with **bold** and more", 0, 0, defaultMarkdownTheme);
  938. const lines = markdown.render(80);
  939. const joinedOutput = lines.join("\n");
  940. const afterBoldIndex = joinedOutput.indexOf("and more");
  941. assert.ok(afterBoldIndex > 0, "Should contain text after bold");
  942. const precedingChunk = joinedOutput.slice(Math.max(0, afterBoldIndex - 40), afterBoldIndex);
  943. assert.ok(precedingChunk.includes("\x1b[1m"), `Should re-apply bold for h2: ${precedingChunk}`);
  944. assert.ok(precedingChunk.includes("\x1b[36m"), `Should re-apply cyan for h2: ${precedingChunk}`);
  945. });
  946. });
  947. describe("Strikethrough syntax", () => {
  948. it("should render ~~text~~ as strikethrough", () => {
  949. const markdown = new Markdown("Use ~~strikethrough~~ here", 0, 0, defaultMarkdownTheme);
  950. const lines = markdown.render(80);
  951. const joinedOutput = lines.join("\n");
  952. const joinedPlain = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "")).join(" ");
  953. assert.ok(joinedOutput.includes("\x1b[9m"), "Should apply strikethrough styling");
  954. assert.ok(joinedPlain.includes("strikethrough"), "Should include struck text content");
  955. assert.ok(!joinedPlain.includes("~~strikethrough~~"), "Should not render delimiters as text");
  956. });
  957. it("should keep ~text~ as plain text", () => {
  958. const markdown = new Markdown("Use ~strikethrough~ literally", 0, 0, defaultMarkdownTheme);
  959. const lines = markdown.render(80);
  960. const joinedOutput = lines.join("\n");
  961. const joinedPlain = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, "")).join(" ");
  962. assert.ok(joinedPlain.includes("~strikethrough~"), "Single-tilde delimiters should remain visible");
  963. assert.ok(!joinedOutput.includes("\x1b[9m"), "Single-tilde text should not use strikethrough styling");
  964. });
  965. });
  966. describe("Links", () => {
  967. afterEach(() => {
  968. resetCapabilitiesCache();
  969. });
  970. it("should not duplicate URL for autolinked emails", () => {
  971. // Hyperlinks capability does not affect the mailto: display check.
  972. setCapabilities({ images: null, trueColor: false, hyperlinks: false });
  973. const markdown = new Markdown("Contact user@example.com for help", 0, 0, defaultMarkdownTheme);
  974. const lines = markdown.render(80);
  975. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  976. const joinedPlain = plainLines.join(" ");
  977. // Should contain the email once, not duplicated with mailto:
  978. assert.ok(joinedPlain.includes("user@example.com"), "Should contain email");
  979. assert.ok(!joinedPlain.includes("mailto:"), "Should not show mailto: prefix for autolinked emails");
  980. });
  981. it("should not duplicate URL for bare URLs", () => {
  982. setCapabilities({ images: null, trueColor: false, hyperlinks: false });
  983. const markdown = new Markdown("Visit https://example.com for more", 0, 0, defaultMarkdownTheme);
  984. const lines = markdown.render(80);
  985. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  986. const joinedPlain = plainLines.join(" ");
  987. // URL should appear only once
  988. const urlCount = (joinedPlain.match(/https:\/\/example\.com/g) || []).length;
  989. assert.strictEqual(urlCount, 1, "URL should appear exactly once");
  990. });
  991. it("should show URL in parentheses when hyperlinks are not supported", () => {
  992. setCapabilities({ images: null, trueColor: false, hyperlinks: false });
  993. const markdown = new Markdown("[click here](https://example.com)", 0, 0, defaultMarkdownTheme);
  994. const lines = markdown.render(80);
  995. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  996. const joinedPlain = plainLines.join(" ");
  997. assert.ok(joinedPlain.includes("click here"), "Should contain link text");
  998. assert.ok(joinedPlain.includes("(https://example.com)"), "Should show URL in parentheses");
  999. });
  1000. it("should show mailto URL in parentheses when hyperlinks are not supported", () => {
  1001. setCapabilities({ images: null, trueColor: false, hyperlinks: false });
  1002. const markdown = new Markdown("[Email me](mailto:test@example.com)", 0, 0, defaultMarkdownTheme);
  1003. const lines = markdown.render(80);
  1004. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  1005. const joinedPlain = plainLines.join(" ");
  1006. assert.ok(joinedPlain.includes("Email me"), "Should contain link text");
  1007. assert.ok(joinedPlain.includes("(mailto:test@example.com)"), "Should show mailto URL in parentheses");
  1008. });
  1009. it("should emit OSC 8 hyperlink sequence when terminal supports hyperlinks", () => {
  1010. setCapabilities({ images: null, trueColor: false, hyperlinks: true });
  1011. const markdown = new Markdown("[click here](https://example.com)", 0, 0, defaultMarkdownTheme);
  1012. const lines = markdown.render(80);
  1013. const joined = lines.join("");
  1014. // OSC 8 open: ESC ] 8 ; ; <url> ESC \
  1015. assert.ok(joined.includes("\x1b]8;;https://example.com\x1b\\"), "Should contain OSC 8 open sequence");
  1016. // OSC 8 close: ESC ] 8 ; ; ESC \
  1017. assert.ok(joined.includes("\x1b]8;;\x1b\\"), "Should contain OSC 8 close sequence");
  1018. // Visible text is present
  1019. const plainLines = lines.map((line) => line.replace(/\x1b[^a-zA-Z]*[a-zA-Z]|\x1b\].*?\x1b\\/g, ""));
  1020. assert.ok(plainLines.join("").includes("click here"), "Should contain link text");
  1021. // URL is NOT printed inline as plain text
  1022. const rawPlain = lines.map((line) =>
  1023. line.replace(/\x1b\]8;;[^\x1b]*\x1b\\/g, "").replace(/\x1b\[[0-9;]*m/g, ""),
  1024. );
  1025. assert.ok(!rawPlain.join("").includes("(https://example.com)"), "URL should not appear inline in parentheses");
  1026. });
  1027. it("should use OSC 8 for mailto links when terminal supports hyperlinks", () => {
  1028. setCapabilities({ images: null, trueColor: false, hyperlinks: true });
  1029. const markdown = new Markdown("[Email me](mailto:test@example.com)", 0, 0, defaultMarkdownTheme);
  1030. const lines = markdown.render(80);
  1031. const joined = lines.join("");
  1032. assert.ok(
  1033. joined.includes("\x1b]8;;mailto:test@example.com\x1b\\"),
  1034. "Should contain OSC 8 open with mailto URL",
  1035. );
  1036. assert.ok(joined.includes("\x1b]8;;\x1b\\"), "Should contain OSC 8 close sequence");
  1037. });
  1038. it("should use OSC 8 for bare URLs when terminal supports hyperlinks", () => {
  1039. setCapabilities({ images: null, trueColor: false, hyperlinks: true });
  1040. const markdown = new Markdown("Visit https://example.com for more", 0, 0, defaultMarkdownTheme);
  1041. const lines = markdown.render(80);
  1042. const joined = lines.join("");
  1043. assert.ok(joined.includes("\x1b]8;;https://example.com\x1b\\"), "Should contain OSC 8 hyperlink");
  1044. // URL should not also appear as raw parenthetical text
  1045. const rawPlain = lines.map((line) =>
  1046. line.replace(/\x1b\]8;;[^\x1b]*\x1b\\/g, "").replace(/\x1b\[[0-9;]*m/g, ""),
  1047. );
  1048. assert.ok(!rawPlain.join("").includes("(https://example.com)"), "URL should not appear twice");
  1049. });
  1050. });
  1051. describe("HTML-like tags in text", () => {
  1052. it("should render content with HTML-like tags as text", () => {
  1053. // When the model emits something like <thinking>content</thinking> in regular text,
  1054. // marked might treat it as HTML and hide the content
  1055. const markdown = new Markdown(
  1056. "This is text with <thinking>hidden content</thinking> that should be visible",
  1057. 0,
  1058. 0,
  1059. defaultMarkdownTheme,
  1060. );
  1061. const lines = markdown.render(80);
  1062. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  1063. const joinedPlain = plainLines.join(" ");
  1064. // The content inside the tags should be visible
  1065. assert.ok(
  1066. joinedPlain.includes("hidden content") || joinedPlain.includes("<thinking>"),
  1067. "Should render HTML-like tags or their content as text, not hide them",
  1068. );
  1069. });
  1070. it("should render HTML tags in code blocks correctly", () => {
  1071. const markdown = new Markdown("```html\n<div>Some HTML</div>\n```", 0, 0, defaultMarkdownTheme);
  1072. const lines = markdown.render(80);
  1073. const plainLines = lines.map((line) => line.replace(/\x1b\[[0-9;]*m/g, ""));
  1074. const joinedPlain = plainLines.join("\n");
  1075. // HTML in code blocks should be visible
  1076. assert.ok(
  1077. joinedPlain.includes("<div>") && joinedPlain.includes("</div>"),
  1078. "Should render HTML in code blocks",
  1079. );
  1080. });
  1081. });
  1082. });