(text: string, targetWidth: number)
| 1213 | |
| 1214 | // Convert display width to string index |
| 1215 | public displayWidthToStringIndex(text: string, targetWidth: number): number { |
| 1216 | if (targetWidth <= 0) return 0 |
| 1217 | if (!text) return 0 |
| 1218 | |
| 1219 | // If the text matches our text, use the precomputed graphemes |
| 1220 | if (text === this.text) { |
| 1221 | return this.offsetAtDisplayWidth(targetWidth) |
| 1222 | } |
| 1223 | |
| 1224 | // Otherwise compute on the fly |
| 1225 | let currentWidth = 0 |
| 1226 | let currentOffset = 0 |
| 1227 | |
| 1228 | for (const { segment, index } of getGraphemeSegmenter().segment(text)) { |
| 1229 | const segmentWidth = stringWidth(segment) |
| 1230 | |
| 1231 | if (currentWidth + segmentWidth > targetWidth) { |
| 1232 | break |
| 1233 | } |
| 1234 | |
| 1235 | currentWidth += segmentWidth |
| 1236 | currentOffset = index + segment.length |
| 1237 | } |
| 1238 | |
| 1239 | return currentOffset |
| 1240 | } |
| 1241 | |
| 1242 | /** |
| 1243 | * Find the string offset that corresponds to a target display width. |
no test coverage detected