(text: string, targetWidth: number)
| 1238 | |
| 1239 | // Convert display width to string index |
| 1240 | public displayWidthToStringIndex(text: string, targetWidth: number): number { |
| 1241 | if (targetWidth <= 0) return 0 |
| 1242 | if (!text) return 0 |
| 1243 | |
| 1244 | // If the text matches our text, use the precomputed graphemes |
| 1245 | if (text === this.text) { |
| 1246 | return this.offsetAtDisplayWidth(targetWidth) |
| 1247 | } |
| 1248 | |
| 1249 | // Otherwise compute on the fly |
| 1250 | let currentWidth = 0 |
| 1251 | let currentOffset = 0 |
| 1252 | |
| 1253 | for (const { segment, index } of getGraphemeSegmenter().segment(text)) { |
| 1254 | const segmentWidth = stringWidth(segment) |
| 1255 | |
| 1256 | if (currentWidth + segmentWidth > targetWidth) { |
| 1257 | break |
| 1258 | } |
| 1259 | |
| 1260 | currentWidth += segmentWidth |
| 1261 | currentOffset = index + segment.length |
| 1262 | } |
| 1263 | |
| 1264 | return currentOffset |
| 1265 | } |
| 1266 | |
| 1267 | /** |
| 1268 | * Find the string offset that corresponds to a target display width. |
no test coverage detected