47 lines
1.4 KiB
TypeScript
47 lines
1.4 KiB
TypeScript
export function fixMdxDataProps(content: string): string {
|
|
let fixedContent = content;
|
|
let dataIndex = fixedContent.indexOf('data={{');
|
|
|
|
while (dataIndex !== -1) {
|
|
let openCount = 0;
|
|
let endIndex = -1;
|
|
const startObj = dataIndex + 6; // index of the first '{' in 'data={{'
|
|
|
|
for (let i = startObj; i < fixedContent.length; i++) {
|
|
if (fixedContent[i] === '{') {
|
|
openCount++;
|
|
} else if (fixedContent[i] === '}') {
|
|
openCount--;
|
|
if (openCount === 0) {
|
|
endIndex = i;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
if (endIndex !== -1) {
|
|
// jsonStr is the content INSIDE the outer curly braces
|
|
const jsonStr = fixedContent.substring(startObj + 1, endIndex);
|
|
const safeJsonStr = jsonStr.replace(/"/g, '"');
|
|
const replacement = `data="{${safeJsonStr}}"`;
|
|
|
|
// We also need to consume the closing `}` of the `data={{`
|
|
const nextCharIndex = endIndex + 1;
|
|
const skipChars =
|
|
nextCharIndex < fixedContent.length && fixedContent[nextCharIndex] === '}' ? 2 : 1;
|
|
|
|
fixedContent =
|
|
fixedContent.substring(0, dataIndex) +
|
|
replacement +
|
|
fixedContent.substring(endIndex + skipChars);
|
|
|
|
dataIndex = fixedContent.indexOf('data={{', dataIndex + replacement.length);
|
|
} else {
|
|
// Malformed braces, prevent infinite loop
|
|
break;
|
|
}
|
|
}
|
|
|
|
return fixedContent;
|
|
}
|