mirror of
https://github.com/linagora/tmail-flutter.git
synced 2026-12-05 16:08:46 +00:00
1151 lines
39 KiB
Dart
1151 lines
39 KiB
Dart
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,
|
|
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');
|
|
|
|
/// 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 = '<br>';
|
|
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 `<img>` 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 '''
|
|
<style>
|
|
.note-frame, .note-tooltip-content, .note-popover {
|
|
font-family: '${HtmlTemplate.fontFamilyApp}', 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,
|
|
}) {
|
|
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 '''
|
|
<!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) : ''}
|
|
|
|
*, *::before, *::after {
|
|
box-sizing: border-box;
|
|
}
|
|
|
|
.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:not(.tmail-file-link-card) {
|
|
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>
|
|
<style>html, body { height: auto !important; }</style>
|
|
${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 windowFeatures({String? size, required bool noOpener}) =>
|
|
[if (size != null) size, if (noOpener) 'noopener,noreferrer'].join(',');
|
|
|
|
static bool openNewWindowByUrl(
|
|
String url,
|
|
{
|
|
int width = 800,
|
|
int height = 600,
|
|
bool isFullScreen = false,
|
|
bool isCenter = true,
|
|
bool noOpener = false,
|
|
}
|
|
) {
|
|
try {
|
|
// For untrusted URLs, do not give the opened page a handle on this
|
|
// window (reverse tabnabbing) nor leak the referrer.
|
|
if (isFullScreen) {
|
|
html.window.open(url, '_blank', windowFeatures(noOpener: noOpener));
|
|
|
|
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 = windowFeatures(
|
|
size: 'width=$width,height=$height,top=$top,left=$left',
|
|
noOpener: noOpener,
|
|
);
|
|
|
|
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,
|
|
bool removeTMailSignature = true,
|
|
bool removeFileLinkCards = 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());
|
|
}
|
|
if (removeTMailSignature) {
|
|
doc.querySelectorAll('div.tmail-signature').forEach((e) => e.remove());
|
|
}
|
|
if (removeFileLinkCards) {
|
|
// File-link cards (e.g. Drive attachments, see FileLinkCardHtmlBuilder)
|
|
// carry the "tmail-file-link-card" class. Their title/action-label
|
|
// text is card chrome, not user-authored content, so it must not feed
|
|
// the attachment-reminder keyword scan.
|
|
doc.querySelectorAll('a.tmail-file-link-card').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 fragment = parser.parseFragment(htmlString);
|
|
|
|
_processNode(fragment, _urlRegex);
|
|
|
|
return fragment.outerHtml;
|
|
} catch (e) {
|
|
logWarning('HtmlUtils::wrapPlainTextLinks:Exception = $e');
|
|
return htmlString;
|
|
}
|
|
}
|
|
|
|
static final _skipTags = {
|
|
'a',
|
|
'img',
|
|
'video',
|
|
'audio',
|
|
'source',
|
|
'link',
|
|
'script',
|
|
'style',
|
|
'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 = node is dom.Element ? node.localName : null;
|
|
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;
|
|
|
|
final nodes = <dom.Node>[];
|
|
int lastIndex = 0;
|
|
|
|
for (final match in matches) {
|
|
final url = match.group(0)!;
|
|
final start = match.start;
|
|
|
|
if (start > lastIndex) {
|
|
nodes.add(dom.Text(text.substring(lastIndex, start)));
|
|
}
|
|
|
|
// ignore unsafe URLs
|
|
if (url.toLowerCase().startsWith('javascript:') ||
|
|
url.toLowerCase().startsWith('data:')) {
|
|
nodes.add(dom.Text(url));
|
|
} else {
|
|
// Normalize href
|
|
final href = url.startsWith(_protocolRegex)
|
|
? url
|
|
: 'https://$url';
|
|
|
|
final link = dom.Element.tag('a')
|
|
..attributes['href'] = href
|
|
..text = url;
|
|
|
|
nodes.add(link);
|
|
}
|
|
|
|
lastIndex = match.end;
|
|
}
|
|
|
|
if (lastIndex < text.length) {
|
|
nodes.add(dom.Text(text.substring(lastIndex)));
|
|
}
|
|
|
|
final index = node.nodes.indexOf(child);
|
|
|
|
node.nodes.removeAt(index);
|
|
node.nodes.insertAll(index, nodes);
|
|
} else {
|
|
_processNode(child, urlRegex);
|
|
}
|
|
}
|
|
}
|
|
|
|
static String getRandString(int len) {
|
|
var random = Random.secure();
|
|
var values = List<int>.generate(len, (i) => random.nextInt(255));
|
|
return base64UrlEncode(values);
|
|
}
|
|
|
|
}
|