kopia lustrzana https://github.com/badgen/badgen
fix: Accented characters are treated as unknown and fallback to @ width (#14)
* fix: Accented characters are treated as unknown and fallback to @ width * chore: Improve tests * chore: Fix lintingpull/13/head
rodzic
79cfe87799
commit
da5795ac13
|
@ -5,16 +5,19 @@ const SCALE = 10 // Prevent results like 60.599999999999994
|
|||
const calcWidth = (charWidthTable) => {
|
||||
const widthTable = charWidthTable.map(w => Math.round(w * SCALE))
|
||||
widthTable[64] = widthTable[64] + 6 // Slightly increase width of "@" by 0.6px
|
||||
const fallbackWidth = widthTable[64] // Width as "@" for overflows
|
||||
|
||||
return (text, astral) => {
|
||||
if (astral) text = [...text]
|
||||
|
||||
let total = 0
|
||||
let code = 0
|
||||
let i = text.length
|
||||
let char = ''
|
||||
while (i--) {
|
||||
code = text[i].charCodeAt()
|
||||
total += widthTable[code < 127 ? code : 64] // Width as "@" for overflows
|
||||
char = text[i]
|
||||
total += widthTable[char.charCodeAt()] ||
|
||||
widthTable[char.normalize('NFD').charCodeAt()] ||
|
||||
fallbackWidth
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
|
|
@ -18,6 +18,13 @@ tap.test('calc width for unicode', t => {
|
|||
t.end()
|
||||
})
|
||||
|
||||
tap.test('calc width for accented characters', t => {
|
||||
t.ok(calcWidth('i') === calcWidth('ï'), 'i and ï have the same width')
|
||||
t.ok(calcWidth('e') === calcWidth('é'), 'e and é have the same width')
|
||||
t.ok(calcWidth('s') === calcWidth('ṣ'), 's and ṣ have the same width')
|
||||
t.end()
|
||||
})
|
||||
|
||||
tap.test('calc width for emojis', t => {
|
||||
t.matchSnapshot(calcWidth('💩🤱🦄', true), 'result is correct')
|
||||
t.end()
|
||||
|
|
Ładowanie…
Reference in New Issue