doSerialization method

  1. @override
String doSerialization(
  1. Document document,
  2. ParagraphNode node, {
  3. NodeSelection? selection,
})
override

Implementation

@override
String doSerialization(
  Document document,
  ParagraphNode node, {
  NodeSelection? selection,
}) {
  if (selection != null && selection is! TextNodeSelection) {
    // We don't know how to handle this selection type.
    return '';
  }
  final textSelection = selection as TextNodeSelection?;
  if (textSelection != null && textSelection.isCollapsed) {
    // Selection is collapsed. Nothing is selected for copy.
    return '';
  }
  final textToConvert = textSelection != null //
      ? node.text.copyText(textSelection.start, textSelection.end)
      : node.text;

  final buffer = StringBuffer();

  final Attribution? blockType = node.getMetadataValue('blockType');
  final String? textAlign = node.getMetadataValue('textAlign');

  // Add the alignment token, we exclude the left alignment because it's the default.
  if (markdownSyntax == MarkdownSyntax.superEditor && textAlign != null && textAlign != 'left') {
    final alignmentToken = _convertAlignmentToMarkdown(textAlign);
    if (alignmentToken != null) {
      buffer.writeln(alignmentToken);
    }
  }

  if (blockType == header1Attribution) {
    buffer.write('# ${textToConvert.toMarkdown()}');
  } else if (blockType == header2Attribution) {
    buffer.write('## ${textToConvert.toMarkdown()}');
  } else if (blockType == header3Attribution) {
    buffer.write('### ${textToConvert.toMarkdown()}');
  } else if (blockType == header4Attribution) {
    buffer.write('#### ${textToConvert.toMarkdown()}');
  } else if (blockType == header5Attribution) {
    buffer.write('##### ${textToConvert.toMarkdown()}');
  } else if (blockType == header6Attribution) {
    buffer.write('###### ${textToConvert.toMarkdown()}');
  }

  // We're not at the end of the document yet. Add a blank line after the
  // paragraph so that we can tell the difference between separate
  // paragraphs vs. newlines within a single paragraph.
  final nodeIndex = document.getNodeIndexById(node.id);
  if (nodeIndex != document.nodeCount - 1) {
    buffer.writeln();
  }

  return buffer.toString();
}