getAllImage function

Future<void> getAllImage(
  1. String pathSource,
  2. CoreGenModel modelGen,
  3. FigmaGen config,
  4. FigmaFile figmaFile,
  5. ImageWriter writer,
)

Implementation

Future<void> getAllImage(
  String pathSource,
  CoreGenModel modelGen,
  FigmaGen config,
  FigmaFile figmaFile,
  ImageWriter writer,
) async {
  final List<
      ({
        String? id,
        String? name,
        String? parent,
      })> imgIds = [
    for (final i in figmaFile.document.documentsForImage())
      if (i.type == 'IMAGE' || i.type == 'RECTANGLE')
        (
          id: i.id,
          name: i.name,
          parent: i.parent?.name,
        ),
  ].where((e) => e.id != null).toList();

  final token = modelGen.tokenFigma ?? config.figmaToken;

  if (token == null) {
    stdout.writeln('Token figma is null');
    return;
  }

  final imgLst = await fetchImages(
    config.figmaKey,
    token,
    imgIds.map((e) => e.id).where((e) => e != null).cast<String>().toList(),
    modelGen,
  );
  final lstLog = <String>[];
  for (final img in imgLst) {
    final node = imgIds.firstWhereOrNull((e) => e.id == img.imageId);
    final name = node != null ? '${node.name}_${node.parent}' : null;
    final path = name ?? img.imageId;

    final pathDot = RegExp('\\.${modelGen.format}\$').hasMatch(path)
        ? path
        : '$path.${modelGen.format}';
    stdout.writeln(pathDot);
    final check = checkIfExit(pathSource, pathDot);
    if (check || img.url == null) continue;

    stdout.writeln('img $path download...');
    final imageByte = await download(img.url!);

    String? oldPath;

    lstLog.add('add imgs: - $path: :name');

    writer(imageByte, pathDot, oldPath);
  }
  stdout
    ..writeln(lstLog.join('\n'))
    ..writeln('Download images success!');
}