From 0a5bfcd14da6f7d49cce199ee649b83c114350ec Mon Sep 17 00:00:00 2001 From: BaskarMitrah Date: Tue, 30 Dec 2025 20:13:23 +0530 Subject: [PATCH] added class code --- src/steps/to-hast.ts | 27 ++++++++++++++++++++++----- 1 file changed, 22 insertions(+), 5 deletions(-) diff --git a/src/steps/to-hast.ts b/src/steps/to-hast.ts index c7b006f..2aa206a 100644 --- a/src/steps/to-hast.ts +++ b/src/steps/to-hast.ts @@ -20,18 +20,35 @@ import { toHast as mdast2hast, defaultHandlers, State } from 'mdast-util-to-hast import { raw } from 'hast-util-raw'; import { mdast2hastGridTablesHandler, TYPE_TABLE } from '@adobe/mdast-util-gridtables'; +// Parses js{try id=foo} into ['language-js', 'try', 'id=foo'] +function getCodeClasses(lang: string | null, meta: string | null): string[] { + const [, language, extra] = lang?.match(/^([^{]*)(.*)$/) || []; + const fullMeta = ((extra || '') + ' ' + (meta || '')).replace(/[{}]/g, '').trim(); + return [...(language ? [`language-${language}`] : []), ...fullMeta.split(/\s+/).filter(Boolean)]; +} + export default function toHast(ctx: Helix.UniversalContext) { const { content } = ctx.attributes; content.hast = mdast2hast(content.mdast, { handlers: { ...defaultHandlers, - section: (state: State, node: any) => { - const n = { ...node }; - const children = state.all(n); + section: (state: State, node: any) => ({ + type: 'element', + tagName: 'div', + children: state.all({ ...node }), + }), + code: (_state: State, node: any) => { + const classes = getCodeClasses(node.lang, node.meta); return { type: 'element', - tagName: 'div', - children, + tagName: 'pre', + properties: {}, + children: [{ + type: 'element', + tagName: 'code', + properties: classes.length ? { className: classes } : {}, + children: [{ type: 'text', value: node.value || '' }], + }], }; }, [TYPE_TABLE]: mdast2hastGridTablesHandler(),