generateAndSaveMermaidImage method

Future<SlideAsset?> generateAndSaveMermaidImage(
  1. String mermaidSyntax
)

Implementation

Future<SlideAsset?> generateAndSaveMermaidImage(String mermaidSyntax) async {
  final fileName = '${mermaidSyntax.hashCode}.png';

  final existingAsset = await Pipeline.getAsset(fileName);

  if (existingAsset != null) {
    return existingAsset;
  }

  const tempDirPath = '.tmp_superdeck';
  final tempFilePath = p.join(tempDirPath, '$fileName.mmd');
  final tempFile = File(tempFilePath);
  final tempOutputPath = p.join(tempDirPath, fileName);

  if (!await Directory(tempDirPath).exists()) {
    await Directory(tempDirPath).create(recursive: true);
  }

  try {
    mermaidSyntax = mermaidSyntax.trim().replaceAll(r'\n', '\n');

    await tempFile.writeAsString(mermaidSyntax);

    final imageSizeParams = '--scale 2'.split(' ');
    final params =
        '-t dark -b transparent -i $tempFilePath -o $tempOutputPath '
            .split(' ');

    // Check if can execute mmdc before executing command
    final mmdcResult = await Process.run('mmdc', ['--version']);

    if (mmdcResult.exitCode != 0) {
      log(
        '"mmdc" not found. You need mermaid cli installed to process mermaid syntax',
      );

      return null;
    }

    final result = await Process.run('mmdc', [...params, ...imageSizeParams]);

    if (result.exitCode != 0) {
      log('Error while processing mermaid syntax');
      log(result.stderr);
      return null;
    }

    final output = await File(tempOutputPath).readAsBytes();

    return Pipeline.saveAsset(
      fileName,
      data: output,
    );
  } catch (e) {
    log('Error while processing mermaid syntax: $e');
    return null;
  } finally {
    final tempDir = Directory(tempDirPath);
    if (await tempDir.exists()) {
      await tempDir.delete(recursive: true);
    }
  }
}