breakIntoLines method

List<List<int>> breakIntoLines(
  1. List<LatexNode> nodes,
  2. List<double> widths
)

Breaks nodes into lines based on calculated penalties and widths.

Implementation

List<List<int>> breakIntoLines(List<LatexNode> nodes, List<double> widths) {
  if (nodes.isEmpty) return [[]];

  double totalWidth = 0.0;
  for (final w in widths) {
    totalWidth += w;
  }

  if (totalWidth <= maxWidth) {
    return [List.generate(nodes.length, (i) => i)];
  }

  final state = _BreakState();
  int depth = 0;

  for (int i = 0; i < nodes.length; i++) {
    final node = nodes[i];
    final width = widths[i];

    depth += _getDepthDelta(node, entering: true);

    if (state.currentWidth + width > maxWidth &&
        state.currentPos > state.lineStart) {
      if (!state.commitBreak()) {
        state.forceBreak();
      }
    }

    final widthBeforeThis = state.currentWidth;
    state.currentWidth += width;
    state.currentPos = i + 1;

    final penalty = _calculatePenalty(node, depth);
    if (penalty < noBreak) {
      state.recordBreakCandidate(i, penalty, widthBeforeThis);
    }

    depth += _getDepthDelta(node, entering: false);
  }

  return state.finalizeRanges();
}