updateIndex function

void updateIndex({
  1. required String imageMode,
  2. required String? imagePath,
})

Implementation

void updateIndex({required String imageMode, required String? imagePath}) {
  print('[Web] Updating index.html');
  final webIndex = File(_webIndex);
  var lines = webIndex.readAsLinesSync();

  var foundExistingStyleSheet = false;
  var headCloseTagLine = 0;
  var bodyOpenTagLine = 0;
  var existingPictureLine = 0;
  var existingBodyLine = 0;

  const styleSheetLink =
      '<link rel="stylesheet" type="text/css" href="splash/style.css">';
  for (var x = 0; x < lines.length; x++) {
    var line = lines[x];

    if (line.contains(styleSheetLink)) {
      foundExistingStyleSheet = true;
    } else if (line.contains('</head>')) {
      headCloseTagLine = x;
    } else if (line.contains('<body')) {
      bodyOpenTagLine = x;
    } else if (line.contains('<picture id="splash">')) {
      existingPictureLine = x;
    } else if (line.contains('<body>')) {
      existingBodyLine = x;
    }
  }

  if (!foundExistingStyleSheet) {
    lines[headCloseTagLine] = '  ' + styleSheetLink + '\n</head>';
  }

  if (existingPictureLine == 0) {
    if (imagePath != null) {
      for (var x = _indexHtmlPicture.length - 1; x >= 0; x--) {
        lines[bodyOpenTagLine + 1] =
            _indexHtmlPicture[x].replaceFirst('[IMAGEMODE]', imageMode) +
                '\n' +
                lines[bodyOpenTagLine + 1];
      }
    }
  } else {
    if (imagePath != null) {
      for (var x = 0; x < _indexHtmlPicture.length; x++) {
        lines[existingPictureLine + x] =
            _indexHtmlPicture[x].replaceFirst('[IMAGEMODE]', imageMode);
      }
    } else {
      lines.removeRange(
          existingPictureLine, existingPictureLine + _indexHtmlPicture.length);
    }
  }
  if (existingBodyLine != 0) {
    lines[existingBodyLine] =
        '<body style="position: fixed; inset: 0px; overflow: hidden; padding: 0px; margin: 0px; user-select: none; touch-action: none; font: 14px sans-serif; color: red;">';
  }
  webIndex.writeAsStringSync(lines.join('\n'));
}