computeFullTextSizeForWidth method

Size computeFullTextSizeForWidth(
  1. double maxWidth
)

Implementation

Size computeFullTextSizeForWidth(double maxWidth) {
  // Reuse span building to keep style consistent with actual painting.
  final span = _buildTextSpan();
  // Configure strut and text height behavior to honor CSS line-height.
  StrutStyle? strut;
  final lh = renderStyle.lineHeight;
  if (lh.type != CSSLengthType.NORMAL) {
    final double fs = renderStyle.fontSize.computedValue;
    if (fs.isFinite && fs > 0) {
      final double scaledFs = renderStyle.textScaler.scale(fs);
      final double multiple = lh.computedValue / fs;
      if (multiple.isFinite && multiple > 0) {
        final FontWeight weight = (renderStyle.boldText && renderStyle.fontWeight.index < FontWeight.w700.index)
            ? FontWeight.w700
            : renderStyle.fontWeight;
        strut = StrutStyle(
          fontSize: scaledFs,
          height: multiple,
          fontFamilyFallback: renderStyle.fontFamily,
          fontStyle: renderStyle.fontStyle,
          fontWeight: weight,
          // Minimum line-box height like CSS; allow expansion if content larger.
          forceStrutHeight: false,
        );
      }
    }
  }
  const TextHeightBehavior thb = TextHeightBehavior(
    applyHeightToFirstAscent: true,
    applyHeightToLastDescent: true,
    leadingDistribution: TextLeadingDistribution.even,
  );

  // Compute effective maxLines consistent with layout.
  final bool nowrap = renderStyle.whiteSpace == WhiteSpace.nowrap;
  final bool ellipsis = renderStyle.effectiveTextOverflow == TextOverflow.ellipsis;
  final int? effectiveMaxLines = renderStyle.lineClamp ?? (nowrap && ellipsis ? 1 : null);

  final tp = TextPainter(
    text: span,
    textAlign: renderStyle.textAlign,
    textDirection: renderStyle.direction,
    textScaler: renderStyle.textScaler,
    ellipsis: ellipsis ? '…' : null,
    maxLines: effectiveMaxLines, // honor line-clamp or nowrap+ellipsis
    strutStyle: strut,
    textHeightBehavior: thb,
  );
  tp.layout(minWidth: 0, maxWidth: maxWidth.isFinite ? maxWidth : double.infinity);
  return Size(tp.width, tp.height);
}