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 'package:core/data/constants/constant.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,
);
@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');
/// Removes every identity signature, including ones the user edited or
/// split; signatures inside a quoted message are kept. Runs in the web
/// editor iframe and the mobile editor webview; only the web editor has
/// jQuery, so only it emits the change notification. In code view the
/// edited HTML lives in the code textarea, so signatures are removed there.
static const removeAllSignatures = (
script: '''
(() => {
const root = document.querySelector('.note-editable') || document.getElementById('editor');
if (!root) return;
const removeFrom = (container) => {
let removed = 0;
container.querySelectorAll('.tmail-signature').forEach(el => {
if (!el.closest('blockquote, cite')) { el.remove(); removed++; }
});
return removed;
};
const jq = window.jQuery;
const \$editor = jq ? jq('#summernote-2') : null;
const codable = document.querySelector('.note-codable');
if (\$editor && codable && \$editor.summernote('codeview.isActivated')) {
// Inert document: the user's raw HTML is parsed without running anything.
const container = document.implementation.createHTMLDocument('').createElement('div');
container.innerHTML = codable.value;
if (removeFrom(container) === 0) return;
codable.value = container.innerHTML;
\$editor.trigger('summernote.change.codeview', [codable.value, jq(codable)]);
return;
}
removeFrom(root);
// Notify through this editor's own change handler, which tags the
// message with its view id, so the composer refreshes its cached body
// without a window-wide getText that another composer could answer.
if (\$editor) {
\$editor.trigger('summernote.change', [root.innerHTML, jq(root)]);
}
})();''',
name: 'removeAllSignatures');
/// Editor script (summernote iframe): sanitizes every `insertHTML`
/// command. The editor inserts pasted and dropped HTML with
/// `document.execCommand('insertHTML', ...)` instead of the browser's
/// native, sanitizing paste, and the editor iframe is same-origin with the
/// application: pasted scripts, event handlers or `javascript:` links would
/// run with its privileges. The markup is parsed in an inert document,
/// active content is removed, then the native command runs.
static const sanitizeInsertHtml = (
script: r"""
if (!document.__tmailInsertHtmlSanitized) {
document.__tmailInsertHtmlSanitized = true;
const blockedTags = 'script,iframe,frame,frameset,object,embed,applet,meta,base,link,'
+ 'form,input,button,textarea,select,option,noscript,template,xmp,noembed,noframes,'
+ 'plaintext,title,style,svg,math,portal';
const urlAttributes = ['href', 'src', 'xlink:href', 'action', 'formaction', 'background',
'poster', 'data', 'codebase', 'cite', 'longdesc', 'usemap', 'lowsrc', 'dynsrc'];
const isSafeUrl = (name, value) => {
const url = String(value).replace(/[\u0000- \u007f-\u009f]/g, '').toLowerCase();
if (/^(javascript|vbscript|livescript|mocha):/.test(url)) return false;
if (url.startsWith('data:')) {
return name === 'src' && /^data:image\/(png|jpe?g|gif|webp|bmp);/.test(url);
}
return true;
};
const sanitizeHtml = (html) => {
const doc = new DOMParser().parseFromString(String(html), 'text/html');
doc.querySelectorAll(blockedTags).forEach((node) => node.remove());
doc.querySelectorAll('*').forEach((element) => {
for (const attribute of Array.from(element.attributes)) {
const name = attribute.name.toLowerCase();
if (name.startsWith('on') || name === 'srcdoc' || name === 'srcset' || name === 'is'
|| (urlAttributes.includes(name) && !isSafeUrl(name, attribute.value))) {
element.removeAttribute(attribute.name);
}
}
const position = element.style && element.style.position;
if (position === 'fixed' || position === 'absolute' || position === 'sticky') {
element.style.removeProperty('position');
}
});
return doc.body ? doc.body.innerHTML : '';
};
const nativeExecCommand = document.execCommand.bind(document);
document.execCommand = function (command, showUI, value) {
if (typeof command === 'string' && command.toLowerCase() === 'inserthtml') {
value = sanitizeHtml(value);
}
return nativeExecCommand(command, showUI, value);
};
}""",
name: 'sanitizeInsertHtml');
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',
);
/// Intercepts Enter inside a drive-link file card row (a DIV whose direct
/// children include a `contenteditable="false"` card) and breaks the row
/// into two rows at the caret's position, with a new empty paragraph in
/// between - instead of letting the editor's native paragraph-split run.
/// Pressing Enter at the very start/end of the row just adds a blank line
/// before/after it instead of producing a pointless empty row.
///
/// Neither editor's own Enter can be reused here, and the reason is worth
/// recording because the alternative looks tempting. The row contains only
/// cards, so it holds no text node. Summernote's `insertParagraph` first
/// calls `range.normalize()`, which for a collapsed caret walks *backward*
/// looking for a "visible point"; that check accepts any text node but never
/// consults `contenteditable`, so with nothing at row level it descends into
/// the previous card and lands on its title text. `ancestor(sc, isPara)`
/// then resolves to the card's inner DIV - Summernote's `isPara` matches
/// `/^DIV|^P|^LI|^H[1-7]/` - and `splitTree` splits *inside* the card, which
/// is what made Enter grow the card before the caret. Mobile's raw
/// `contenteditable` div hits the same missing-text-node problem natively.
///
/// Padding the row with zero-width text nodes to give the caret somewhere
/// legal to sit was measured and rejected: it fixes only the row's two ends,
/// and each filler costs an extra arrow press to cross because its two
/// offsets render at the same pixel.
static ({String name, String script}) registerFileLinkRowEnterKeyHandler({
bool isWebPlatform = false,
}) =>
(
script: '''
(() => {
const isWebPlatform = $isWebPlatform;
const root = isWebPlatform
? document.querySelector('.note-editor .note-editable')
: document.querySelector('#editor');
if (!root || root.dataset.fileLinkRowEnterHandlerAttached) return;
root.dataset.fileLinkRowEnterHandlerAttached = 'true';
function isFileLinkCardRow(el) {
if (!el || el.tagName !== 'DIV') return false;
let child = el.firstElementChild;
while (child) {
if (child.tagName === 'A' && child.classList.contains('tmail-file-link-card')) {
return true;
}
child = child.nextElementSibling;
}
return false;
}
function findFileLinkCardRow(node) {
let el = node && node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
while (el && el !== root) {
if (isFileLinkCardRow(el)) return el;
el = el.parentElement;
}
return null;
}
function isEmptyBlock(el) {
return !!el
&& (el.tagName === 'P' || el.tagName === 'DIV')
&& !isFileLinkCardRow(el)
&& el.textContent.trim() === '';
}
// Index into row.childNodes (not just element children), splitting
// a text node in two if the caret sits mid-text - handles text typed
// between cards, which lands as a direct child text node of `row`.
function getSplitIndex(row, selection) {
const node = selection.anchorNode;
const offset = selection.anchorOffset;
if (node === row) return Math.min(offset, row.childNodes.length);
if (node.nodeType === Node.TEXT_NODE && node.parentNode === row) {
if (offset > 0 && offset < node.length) {
node.splitText(offset);
}
const index = Array.prototype.indexOf.call(row.childNodes, node);
return offset === 0 ? index : index + 1;
}
let el = node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
while (el && el.parentNode !== row) {
el = el.parentNode;
}
if (!el) return row.childNodes.length;
const index = Array.prototype.indexOf.call(row.childNodes, el);
return index < 0 ? row.childNodes.length : index + 1;
}
function makeEmptyParagraph() {
const p = document.createElement('p');
p.innerHTML = '
';
return p;
}
function placeCaretAtStart(selection, target) {
const range = document.createRange();
range.setStart(target, 0);
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
// Reuses an already-empty block sibling of `row` (on `side`) as the
// caret's landing line instead of stacking a new blank line on top
// of one that's already there, creating one only if needed.
function placeCaretInAdjacentLine(row, side, selection) {
const sibling = side === 'before' ? row.previousElementSibling : row.nextElementSibling;
let target = sibling;
if (!isEmptyBlock(target)) {
target = makeEmptyParagraph();
row.parentNode.insertBefore(target, side === 'before' ? row : row.nextSibling);
}
placeCaretAtStart(selection, target);
}
function hasCard(nodes) {
return nodes.some(function (node) {
return node.nodeType === Node.ELEMENT_NODE && node.tagName === 'A';
});
}
// Splits row's child nodes at splitIndex. If a side has no card
// left, docks the caret in the adjacent line instead.
function splitRowAt(row, splitIndex, selection) {
const childNodes = Array.prototype.slice.call(row.childNodes);
const before = childNodes.slice(0, splitIndex);
const after = childNodes.slice(splitIndex);
if (!hasCard(before)) {
placeCaretInAdjacentLine(row, 'before', selection);
return;
}
if (!hasCard(after)) {
placeCaretInAdjacentLine(row, 'after', selection);
return;
}
const secondRow = row.cloneNode(false);
after.forEach(function (node) {
secondRow.appendChild(node);
});
const newLine = makeEmptyParagraph();
row.parentNode.insertBefore(newLine, row.nextSibling);
row.parentNode.insertBefore(secondRow, newLine.nextSibling);
placeCaretAtStart(selection, newLine);
}
root.addEventListener('keydown', function (event) {
if (event.key !== 'Enter') return;
try {
const selection = window.getSelection();
if (!selection || selection.rangeCount === 0) return;
const row = findFileLinkCardRow(selection.anchorNode);
if (!row) return;
event.preventDefault();
splitRowAt(row, getSplitIndex(row, selection), selection);
root.dispatchEvent(new Event('input', { bubbles: true }));
} catch (error) {
console.error('File link row Enter handler error:', error);
}
}, true);
})();''',
name: 'registerFileLinkRowEnterKeyHandler',
);
/// JS handler name used to bridge file-link-card taps back to Dart on
/// mobile, since `window.open()` inside the InAppWebView editor has no
/// `onCreateWindow` wired up and is silently swallowed.
static const String fileLinkCardClickHandlerName = 'tmailFileLinkCardClick';
/// `target="_blank"` on the card anchor doesn't survive
/// StandardizeHtmlSanitizingTransformers (draft reload strips it), and
/// Summernote's image-handle module hijacks mousedown on any `` before
/// it reaches the anchor - so this bypasses both by opening the link itself
/// on a capture-phase listener. On mobile, `window.open()` inside the
/// InAppWebView editor has no `onCreateWindow` handler and is silently
/// swallowed, so the tap is bridged to Dart instead, which opens the link
/// via `url_launcher`.
static ({String name, String script}) registerFileLinkCardClickHandler({
bool isWebPlatform = false,
}) =>
(
script: '''
(() => {
const isWebPlatform = $isWebPlatform;
const root = isWebPlatform
? document.querySelector('.note-editor .note-editable')
: document.querySelector('#editor');
if (!root || root.dataset.fileLinkCardClickHandlerAttached) return;
root.dataset.fileLinkCardClickHandlerAttached = 'true';
function closestCardAnchor(node) {
let el = node && node.nodeType === Node.TEXT_NODE ? node.parentElement : node;
while (el && el !== root.parentElement) {
if (el.tagName === 'A' && el.classList.contains('tmail-file-link-card')) {
return el;
}
el = el.parentElement;
}
return null;
}
function isSafeCardHref(href) {
try {
const protocol = new URL(href, window.location.href).protocol;
return protocol === 'http:' || protocol === 'https:';
} catch (error) {
return false;
}
}
root.addEventListener('mousedown', function (event) {
if (closestCardAnchor(event.target)) {
event.preventDefault();
event.stopPropagation();
// preventDefault() also blocks the native focus shift, so the
// app's onFocus->hideMenu bridge never fires. Refocus explicitly
// (preventScroll avoids the iframe scroll-into-view jump).
if (document.activeElement !== root) {
root.focus({ preventScroll: true });
}
}
}, true);
root.addEventListener('click', function (event) {
const anchor = closestCardAnchor(event.target);
if (!anchor) return;
event.preventDefault();
event.stopPropagation();
try {
const href = anchor.getAttribute('href');
if (href && isSafeCardHref(href)) {
if (isWebPlatform) {
window.open(href, '_blank', 'noopener,noreferrer');
} else {
window.flutter_inappwebview.callHandler('$fileLinkCardClickHandlerName', href);
}
}
} catch (error) {
console.error('File link card click handler error:', error);
}
}, true);
})();''',
name: 'registerFileLinkCardClickHandler',
);
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 '''
''';
}
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,
}) {
try {
return 'data:$mimeType;base64,${base64.normalize(base64Data)}';
} catch (e) {
logWarning('HtmlUtils::convertBase64ToImageResourceData: $e');
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 '''