From 5c1c2d626ffed786d00c79aadef26fa5718ca43d Mon Sep 17 00:00:00 2001 From: chezsmithy Date: Sun, 11 May 2025 21:46:25 -0700 Subject: [PATCH] fix: :bug: fixing issues with creating markdown files --- .../streamTransforms/lineStream.test.ts | 82 +++++++++++++- .../filtering/streamTransforms/lineStream.ts | 56 +++++----- .../utils/patchNestedMarkdown.test.ts | 105 ++++++++++++++++++ .../utils/patchNestedMarkdown.ts | 54 +++++---- 4 files changed, 250 insertions(+), 47 deletions(-) create mode 100644 gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts index 5cb05d2c3..5bb59c660 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -2,6 +2,7 @@ import { jest } from "@jest/globals"; import * as lineStream from "./lineStream"; +// eslint-disable-next-line max-lines-per-function describe("lineStream", () => { let mockFullStop: jest.Mock; @@ -204,6 +205,33 @@ describe("lineStream", () => { }); describe("filterCodeBlockLines", () => { + it("should handle unfenced code", async () => { + const linesGenerator = await getLineGenerator(["const x = 5;"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should handle unfenced code with a code block", async () => { + const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]); + }); + + it("should handle unfenced code with two code blocks", async () => { + const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]); + }); + it("should remove lines before the first valid line", async () => { const linesGenerator = await getLineGenerator(["```ts", "const x = 5;"]); @@ -213,7 +241,59 @@ describe("lineStream", () => { expect(filteredLines).toEqual(["const x = 5;"]); }); - it.todo("Need some sample inputs to properly test this"); + it("should remove outer blocks", async () => { + const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;"]); + }); + + it("should leave inner blocks intact", async () => { + const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]); + }); + + it("should handle included inner ticks", async () => { + const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]); + }); + + it("should leave single inner blocks intact but not return trailing text", async () => { + const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]); + }); + + it("should leave double inner blocks intact but not return trailing text", async () => { + const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]); + }); + + it("should leave inner blocks intact but not return trailing or leading text", async () => { + const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]); + + const result = lineStream.filterCodeBlockLines(linesGenerator); + const filteredLines = await getFilteredLines(result); + + expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]); + }); }); describe("filterEnglishLinesAtStart", () => { diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index edad1febc..ef4648ffb 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -55,8 +55,8 @@ function shouldChangeLineAndStop(line: string): string | undefined { return line; } - if (line.includes(CODE_START_BLOCK)) { - return line.split(CODE_START_BLOCK)[0].trimEnd(); + if (line.includes(CODE_STOP_BLOCK)) { + return line.split(CODE_STOP_BLOCK)[0].trimEnd(); } return undefined; @@ -71,9 +71,9 @@ function isUselessLine(line: string): boolean { return hasUselessLine || trimmed.startsWith("// end"); } -export const USELESS_LINES = ["", "```"]; +export const USELESS_LINES = [""]; export const CODE_KEYWORDS_ENDING_IN_SEMICOLON = ["def"]; -export const CODE_START_BLOCK = "[/CODE]"; +export const CODE_STOP_BLOCK = "[/CODE]"; export const BRACKET_ENDING_CHARS = [")", "]", "}", ";"]; export const PREFIXES_TO_SKIP = [""]; export const LINES_TO_STOP_AT = ["# End of file.", " 0) { + // Inside a block + const changedEndLine = shouldChangeLineAndStop(line); + if (typeof changedEndLine === "string") { + // Ending a block with just backticks (```) or STOP + nestCount--; + if (nestCount === 0) { + return; + } else { + yield line; + } + } else if (line.startsWith("```")) { + // Going into a nested codeblock + nestCount++; + yield line; + } else { + yield line; + } } } } diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts new file mode 100644 index 000000000..982517bf5 --- /dev/null +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.test.ts @@ -0,0 +1,105 @@ +import { patchNestedMarkdown } from './patchNestedMarkdown'; + +describe('patchNestedMarkdown', () => { + it('should return unchanged content when no markdown codeblocks are present', () => { + const source = 'Regular text\n```javascript\nconsole.log("hello");\n```'; + expect(patchNestedMarkdown(source)).toBe(source); + }); + + it('should replace backticks with tildes for markdown codeblocks', () => { + const source = '```markdown\n# Header\nSome text\n```'; + const expected = '~~~markdown\n# Header\nSome text\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle nested codeblocks within markdown blocks', () => { + const source = '```markdown\n# Example\n```js\nconsole.log("nested");\n```\n```'; + const expected = '~~~markdown\n# Example\n```js\nconsole.log("nested");\n```\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle .md file extension', () => { + const source = '```test.md\nContent\n```'; + const expected = '~~~test.md\nContent\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle multiple levels of nesting', () => { + const source = '```markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n```'; + const expected = '~~~markdown\n# Doc\n```js\nlet x = "```nested```";\n```\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle blocks that start with md', () => { + const source = '```md\n# Header\nSome text\n```'; + const expected = '~~~md\n# Header\nSome text\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle blocks with language specifier followed by md', () => { + const source = '```lang md\n# Header\nSome text\n```'; + const expected = '~~~lang md\n# Header\nSome text\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle blocks with language specifier followed by markdown', () => { + const source = '```lang markdown\n# Header\nSome text\n```'; + const expected = '~~~lang markdown\n# Header\nSome text\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should not replace backticks for non-markdown file extensions', () => { + const source = '```test.js\nContent\n```'; + expect(patchNestedMarkdown(source)).toBe(source); + }); + + it('should check the file extension branch when extension is not md/markdown/gfm', () => { + // This tests the extension check branch with an unrecognized extension + const source = '```test.txt\nContent with md keyword\n```'; + expect(patchNestedMarkdown(source)).toBe(source); + }); + + it('should handle empty file name in code block header', () => { + // This covers the branch where file is empty or undefined + const source = '``` \nSome content\n```'; + expect(patchNestedMarkdown(source)).toBe(source); + }); + + it('should handle file names with no extension', () => { + // This covers the branch where ext might be undefined + const source = '```filename\nContent\n```'; + expect(patchNestedMarkdown(source)).toBe(source); + }); + + it('should correctly identify .markdown extension', () => { + // This specifically tests the ext === "markdown" condition in the extension check + const source = '```example.markdown\n# Some markdown content\n```'; + const expected = '~~~example.markdown\n# Some markdown content\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + // GitHub-specific tests + it('should handle gfm language identifier', () => { + const source = '```gfm\n# Header\nSome text\n```'; + const expected = '~~~gfm\n# Header\nSome text\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle github-markdown language identifier', () => { + const source = '```github-markdown\n# Header\nSome text\n```'; + const expected = '~~~github-markdown\n# Header\nSome text\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle language specifier followed by gfm', () => { + const source = '```lang gfm\n# Header\nSome text\n```'; + const expected = '~~~lang gfm\n# Header\nSome text\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); + + it('should handle .gfm file extension', () => { + const source = '```example.gfm\n# Some GitHub markdown content\n```'; + const expected = '~~~example.gfm\n# Some GitHub markdown content\n~~~'; + expect(patchNestedMarkdown(source)).toBe(expected); + }); +}); diff --git a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts index 10d5af1b2..b4a54a58b 100644 --- a/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts +++ b/gui/src/components/StyledMarkdownPreview/utils/patchNestedMarkdown.ts @@ -1,47 +1,61 @@ /* This is a patch for outputing markdown code that contains codeblocks - It notices markdown blocks, keeps track of when that specific block is closed, + It notices markdown blocks (including GitHub-specific variants), + keeps track of when that specific block is closed, and uses ~~~ instead of ``` for that block Note, this was benchmarked at sub-millisecond - - // TODO support github-specific markdown as well, edge case */ export const patchNestedMarkdown = (source: string): string => { - if (!source.match(/```(\w+\.(md|markdown))/)) return source; // For performance - // const start = Date.now(); + // Early return if no markdown codeblock pattern is found (including GitHub variants) + if (!source.match(/```(\w*|.*)(md|markdown|gfm|github-markdown)/)) return source; + let nestCount = 0; const lines = source.split("\n"); const trimmedLines = lines.map((l) => l.trim()); + for (let i = 0; i < trimmedLines.length; i++) { const line = trimmedLines[i]; - if (nestCount) { + + if (nestCount > 0) { + // Inside a markdown block if (line.match(/^`+$/)) { - // Ending a block - if (nestCount === 1) lines[i] = "~~~"; // End of markdown block + // Ending a block with just backticks (```) nestCount--; + if (nestCount === 0) { + lines[i] = "~~~"; // End of markdown block + } } else if (line.startsWith("```")) { // Going into a nested codeblock nestCount++; } } else { - // Enter the markdown block, start tracking nesting + // Not inside a markdown block yet if (line.startsWith("```")) { const header = line.replaceAll("`", ""); - const file = header.split(" ")[0]; - - if (file) { - const ext = file.split(".").at(-1); - if (ext === "md" || ext === "markdown") { - nestCount = 1; - lines[i] = lines[i].replaceAll("`", "~"); // Replace backticks with tildes - } + + // Check if this is a markdown codeblock using a consolidated approach (including GitHub-specific variants) + const isMarkdown = + header === "md" || + header === "markdown" || + header === "gfm" || + header === "github-markdown" || + header.includes(" md") || + header.includes(" markdown") || + header.includes(" gfm") || + header.includes(" github-markdown") || + (header.split(" ")[0]?.split(".").pop() === "md") || + (header.split(" ")[0]?.split(".").pop() === "markdown") || + (header.split(" ")[0]?.split(".").pop() === "gfm"); + + if (isMarkdown) { + nestCount = 1; + lines[i] = lines[i].replaceAll("`", "~"); } } } } - const out = lines.join("\n"); - // console.log(`patched in ${Date.now() - start}ms`); - return out; + + return lines.join("\n"); };