Skip to content

Commit

Permalink
refactor(line numbers): optimize calculation for padding of line numb…
Browse files Browse the repository at this point in the history
…ers in code blocks
  • Loading branch information
Li Guanglin committed Oct 15, 2023
1 parent ad1f749 commit 344ff2c
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 5 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ static class LineNumbersDrawer {
private final Paint _paint = new Paint();

private final int _defaultPaddingLeft;
private static final int LINE_NUMBER_PADDING_LEFT = 16;
private static final int LINE_NUMBER_PADDING_LEFT = 20;
private static final int LINE_NUMBER_PADDING_RIGHT = 12;

private final Rect _visibleArea = new Rect();
Expand Down
18 changes: 14 additions & 4 deletions app/thirdparty/assets/prism/plugins/line-numbers/custom.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,25 @@ function enableLineNumbers() {
}

function adjustLineNumbers() {
let preElements = document.querySelectorAll("pre[class*='language-']");
const preElements = document.querySelectorAll("pre[class*='language-']");
let fontWidth = -1;

preElements.forEach((element) => {
let codeElement = element.querySelector("code");
if (codeElement) {
let maxNumber = codeElement.textContent.split("\n").length - 1;
if (maxNumber > 0) {
element.style.paddingLeft = 1.1 + getNumberDigits(maxNumber) * 0.5 + "em";
const maxNumber = codeElement.textContent.split("\n").length - 1;
if (maxNumber == 0) {
return;
}

if (fontWidth == -1) {
const canvasContext = document.createElement("canvas").getContext("2d");
canvasContext.font = window.getComputedStyle(codeElement, null).getPropertyValue("font");
fontWidth = canvasContext.measureText("0").width;
}

const digits = getNumberDigits(maxNumber);
element.style.paddingLeft = 2 * fontWidth + digits * fontWidth - digits + "px";
}
});
}
Expand Down
Binary file modified doc/assets/2023-10-11-line-numbers.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 344ff2c

Please sign in to comment.