''';
static String _downloadButtonListenerScript(Uint8List bytes, String? fileName) {
return '''
const downloadBtn = document.getElementById('download-btn');
downloadBtn.addEventListener('click', () => {
const buffer = new Uint8Array(${bytes.toJS}).buffer;
const blob = new Blob([buffer], { type: "application/pdf" });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.download = "$fileName";
a.href = url;
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
});''';
}
static String _fileInfoScript(String? fileName) {
return '''
function formatFileSize(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat(bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
}
const fileNameSpan = document.getElementById('file-name');
fileNameSpan.textContent = "$fileName";
const fileSizeSpan = document.getElementById('file-size');
fileSizeSpan.textContent = formatFileSize(bytesJs.length);''';
}
static bool openNewWindowByUrl(
String url,
{
int width = 800,
int height = 600,
bool isFullScreen = false,
bool isCenter = true,
}
) {
try {
if (isFullScreen) {
html.window.open(url, '_blank');
html.Url.revokeObjectUrl(url);
return true;
}
final screenWidth = html.window.screen?.width ?? width;
final screenHeight = html.window.screen?.height ?? height;
int left, top;
if (isCenter) {
left = (screenWidth - width) ~/ 2;
top = (screenHeight - height) ~/ 2;
} else {
left = random.nextInt(screenWidth ~/ 2);
top = random.nextInt(screenHeight ~/ 2);
}
final options = 'width=$width,height=$height,top=$top,left=$left';
html.window.open(url, '_blank', options);
html.Url.revokeObjectUrl(url);
return true;
} catch (e) {
logError('AppUtils::openNewWindowByUrl:Exception = $e');
return false;
}
}
static void setWindowBrowserTitle(String title) {
try {
final titleElements = html.window.document.getElementsByTagName('title');
if (titleElements.isNotEmpty) {
titleElements.first.text = title;
}
} catch (e) {
logError('AppUtils::setWindowBrowserTitle:Exception = $e');
}
}
static String unescapeHtml(String input) {
try {
return htmlUnescape.convert(input);
} catch (e) {
logError('HtmlUtils::unescapeHtml:Exception = $e');
return input;
}
}
static String removeWhitespace(String input) {
return input
.replaceAll('\r', '')
.replaceAll('\n', '')
.replaceAll('\t', '');
}
/// Returns true if the browser is Safari and its major version is less than 17.
static bool isSafariBelow17() {
try {
final userAgent = html.window.navigator.userAgent;
log('HtmlUtils::isOldSafari:UserAgent = $userAgent');
final isSafari = userAgent.contains('Safari') && !userAgent.contains('Chrome');
if (!isSafari) return false;
final match = RegExp(r'Version/(\d+)\.').firstMatch(userAgent);
if (match == null) return false;
final version = int.tryParse(match.group(1)!);
log('HtmlUtils::isOldSafari:Version = $version');
return version != null && version < 17;
} catch (e) {
logError('HtmlUtils::isOldSafari:Exception = $e');
return false;
}
}
static String addQuoteToggle(String htmlString) {
final likelyHtml = htmlString.contains(RegExp(r'<[a-zA-Z][^>]*>')) && // Contains a start tag
htmlString.contains(RegExp(r'[a-zA-Z][^>]*>')); // Contains an end tag
if (!likelyHtml) {
return htmlString; // Not likely HTML, return original
}
try {
html.DomParser().parseFromString(htmlString, 'text/html');
} catch (e) {
return htmlString;
}
final containerElement = '
$htmlString
';
final containerDom = html.DomParser().parseFromString(containerElement, 'text/html');
html.ElementList blockquotes = containerDom.querySelectorAll('.quote-toggle-container > blockquote');
int currentSearchLevel = 1;
while (blockquotes.isEmpty) {
// Finish searching at level [currentSearchLevel]
if (currentSearchLevel >= 3) return htmlString;
// No blockquote elements found on first level, try another level
blockquotes = containerDom.querySelectorAll('.quote-toggle-container${' > div' * currentSearchLevel} > blockquote');
currentSearchLevel++;
}
final lastBlockquote = blockquotes.last;
const buttonHtmlContent = '''
''';
// Parse the button HTML content as a fragment
final tempDoc =
html.DomParser().parseFromString(buttonHtmlContent, 'text/html');
final buttonElement = tempDoc.querySelector('.quote-toggle-button');
// Insert the button before the last blockquote
if (lastBlockquote.parentNode != null && buttonElement != null) {
lastBlockquote.parentNode!.insertBefore(buttonElement, lastBlockquote);
}
// Return the modified HTML string
return containerDom.documentElement?.outerHtml ?? htmlString;
}
static String get quoteToggleStyle => '''
''';
static String get quoteToggleScript => '''
''';
static String extractPlainText(String html) {
var cleaned = html;
// Delete the blockquote and the content inside
final blockquoteRegex = RegExp(
r'
',
caseSensitive: false,
);
cleaned = html.replaceAll(blockquoteRegex, '');
// Decode HTML entities up to 5 times (& → &, → space, <div> →
, ...)
int iterations = 0;
const maxIterations = 5;
String decoded;
do {
decoded = cleaned;
cleaned = htmlUnescape.convert(cleaned);
iterations++;
} while (decoded != cleaned && iterations < maxIterations);
// Delete all remaining HTML tags → replace tag with space to avoid text sticking
final tagRegex = RegExp(
'?(${validTags.join('|')})(\\s+[^>]*)?>',
caseSensitive: false,
);
cleaned = cleaned.replaceAll(tagRegex, ' ');
// Normalize whitespace
cleaned = cleaned.replaceAll(RegExp(r'\s+'), ' ').trim();
return cleaned;
}
}