-
Notifications
You must be signed in to change notification settings - Fork 118
Expand file tree
/
Copy pathhtml_utils.dart
More file actions
1053 lines (892 loc) · 30.9 KB
/
html_utils.dart
File metadata and controls
1053 lines (892 loc) · 30.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import 'dart:convert';
import 'dart:math';
import 'package:core/utils/html/html_template.dart';
import 'package:html/dom.dart' as dom;
import 'package:html/parser.dart' as parser;
import 'package:html_unescape/html_unescape.dart';
import 'js_interop_stub.dart' if (dart.library.html) 'dart:js_interop';
import 'dart:typed_data';
import 'package:core/data/constants/constant.dart';
import 'package:core/presentation/extensions/html_extension.dart';
import 'package:core/utils/app_logger.dart';
import 'package:flutter/material.dart';
import 'package:universal_html/html.dart' as html;
class HtmlUtils {
static const validTags = [
'html','head','body','div','span','p','b','i','u','strong','em','a',
'img','blockquote','ul','ol','li','table','tr','td','th','thead','tbody',
'br','hr','h1','h2','h3','h4','h5','h6','pre','code'
];
static final random = Random();
static final htmlUnescape = HtmlUnescape();
// ReDoS-safe regex patterns as const
static final _htmlStartTagRegex = RegExp(r'<[a-zA-Z][^>\s]*[^>]*>');
static final _htmlEndTagRegex = RegExp(r'</[a-zA-Z][^>]{0,128}>');
static final _whitespaceNormalizationRegex = RegExp(r'\s+');
static final _urlRegex = RegExp(
r'''(?:https?://|ftp://|mailto:|file://|www\.)[^\s<.]+(?:\.[^\s<.]+)*(?<![.,:;!?"')\]])''',
caseSensitive: false,
multiLine: true,
);
static final _protocolRegex = RegExp(r'^(?:https?|ftp|mailto|file)');
static final _tagRemovalRegex = RegExp(
'</?(?:${validTags.map(RegExp.escape).join('|')})(?:\\s+[^>]*)?>',
caseSensitive: false,
);
@visibleForTesting
static RegExp get htmlStartTagRegex => _htmlStartTagRegex;
@visibleForTesting
static RegExp get htmlEndTagRegex => _htmlEndTagRegex;
@visibleForTesting
static RegExp get urlRegex => _urlRegex;
static const removeLineHeight1px = (
script: '''
document.querySelectorAll('[style*="line-height"]').forEach(el => {
if (el.style.lineHeight === "1px") {
el.style.removeProperty("line-height");
}
});''',
name: 'removeLineHeight1px');
static const registerDropListener = (
script: '''
document.querySelector(".note-editable").addEventListener(
"drop",
(event) => window.parent.postMessage(
JSON.stringify({"name": "registerDropListener"})))''',
name: 'registerDropListener');
static const unregisterDropListener = (
script: '''
const editor = document.querySelector(".note-editable");
const newEditor = editor.cloneNode(true);
editor.parentNode.replaceChild(newEditor, editor);''',
name: 'unregisterDropListener');
static ({String name, String script}) registerSelectionChangeListener(
String viewId, {
bool isWebPlatform = false,
}) =>
(
script: '''
let lastSelectedText = '';
const isWebPlatform = $isWebPlatform;
const sendSelectionChangeMessage = (data) => {
// When iframe
if (window.parent) {
window.parent.postMessage(
JSON.stringify({
...data,
viewId: '$viewId',
name: 'onSelectionChange',
}),
'*'
);
}
// When WebView
if (window.flutter_inappwebview) {
window.flutter_inappwebview.callHandler('onSelectionChange', data);
}
};
function getEditableFromSelection(selection) {
const node = selection?.focusNode || selection?.anchorNode;
const el = node?.nodeType === Node.ELEMENT_NODE ? node : node?.parentElement;
if (isWebPlatform) {
return (
el?.closest('.note-editor .note-editable') ||
document.querySelector('.note-editor .note-editable')
);
} else {
return (
el?.closest('#editor')
);
}
}
function clamp(v, min, max) {
return Math.max(min, Math.min(max, v));
}
document.addEventListener('selectionchange', function() {
const selection = window.getSelection();
const selectedText = selection ? selection.toString().trim() : '';
if (selectedText === lastSelectedText) return;
lastSelectedText = selectedText;
if (!selectedText || !selection || selection.rangeCount === 0) {
sendSelectionChangeMessage({ hasSelection: false });
return;
}
try {
const editable = getEditableFromSelection(selection);
if (!editable) {
sendSelectionChangeMessage({ hasSelection: false });
return;
}
const editableRect = editable.getBoundingClientRect();
const padding = 8;
const safeHeight = Math.max(editableRect.height, padding * 2);
const range = selection.getRangeAt(0);
const rects = range.getClientRects();
if (!rects || rects.length === 0) {
sendSelectionChangeMessage({ hasSelection: false });
return;
}
const lastRect = rects[rects.length - 1];
// Avoid native selection marks in mobile
// Offset has been arbitrary determined to avoid selection marks on Android and iOS
const buttonOffset = isWebPlatform ? { x: 0, y: 0 } : { x: 24, y: -24 };
let x = lastRect.right - editableRect.left + buttonOffset.x;
let y = lastRect.bottom - editableRect.top + buttonOffset.y;
const isInside =
lastRect.bottom >= editableRect.top &&
lastRect.top <= editableRect.bottom &&
lastRect.right >= editableRect.left &&
lastRect.left <= editableRect.right;
if (!isInside) {
x = padding;
y = safeHeight / 2;
}
x = clamp(x, padding, editableRect.width - padding);
y = clamp(y, padding, safeHeight - padding);
sendSelectionChangeMessage({
hasSelection: true,
selectedText,
coordinates: {
x,
y,
width: lastRect.width,
height: lastRect.height,
},
});
} catch (error) {
console.error('Selection change error:', error);
sendSelectionChangeMessage({ hasSelection: false });
}
});
''',
name: 'onSelectionChange',
);
static const collapseSelectionToEnd = (
script: '''
(() => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
selection.collapseToEnd()
}
})();''',
name: 'collapseSelectionToEnd');
static const deleteSelectionContent = (
script: '''
(() => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
const range = selection.getRangeAt(0);
range.deleteContents();
}
})();''',
name: 'deleteSelectionContent');
static const saveSelection = (
script: '''
(() => {
const selection = window.getSelection();
if (selection && selection.rangeCount > 0) {
window._savedRange = selection.getRangeAt(0).cloneRange();
const result = selection.toString()
window.parent.postMessage(JSON.stringify({ "type": "toDart: saveSelection", result }), "*");
return result;
}
delete window._savedRange;
window.parent.postMessage(JSON.stringify({ "type": "toDart: saveSelection", result: "" }), "*");
return "";
})();''',
name: 'saveSelection');
static const restoreSelection = (
script: '''
(() => {
if (window._savedRange) {
const selection = window.getSelection();
if (selection) {
selection.removeAllRanges();
selection.addRange(window._savedRange);
delete window._savedRange;
const result = selection.toString()
window.parent.postMessage(JSON.stringify({ "type": "toDart: restoreSelection", result }), "*");
return result;
}
}
window.parent.postMessage(JSON.stringify({ "type": "toDart: restoreSelection", result: "" }), "*");
return "";
})();''',
name: 'restoreSelection');
static const getSavedSelection = (
script: '''
(() => {
if(window._savedRange) {
const result = window._savedRange.toString();
window.parent.postMessage(JSON.stringify({ "type": "toDart: getSavedSelection", result }), "*");
return result;
} else {
window.parent.postMessage(JSON.stringify({ "type": "toDart: getSavedSelection", result: "" }), "*");
return "";
}
})();''',
name: 'getSavedSelection');
static const clearSavedSelection = (
script: '''
(() => {
delete window._savedRange;
})();''',
name: 'clearSavedSelection');
static recalculateEditorHeight({double? maxHeight}) => (
script: '''
const editable = document.querySelector('.note-editable');
if (editable) {
editable.style.height = $maxHeight + 'px';
}
''',
name: 'recalculateEditorHeight');
static String customInlineBodyCssStyleHtmlEditor({
TextDirection direction = TextDirection.ltr,
double? horizontalPadding,
}) {
return '''
<style>
.note-frame, .note-tooltip-content, .note-popover {
font-family: 'Inter', sans-serif;
color: #222222;
}
.note-editable {
direction: ${direction.name};
}
.note-editable .tmail-signature {
text-align: ${direction == TextDirection.rtl ? 'right' : 'left'};
}
${horizontalPadding != null
? '''
.note-codable {
padding: 10px ${horizontalPadding}px 0px ${horizontalPadding > 3 ? horizontalPadding - 3 : horizontalPadding}px;
margin-right: 3px;
}
.note-editable {
padding: 10px ${horizontalPadding}px 0px ${horizontalPadding > 3 ? horizontalPadding - 3 : horizontalPadding}px;
margin-right: 3px;
}
'''
: '''
.note-editable {
padding: 10px 10px 0px 10px;
}
'''}
</style>
''';
}
static String validateHtmlImageResourceMimeType(String mimeType) {
if (mimeType.endsWith('svg')) {
mimeType = 'image/svg+xml';
}
log('HtmlUtils::validateHtmlImageResourceMimeType:mimeType: $mimeType');
return mimeType;
}
static String convertBase64ToImageResourceData({
required String base64Data,
required String mimeType
}) {
if (!base64Data.endsWith('==')) {
base64Data.append('==');
}
return 'data:$mimeType;base64,$base64Data';
}
static String generateHtmlDocument({
required String content,
double? minHeight,
double? minWidth,
String? styleCSS,
String? javaScripts,
bool hideScrollBar = true,
bool useDefaultFontStyle = false,
double fontSize = 14,
TextDirection? direction,
double? contentPadding,
}) {
return '''
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style>
${HtmlTemplate.fontFaceStyle}
${useDefaultFontStyle ? HtmlTemplate.defaultFontStyle(fontSize: fontSize) : ''}
.tmail-content {
min-height: ${minHeight ?? 0}px;
min-width: ${minWidth ?? 0}px;
overflow: auto;
overflow-wrap: break-word;
word-break: break-word;
}
${hideScrollBar ? '''
.tmail-content::-webkit-scrollbar {
display: none;
}
.tmail-content {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
''' : ''}
pre {
white-space: pre-wrap;
}
table {
white-space: normal !important;
}
@media only screen and (max-width: 600px) {
table {
width: 100% !important;
}
a {
width: -webkit-fill-available !important;
}
}
table, td, th {
word-break: normal !important;
}
${styleCSS ?? ''}
</style>
</head>
<body ${direction == TextDirection.rtl ? 'dir="rtl"' : ''} style = "overflow-x: hidden; ${contentPadding != null ? 'margin: $contentPadding;' : ''}";>
<div class="tmail-content">$content</div>
${javaScripts ?? ''}
</body>
</html>
''';
}
static String createTemplateHtmlDocument({String? title}) {
return '''
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
${title != null ? '<title>$title</title>' : ''}
</head>
<body></body>
</html>
''';
}
static String generateSVGImageData(String base64Data) => 'data:image/svg+xml;base64,$base64Data';
static void openNewTabHtmlDocument(String htmlDocument) {
final blob = html.Blob([htmlDocument], Constant.textHtmlMimeType);
final url = html.Url.createObjectUrlFromBlob(blob);
html.window.open(url, '_blank');
html.Url.revokeObjectUrl(url);
}
static String chromePdfViewer(Uint8List bytes, String fileName) {
return '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>$fileName</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.0.379/pdf.min.mjs" type="module"></script>
<style>
body {
background-color: black;
}
#pdf-container {
$_pdfContainerStyle
}
#pdf-viewer {
$_pdfViewerStyle
}
#app-bar {
$_pdfAppBarStyle
}
#download-btn {
$_pdfDownloadButtonStyle
}
#file-info {
$_pdfFileInfoStyle
}
#file-name {
$_pdfFileNameStyle
}
</style>
</head>
<body>
<div id="pdf-container">
$_pdfAppbarElement
<div id="pdf-viewer"></div>
</div>
<script type="module">
function renderPage(pdfDoc, pageNumber, canvas) {
pdfDoc.getPage(pageNumber).then(page => {
const viewport = page.getViewport({ scale: 1 });
canvas.height = viewport.height;
canvas.width = viewport.width;
const context = canvas.getContext('2d');
const renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
}
const bytesJs = new Uint8Array(${bytes.toJS});
const pdfContainer = document.getElementById('pdf-viewer');
var { pdfjsLib } = globalThis;
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/4.0.379/pdf.worker.min.mjs';
var loadingTask = pdfjsLib.getDocument(bytesJs);
loadingTask.promise.then(function(pdf) {
const numPages = pdf.numPages;
for (let i = 1; i <= numPages; i++) {
const pageContainer = document.createElement('div');
pageContainer.classList.add('pdf-page');
const canvas = document.createElement('canvas');
canvas.id = `page-\${i}`;
pageContainer.appendChild(canvas);
pdfContainer.appendChild(pageContainer);
renderPage(pdf, i, canvas);
}
}, function (reason) {
console.error(reason);
});
${_fileInfoScript(fileName)}
${_downloadButtonListenerScript(bytes, fileName)}
</script>
</body>
</html>''';
}
static String safariPdfViewer(Uint8List bytes, String fileName) {
final base64 = base64Encode(bytes);
return '''
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>$fileName</title>
<style>
body {
background-color: black;
}
body, html {
margin: 0;
padding: 0;
height: 100%;
}
#pdf-container {
$_pdfContainerStyle
overflow: hidden;
}
#pdf-viewer {
$_pdfViewerStyle
width: 100%;
height: calc(100vh - 53px);
}
#app-bar {
$_pdfAppBarStyle
}
#download-btn {
$_pdfDownloadButtonStyle
}
#file-info {
$_pdfFileInfoStyle
}
#file-name {
$_pdfFileNameStyle
}
</style>
</head>
<body>
<div id="pdf-container">
$_pdfAppbarElement
<div id="pdf-viewer"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.3.0/pdfobject.min.js"></script>
<script>
const bytesJs = new Uint8Array(${bytes.toJS});
PDFObject.embed('data:application/pdf;base64,$base64', "#pdf-viewer");
${_fileInfoScript(fileName)}
${_downloadButtonListenerScript(bytes, fileName)}
</script>
</body>
</html>''';
}
static void openFileViewer({
required Uint8List bytes,
required String fileName,
String? mimeType
}) {
final blob = html.Blob([bytes], mimeType);
final file = html.File([blob], fileName, {'type': mimeType});
final url = html.Url.createObjectUrl(file);
html.window.open(url, '_blank');
html.Url.revokeObjectUrl(url);
}
static const String _pdfContainerStyle = '''
display: flex;
flex-direction: column;
width: 100%;''';
static const String _pdfViewerStyle = '''
flex: 1; /* Allow viewer to fill remaining space */
border: 1px solid #ddd;
margin-left: auto;
margin-right: auto;
padding-top: 53px;
border: none;''';
static const String _pdfAppBarStyle = '''
position: fixed; /* Fix app bar to top */
top: 0;
left: 0;
right: 0; /* Stretch across entire viewport */
display: flex;
justify-content: space-between;
padding: 5px 10px;
background-color: #f0f0f0;
z-index: 100; /* Ensure buttons stay on top */''';
static const String _pdfDownloadButtonStyle = '''
padding: 5px 10px;
border: 1px solid #ddd;
border-radius: 5px;
cursor: pointer;
margin-left: 10px;''';
static const String _pdfFileInfoStyle = '''
width: 30%;
display: flex;
align-items: center;
padding: 5px 10px;''';
static const String _pdfFileNameStyle = '''
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-orient: vertical;''';
static const String _pdfAppbarElement = '''
<div id="app-bar">
<div id="file-info">
<span id="file-name" style="margin-right: 10px;"></span>
(<span id="file-size" style="white-space: nowrap;"></span>)
</div>
<div style="width: 10px;"></div>
<div id="buttons">
<button id="download-btn">
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M19 20V18H5V20H19ZM19 10H15V4H9V10H5L12 17L19 10Z" fill="#7B7B7B"/>
</svg>
</button>
</div>
</div>''';
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) {
logWarning('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) {
logWarning('AppUtils::setWindowBrowserTitle:Exception = $e');
}
}
static String unescapeHtml(String input) {
try {
return htmlUnescape.convert(input);
} catch (e) {
logWarning('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) {
logWarning('HtmlUtils::isOldSafari:Exception = $e');
return false;
}
}
static String addQuoteToggle(String htmlString) {
final likelyHtml = htmlString.contains(_htmlStartTagRegex) && // Contains a start tag
htmlString.contains(_htmlEndTagRegex); // 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 = '<div class="quote-toggle-container" >$htmlString</div>';
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 = '''
<button class="quote-toggle-button collapsed" title="Show trimmed content">
<span class="dot"></span>
<span class="dot"></span>
<span class="dot"></span>
</button>''';
// 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 => '''
<style>
.quote-toggle-button + blockquote {
display: block; /* Default display */
}
.quote-toggle-button.collapsed + blockquote {
display: none;
}
.quote-toggle-button {
display: flex;
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
gap: 2px;
background-color: #d7e2f5;
padding: 0;
margin: 8px 0;
border-radius: 50%;
transition: background-color 0.2s ease-in-out;
border: none;
cursor: pointer;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* IE 10+ */
user-select: none; /* Standard syntax */
-webkit-user-drag: none; /* Prevent dragging on WebKit browsers (e.g., Chrome, Safari) */
}
.quote-toggle-button:hover {
background-color: #cdcdcd !important;
}
.dot {
width: 3.75px;
height: 3.75px;
background-color: #55687d;
border-radius: 50%;
}
</style>''';
static String get quoteToggleScript => '''
<script>
document.addEventListener('DOMContentLoaded', function() {
const buttons = document.querySelectorAll('.quote-toggle-button');
buttons.forEach(button => {
button.onclick = function() {
const blockquote = this.nextElementSibling;
if (blockquote && blockquote.tagName === 'BLOCKQUOTE') {
this.classList.toggle('collapsed');
if (this.classList.contains('collapsed')) {
this.title = 'Show trimmed content';
} else {
this.title = 'Hide expanded content';
}
}
};
});
});
</script>''';
static String extractPlainText(
String html, {
bool removeQuotes = true,
bool removeStyle = true,
bool removeScript = true,
}) {
var cleaned = html;
if (cleaned.isEmpty) return '';
// Parse DOM
final doc = parser.parse(cleaned);
// Remove unwanted nodes by CSS selector
if (removeQuotes) {
doc.querySelectorAll('blockquote').forEach((e) => e.remove());
}
if (removeStyle) {
doc.querySelectorAll('style').forEach((e) => e.remove());
}
if (removeScript) {
doc.querySelectorAll('script').forEach((e) => e.remove());
}
cleaned = doc.outerHtml;
// Decode HTML entities up to 5 times (& → &, → space, <div> → <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
cleaned = cleaned.replaceAll(_tagRemovalRegex, ' ');
// Normalize whitespace
cleaned = cleaned.replaceAll(_whitespaceNormalizationRegex, ' ').trim();
return cleaned;
}
static String wrapPlainTextLinks(String htmlString) {
try {
final document = parser.parse(htmlString);
final container = document.body;
if (container == null) return htmlString;
_processNode(container, _urlRegex);
return container.innerHtml;
} catch (e) {
logWarning('HtmlUtils::wrapPlainTextLinks:Exception = $e');
return htmlString;
}
}
static final _skipTags = {
'a',
'img',
'video',
'audio',
'source',
'link',
'script',
'iframe',
'code',
'pre',
};
static void _processNode(dom.Node node, RegExp urlRegex) {
for (var child in node.nodes.toList()) {
// Skip if node or parent node is in tag to skip
final parentTag = child.parent?.localName;
if (parentTag != null && _skipTags.contains(parentTag.toLowerCase())) {
continue;
}
if (child.nodeType == dom.Node.TEXT_NODE) {
final text = child.text ?? '';
final matches = urlRegex.allMatches(text);
if (matches.isEmpty) continue;