Skip to content

Commit 38b074d

Browse files
committed
fix(ui-truncate-text): parse percentage and non-numeric lineHeight in truncation calc
The v2 truncator treated the lineHeight option as a unitless number and fell back to 1.2 via `options.lineHeight || 1.2`. Percentage values (e.g. "150%") and other string forms were not handled, so the height budget used for truncation could be wrong. Accept lineHeight as a string and normalize it: percent values are converted to a unitless multiplier ("150%" -> 1.5), numeric strings are parsed as-is, and unparsable input falls back to 1.2. A private options type keeps the internal numeric representation.
1 parent bf18f72 commit 38b074d

1 file changed

Lines changed: 17 additions & 4 deletions

File tree

  • packages/ui-truncate-text/src/TruncateText/v2/utils

packages/ui-truncate-text/src/TruncateText/v2/utils/truncate.ts

Lines changed: 17 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,10 @@ import { TruncateTextCommonProps } from '../props.js'
3939

4040
export type TruncatorOptions = {
4141
parent?: Node
42+
lineHeight?: string
43+
} & TruncateTextCommonProps
44+
45+
type PrivateTruncatorOptions = {
4246
lineHeight?: number
4347
} & TruncateTextCommonProps
4448

@@ -74,7 +78,7 @@ function truncate(element: Element, options?: TruncatorOptions) {
7478
}
7579

7680
class Truncator {
77-
private _options: Required<Omit<TruncatorOptions, 'parent'>> &
81+
private _options: Required<PrivateTruncatorOptions> &
7882
Pick<TruncatorOptions, 'parent'>
7983
private _stage!: Element
8084
private _parent?: Node
@@ -89,14 +93,23 @@ class Truncator {
8993
const parentElement = element?.parentElement
9094
? element?.parentElement
9195
: undefined
96+
97+
// if a percent, like 100% or 150%, it should be converted to 1 and 1.5 respectively, if a number, we assume a proper lineheight number and if not parsable, it will default to 1.2
98+
const lineHeight =
99+
options.lineHeight?.slice(-1) === '%'
100+
? Number(options.lineHeight?.slice(0, -1)) / 100
101+
: isNaN(Number(options.lineHeight))
102+
? 1.2
103+
: Number(options.lineHeight)
104+
92105
this._options = {
93106
parent: options.parent || parentElement,
94107
maxLines: options.maxLines || 1,
95108
position: options.position || 'end',
96109
truncate: options.truncate || 'character',
97110
ellipsis: options.ellipsis || '\u2026',
98111
ignore: options.ignore || [' ', '.', ','],
99-
lineHeight: options.lineHeight || 1.2,
112+
lineHeight,
100113
shouldTruncateWhenInvisible: !!options.shouldTruncateWhenInvisible
101114
}
102115

@@ -192,8 +205,8 @@ class Truncator {
192205
textContent.match(/.*?[\.\s\/]+?/g)!
193206
: ['']
194207
: shouldTruncate
195-
? node.textContent!.split('')
196-
: []
208+
? node.textContent!.split('')
209+
: []
197210
})
198211
}
199212
})

0 commit comments

Comments
 (0)