Skip to content
Open
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
24 changes: 24 additions & 0 deletions src/lib/utils/code.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { describe, expect, test } from 'vitest';
import { getCodeHtml, type Language } from './code';

describe('getCodeHtml', () => {
test('normalizes code fence language before highlighting', () => {
const html = getCodeHtml({
content: 'using Appwrite;',
language: 'csharp ' as Language
});

expect(html).toContain('language-csharp');
expect(html).not.toContain('language-csharp ');
expect(html).toContain('hljs-keyword');
});

test('uses the fallback language class when language is omitted', () => {
const html = getCodeHtml({
content: 'echo appwrite'
});

expect(html).toContain('language-sh');
expect(html).not.toContain('language-undefined');
});
});
Comment thread
greptile-apps[bot] marked this conversation as resolved.
7 changes: 5 additions & 2 deletions src/lib/utils/code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,8 @@ hljs.registerAliases(['hcl', 'terraform', 'tf'], { languageName: 'ini' });

export type Language = keyof typeof languages | Platform;

const normalizeLanguage = (language?: Language) => language?.trim() as Language | undefined;

type Args = {
content: string;
language?: Language;
Expand All @@ -124,7 +126,8 @@ type Args = {

export const getCodeHtml = (args: Args) => {
const { content, language, withLineNumbers } = args;
const res = hljs.highlight(content, { language: language ?? 'sh' }).value;
const highlightedLanguage = normalizeLanguage(language) ?? 'sh';
const res = hljs.highlight(content, { language: highlightedLanguage }).value;
const lines = res.split(/\n/g);

while (lines.length > 0 && lines[lines.length - 1] === '') {
Expand All @@ -136,7 +139,7 @@ export const getCodeHtml = (args: Args) => {
return carry;
}, '');

return `<pre class="web-code-pre"><code class="web-code web-code-body language-${language} ${
return `<pre class="web-code-pre"><code class="web-code web-code-body language-${highlightedLanguage} ${
withLineNumbers ? 'line-numbers' : ''
}">${final}</code></pre>`;
};
Expand Down