Skip to content

Commit

Permalink
Fix some small runtime errors
Browse files Browse the repository at this point in the history
  • Loading branch information
ptgott committed Nov 18, 2024
1 parent 016b991 commit 70c8520
Showing 1 changed file with 14 additions and 10 deletions.
24 changes: 14 additions & 10 deletions server/rehype-hljs-var.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ export const rehypeVarInHLJS = (
// We only visit text nodes inside code snippets
if (
node.type !== "text" ||
!parent ||
!parent.hasOwnProperty("tagName") ||
(parent as Element).tagName !== "code"
) {
Expand Down Expand Up @@ -99,22 +100,25 @@ export const rehypeVarInHLJS = (
continue;
}

let hljsSpanValue;
let textValue;
if ((el.children[i] as Element).tagName == "span") {
hljsSpanValue = (el.children[i].children[0] as Text).value;
textValue = (el.children[i].children[0] as Text).value;
} else {
hljsSpanValue = el.children[i].value;
textValue = el.children[i].value;
}
if (!textValue) {
continue;
}

// This is an hljs span with only the placeholder as its child.
// We don't need the span, so replace it with the original Var.
if (placeholdersToVars[hljsSpanValue]) {
el.children[i] = placeholdersToVars[hljsSpanValue];
if (placeholdersToVars[textValue]) {
el.children[i] = placeholdersToVars[textValue];
continue;
}

const placeholders = Array.from(
hljsSpanValue.matchAll(new RegExp(placeholderPattern, "g"))
textValue.matchAll(new RegExp(placeholderPattern, "g"))
);

// No placeholders to recover, so there's nothing more to do.
Expand All @@ -138,23 +142,23 @@ export const rehypeVarInHLJS = (
});

let valueIdx = 0;
while (valueIdx < hljsSpanValue.length) {
while (valueIdx < textValue.length) {
// The current index is in a placeholder, so add the original Var
// component to newChildren.
if (placeholderIndices.has(valueIdx)) {
const placeholder = valueIdx + placeholderIndices.get(valueIdx);
valueIdx += placeholder.length;
newChildren.push(placeholdersToVars[placeholderValue]);
newChildren.push(placeholdersToVars[placeholder]);
continue;
}
// The current index is outside a placeholder, so assemble a text or
// span node and push that to newChildren.
let textVal = "";
while (
!placeholderIndices.has(valueIdx) &&
valueIdx < hljsSpanValue.length
valueIdx < textValue.length
) {
textVal += hljsSpanValue[valueIdx];
textVal += textValue[valueIdx];
valueIdx++;
}
if (el.children[i].type == "text") {
Expand Down

0 comments on commit 70c8520

Please sign in to comment.