Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Code block language parsing #1362

Merged
merged 2 commits into from
Jan 13, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
[
{
"id": "1",
"type": "codeBlock",
"props": {
"language": "javascript"
},
"content": [
{
"type": "text",
"text": "console.log(\"Should default to JS\")",
"styles": {}
}
],
"children": []
},
{
"id": "2",
"type": "codeBlock",
"props": {
"language": "typescript"
},
"content": [
{
"type": "text",
"text": "console.log(\"Should parse TS from data-language\")",
"styles": {}
}
],
"children": []
},
{
"id": "3",
"type": "codeBlock",
"props": {
"language": "python"
},
"content": [
{
"type": "text",
"text": "print(\"Should parse Python from language- class\")",
"styles": {}
}
],
"children": []
},
{
"id": "4",
"type": "codeBlock",
"props": {
"language": "typescript"
},
"content": [
{
"type": "text",
"text": "console.log(\"Should prioritize TS from data-language over language- class\")",
"styles": {}
}
],
"children": []
}
]
9 changes: 9 additions & 0 deletions packages/core/src/api/parsers/html/parseHTML.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -516,4 +516,13 @@ With Hard Break</p>

await parseHTMLAndCompareSnapshots(html, "parse-google-docs-html");
});

it("Parse codeblocks", async () => {
const html = `<pre><code>console.log("Should default to JS")</code></pre>
<pre><code data-language="typescript">console.log("Should parse TS from data-language")</code></pre>
<pre><code class="language-python">print("Should parse Python from language- class")</code></pre>
<pre><code class="language-ruby" data-language="typescript">console.log("Should prioritize TS from data-language over language- class")</code></pre>`;

await parseHTMLAndCompareSnapshots(html, "parse-codeblocks");
});
});
5 changes: 3 additions & 2 deletions packages/core/src/blocks/CodeBlockContent/CodeBlockContent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,10 @@ const CodeBlockContent = createStronglyTypedTiptapNode({
const languages = classNames
.filter((className) => className.startsWith("language-"))
.map((className) => className.replace("language-", ""));
const [classLanguage] = languages;

language = classLanguage.toLowerCase();
if (languages.length > 0) {
language = languages[0].toLowerCase();
}
}

if (!language) {
Expand Down
Loading