Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: fix awkward snippet indention in docs #5367

Merged
merged 1 commit into from
Mar 21, 2024
Merged
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
28 changes: 23 additions & 5 deletions docs/src/preprocess/include_code.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ function processHighlighting(codeSnippet, identifier) {
const regex4 = /this-will-error:([a-zA-Z0-9-._:]+)/;
const replacement4 = "this-will-error";

let result = "";
let mutated = false;

const processLine = (line, regex, replacement) => {
Expand All @@ -46,16 +45,37 @@ function processHighlighting(codeSnippet, identifier) {
return line.trim() == "//" || line.trim() == "#" ? "" : line;
};

const countLeadingSpaces = (line) => {
const match = line.match(/^ */);
return match ? match[0].length : 0;
};
let indention = 200;
let resultLines = [];

for (let line of lines) {
mutated = false;
line = processLine(line, regex1, replacement1);
line = processLine(line, regex2, replacement2);
line = processLine(line, regex3, replacement3);
line = processLine(line, regex4, replacement4);
result += line === "" && mutated ? "" : line + "\n";

if (!(line === "" && mutated)) {
resultLines.push(line);

const leadingSpaces = countLeadingSpaces(line);
if (line.length > 0 && leadingSpaces < indention) {
indention = leadingSpaces;
}
}
}

return result.trim();
let result = "";
for (let line of resultLines) {
result +=
(line.length > indention ? line.substring(indention) : line).trimEnd() +
"\n";
}
return result.trimEnd();
}

/**
Expand All @@ -70,7 +90,6 @@ function processHighlighting(codeSnippet, identifier) {
*/
function extractCodeSnippet(filePath, identifier) {
let fileContent = fs.readFileSync(filePath, "utf-8");
let lineRemovalCount = 0;
let linesToRemove = [];

const startRegex = /(?:\/\/|#)\s+docs:start:([a-zA-Z0-9-._:]+)/g; // `g` will iterate through the regex.exec loop
Expand All @@ -96,7 +115,6 @@ function extractCodeSnippet(filePath, identifier) {
let line = lines[i];
if (line.trim() == match[0].trim()) {
linesToRemove.push(i + 1); // lines are indexed from 1
++lineRemovalCount;
}
}
} else {
Expand Down
Loading