getPreviousGraphemeOffset static method

int getPreviousGraphemeOffset(
  1. String s,
  2. int currentOffset
)

Calculates the previous grapheme cluster offset in a string. Returns the start offset of the grapheme cluster that ends at currentOffset, handling surrogate pairs, CJK variation selectors, combining marks, and ZWJ sequences correctly.

Implementation

static int getPreviousGraphemeOffset(String s, int currentOffset) {
  if (currentOffset <= 0) return 0;
  if (currentOffset > s.length) return s.length;
  // Walk the grapheme clusters and find the one whose end == currentOffset
  int pos = 0;
  for (final grapheme in s.characters) {
    final nextPos = pos + grapheme.length;
    if (nextPos >= currentOffset) {
      return pos;
    }
    pos = nextPos;
  }
  return currentOffset - 1;
}