diff --git a/src/lib/utils/code.test.ts b/src/lib/utils/code.test.ts new file mode 100644 index 0000000000..677daa8baa --- /dev/null +++ b/src/lib/utils/code.test.ts @@ -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'); + }); +}); diff --git a/src/lib/utils/code.ts b/src/lib/utils/code.ts index 87503c1066..70558f38cf 100644 --- a/src/lib/utils/code.ts +++ b/src/lib/utils/code.ts @@ -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; @@ -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] === '') { @@ -136,7 +139,7 @@ export const getCodeHtml = (args: Args) => { return carry; }, ''); - return `
${final}`;
};