Skip to content

Commit 3f6e41c

Browse files
chore(badge): resolve coderabbit nitpick by extracting fallback width constants
1 parent a66454e commit 3f6e41c

File tree

1 file changed

+24
-5
lines changed

1 file changed

+24
-5
lines changed

server/api/registry/badge/[type]/[...pkg].get.ts

Lines changed: 24 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -73,31 +73,50 @@ const MEDIUM_CHARS = new Set([
7373
'~',
7474
])
7575

76+
const FALLBACK_WIDTHS = {
77+
default: {
78+
narrow: 3,
79+
medium: 5,
80+
digit: 6,
81+
uppercase: 7,
82+
other: 6,
83+
},
84+
shieldsio: {
85+
narrow: 3,
86+
medium: 5,
87+
digit: 6,
88+
uppercase: 7,
89+
other: 5.5,
90+
},
91+
} as const
92+
7693
function estimateTextWidth(text: string, fallbackFont: 'default' | 'shieldsio'): number {
94+
// Heuristic coefficients tuned to keep fallback rendering close to canvas metrics.
95+
const widths = FALLBACK_WIDTHS[fallbackFont]
7796
let totalWidth = 0
7897

7998
for (const character of text) {
8099
if (NARROW_CHARS.has(character)) {
81-
totalWidth += 3
100+
totalWidth += widths.narrow
82101
continue
83102
}
84103

85104
if (MEDIUM_CHARS.has(character)) {
86-
totalWidth += 5
105+
totalWidth += widths.medium
87106
continue
88107
}
89108

90109
if (/\d/.test(character)) {
91-
totalWidth += 6
110+
totalWidth += widths.digit
92111
continue
93112
}
94113

95114
if (/[A-Z]/.test(character)) {
96-
totalWidth += 7
115+
totalWidth += widths.uppercase
97116
continue
98117
}
99118

100-
totalWidth += fallbackFont === 'shieldsio' ? 5.5 : 6
119+
totalWidth += widths.other
101120
}
102121

103122
return Math.max(1, Math.round(totalWidth))

0 commit comments

Comments
 (0)