parse method

  1. @override
Node? parse(
  1. BlockParser parser
)
override

Parses a table into its three parts:

  • a head row of head cells (<th> cells)
  • a divider of hyphens and pipes (not rendered)
  • many body rows of body cells (<td> cells)

Implementation

@override
Node? parse(BlockParser parser) {
  var alignments = _parseAlignments(parser.next!);
  var columnCount = alignments.length;
  var headRow = _parseRow(parser, alignments, 'th'),
    headRowCols = headRow.children!,
    headRowColCount = headRowCols.length;
  if (headRowColCount > columnCount) {
    final lastCol = headRowCols.last as Element;
    var fixed = lastCol.children!.isEmpty;
    if (!fixed) {
      final col = lastCol.children!.last;
      fixed = col is UnparsedContent && col.textContent.isEmpty;
    }
    if (fixed) {
      headRowCols.removeLast();
      --headRowColCount;
    }

    while (headRowColCount > columnCount) {
      alignments.add(null);
      ++columnCount;
    }
  } else if (headRowColCount < columnCount) {
    alignments.removeRange(headRowColCount, columnCount);
    columnCount = headRowColCount;
  }
  if (headRowColCount != columnCount) {
    return null;
  }
  var head = Element('thead', [headRow]);

  // Advance past the divider of hyphens.
  parser.advance();

  var rows = <Element>[];
  while (!parser.isDone && !BlockSyntax.isAtBlockEnd(parser)) {
    var row = _parseRow(parser, alignments, 'td');
    var children = row.children;
    if (children != null) {
      while (children.length < columnCount) {
        // Insert synthetic empty cells.
        children.add(Element.withTag('td'));
      }
      while (children.length > columnCount) {
        children.removeLast();
      }
    }
    rows.add(row);
  }
  if (rows.isEmpty) {
    return Element('table', [head]);
  } else {
    var body = Element('tbody', rows);

    return Element('table', [head, body]);
  }
}