bezoerb / text-metrics

An efficient text measurement set for the browser
MIT License
63 stars 4 forks source link

Calculate width of text filled with only (or mostly) whitespace #10

Open CalvinLeGassick opened 4 years ago

CalvinLeGassick commented 4 years ago

Is there a way to get text-metrics to include every whitespace when computing the width of a string?

With strings that are all whitespace or mostly whitespace, the width that text-metrics produces seems to be computed after stripping out whitespaces. At the least, the width results are smaller than when I just compute the width of the string using canvas.measureText. Here's an example of the mismatch:

https://codesandbox.io/s/text-metrics-whitespaces-mzgh2?file=/src/index.js

Am I just missing some CSS prop I need to pass to text-metrics to get it to understand how I want it to treat whitespaces?

I expected passing in pre or break-spaces to white-space would do this trick but it did not. Is it possible this "if block" should add whitespace to the line string before continue-ing if certain white-space values are present?

https://github.com/bezoerb/text-metrics/blob/140bb54a8ffff7141eae12b10d767d374b4510ce/src/utils.js#L464

Also, I did see this issue but could not find the trim() culprit that was mentioned. The trim in normalizeWhitespace looks like it doesn't trim if white-space: pre is used, so I would think that should be fine.

https://github.com/bezoerb/text-metrics/blob/140bb54a8ffff7141eae12b10d767d374b4510ce/src/utils.js#L279

bezoerb commented 4 years ago

Hey @CalvinLeGassick, thanks for the detailed issue :) It looks like line 464 is causing this unexpected behavior. Good catch! I think maybe this if block could be removed at all as the whitespace already get's normalized in normalizeWhitespace. Do you like to try and create a PR?

thanks

bezoerb commented 3 years ago

@CalvinLeGassick : This should be fixed in v2.0.9

benshabatnoam commented 3 months ago

I'm not sure, but it looks looks like this should be a closed issue, as v2.0.9 contains a fix for it... Anyway, I got to this issue because I'm having this problem with v4.0.1, therefore my question is do you think this issue became a regression in my version? thanks

adamatronix commented 3 months ago

I am also facing this issue. Even in 2.0.9 trailing spaces aren't being calculated propery.