sourceOffsetAt method

int sourceOffsetAt(
  1. Offset position
)

Maps a table-local cell position to row-major UTF-16 text coordinates.

Implementation

int sourceOffsetAt(Offset position) {
  if (_cells.isEmpty) return 0;
  final columnStarts = _columnStarts();
  final rowStarts = _rowStarts();
  final column = _partAt(
    position.dx,
    columnStarts,
    _columnWidths,
    sizeAdjustment: _cellPaddingX * 2,
  );
  final row = _partAt(position.dy, rowStarts, _rowHeights);
  final cell = _cells[row * _columnWidths.length + column];
  final lineIndex = (position.dy - rowStarts[row] - _cellPaddingY).clamp(
    0,
    cell.layout.lines.length - 1,
  );
  final line = cell.layout.lines[lineIndex];
  final targetCell = math.max(
    0,
    position.dx - columnStarts[column] - _cellPaddingX,
  );
  var paintedCell = 0;
  for (final run in line.runs) {
    var sourceOffset = run.sourceStart;
    for (final grapheme in run.text.characters) {
      final width = terminalCellWidth(grapheme);
      if (targetCell < paintedCell + math.max(1, width)) {
        return cell.sourceBase + sourceOffset;
      }
      paintedCell += width;
      sourceOffset += grapheme.length;
    }
  }
  final lineEnd = line.runs.isEmpty ? 0 : line.runs.last.sourceEnd;
  return cell.sourceBase + lineEnd;
}