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
8 changes: 6 additions & 2 deletions src/app/plugins/markdown/block/rules.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,12 @@ export const CodeBlockRule: BlockMDRule = {
match: (text) => text.match(CODEBLOCK_REG_1),
html: (match) => {
const [, g1, g2] = match;
const classNameAtt = g1 ? ` class="language-${g1}"` : '';
return `<pre data-md="${CODEBLOCK_MD_1}"><code${classNameAtt}>${g2}</code></pre>`;
// use last identifier after dot, e.g. for "example.json" gets us "json" as language code.
const langCode = g1 ? g1.substring(g1.lastIndexOf('.') + 1) : null;
const filename = g1 != langCode ? g1 : null;
const classNameAtt = langCode ? ` class="language-${langCode}"` : '';
const filenameAtt = filename ? ` data-label="${filename}"` : '';
return `<pre data-md="${CODEBLOCK_MD_1}"><code${classNameAtt}${filenameAtt}>${g2}</code></pre>`;
},
};

Expand Down
7 changes: 4 additions & 3 deletions src/app/plugins/react-custom-html-parser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,9 @@ export function CodeBlock({
opts: HTMLReactParserOptions;
}) {
const code = children[0];
const languageClass =
code instanceof Element && code.name === 'code' ? code.attribs.class : undefined;
const attribs = code instanceof Element && code.name === 'code' ? code.attribs : undefined;
const languageClass = attribs?.class;
const customLabel = attribs?.['data-label'];
const language =
languageClass && languageClass.startsWith('language-')
? languageClass.replace('language-', '')
Expand Down Expand Up @@ -262,7 +263,7 @@ export function CodeBlock({
<Header variant="Surface" size="400" className={css.CodeBlockHeader}>
<Box grow="Yes">
<Text size="L400" truncate>
{language ?? 'Code'}
{customLabel ?? language ?? 'Code'}
</Text>
</Box>
<Box shrink="No" gap="200">
Expand Down
2 changes: 1 addition & 1 deletion src/app/utils/sanitize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ const permittedTagToAttributes = {
ul: ['data-md'],
a: ['name', 'target', 'href', 'rel', 'data-md'],
img: ['width', 'height', 'alt', 'title', 'src', 'data-mx-emoticon'],
code: ['class', 'data-md'],
code: ['class', 'data-md', 'data-label'],
strong: ['data-md'],
i: ['data-md'],
em: ['data-md'],
Expand Down