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 linting
pull/13/head
Guillaume Martigny 2018-08-23 17:29:32 +02:00 zatwierdzone przez Amio /
rodzic 79cfe87799
commit da5795ac13
2 zmienionych plików z 13 dodań i 3 usunięć

Wyświetl plik

@ -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
}

Wyświetl plik

@ -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()