mirror of
https://github.com/linagora/tmail-flutter.git
synced 2026-12-05 08:05:07 +00:00
440 lines
16 KiB
Dart
440 lines
16 KiB
Dart
|
|
import 'dart:convert';
|
|
|
|
import 'package:core/presentation/extensions/color_extension.dart';
|
|
import 'package:core/presentation/utils/app_toast.dart';
|
|
import 'package:core/utils/app_logger.dart';
|
|
import 'package:core/utils/html/html_utils.dart';
|
|
import 'package:core/utils/platform_info.dart';
|
|
import 'package:custom_pop_up_menu/custom_pop_up_menu.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:get/get.dart';
|
|
import 'package:html_editor_enhanced/html_editor.dart';
|
|
import 'package:model/upload/file_info.dart';
|
|
import 'package:tmail_ui_user/features/base/widget/dialog_picker/color_dialog_picker.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/code_view_state.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/dropdown_menu_font_status.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/font_name_type.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/formatting_options_state.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/header_style_type.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/inline_image.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/order_list_type.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/paragraph_type.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/model/rich_text_style_type.dart';
|
|
import 'package:tmail_ui_user/features/composer/presentation/utils/composer_code_view_sanitizer.dart';
|
|
import 'package:tmail_ui_user/main/localizations/app_localizations.dart';
|
|
import 'package:tmail_ui_user/main/routes/route_navigation.dart';
|
|
|
|
class RichTextWebController extends GetxController {
|
|
|
|
static const List<int> fontSizeList = [10, 12, 14, 15, 16, 18, 24, 36, 48, 64];
|
|
static const int fontSizeDefault = 16;
|
|
static const String _emptyEditorHtml = '<p><br></p>';
|
|
|
|
final HtmlEditorController editorController;
|
|
final ComposerCodeViewSanitizer _codeViewSanitizer;
|
|
final Duration _editorReplyTimeout;
|
|
|
|
RichTextWebController({
|
|
HtmlEditorController? editorController,
|
|
ComposerCodeViewSanitizer codeViewSanitizer = const ComposerCodeViewSanitizer(),
|
|
Duration editorReplyTimeout = const Duration(seconds: 5),
|
|
}) : editorController = editorController ?? HtmlEditorController(),
|
|
_codeViewSanitizer = codeViewSanitizer,
|
|
_editorReplyTimeout = editorReplyTimeout;
|
|
|
|
final listTextStyleApply = RxList<RichTextStyleType>();
|
|
final selectedTextColor = Colors.black.obs;
|
|
final selectedTextBackgroundColor = Colors.white.obs;
|
|
final selectedFontName = FontNameType.sansSerif.obs;
|
|
final selectedFontSize = RxInt(fontSizeDefault);
|
|
final codeViewState = CodeViewState.disabled.obs;
|
|
final selectedParagraph = ParagraphType.alignLeft.obs;
|
|
final selectedOrderList = OrderListType.bulletedList.obs;
|
|
final focusMenuOrderList = RxBool(false);
|
|
final focusMenuParagraph = RxBool(false);
|
|
final menuFontStatus = DropdownMenuFontStatus.closed.obs;
|
|
final menuHeaderStyleStatus = DropdownMenuFontStatus.closed.obs;
|
|
final formattingOptionsState = FormattingOptionsState.disabled.obs;
|
|
|
|
final menuParagraphController = CustomPopupMenuController();
|
|
final menuOrderListController = CustomPopupMenuController();
|
|
|
|
// Only reassert focus on the editor when something OTHER than the editor
|
|
// itself genuinely holds Flutter focus right now (e.g. a real toolbar
|
|
// button's own FocusNode). `FocusScopeNode`s (root scope, Navigator scope,
|
|
// modal route scope, etc.) are just ambient focus-tree scaffolding, not a
|
|
// real focused widget. This matters here because onEditorSettingsChange/
|
|
// onEditorTextSizeChanged are wired to the package's native
|
|
// `document.onselectionchange`/`summernote.mouseup` events, which fire on
|
|
// any selection change or mouseup already inside the editor (including
|
|
// our own drive-card delete overlay's own selection manipulation) — i.e.
|
|
// the editor already has focus in the common case, so calling
|
|
// editorController.setFocus() unconditionally there created a
|
|
// near-continuous stream of redundant async round-trips that could
|
|
// resolve later, at an unrelated moment, causing an un-prevented native
|
|
// re-focus/scroll-jump.
|
|
void _reclaimFocusIfDivertedElsewhere() {
|
|
final primaryFocus = FocusManager.instance.primaryFocus;
|
|
if (primaryFocus != null && primaryFocus is! FocusScopeNode) {
|
|
editorController.setFocus();
|
|
}
|
|
}
|
|
|
|
@override
|
|
void onReady() {
|
|
super.onReady();
|
|
menuParagraphController.addListener(() {
|
|
focusMenuParagraph.value = menuParagraphController.menuIsShowing;
|
|
});
|
|
menuOrderListController.addListener(() {
|
|
focusMenuOrderList.value = menuOrderListController.menuIsShowing;
|
|
});
|
|
}
|
|
|
|
void onEditorSettingsChange(EditorSettings settings) {
|
|
_updateTextStyle(settings);
|
|
_updateFontName(settings);
|
|
_updateTextColor(settings);
|
|
_updateBackgroundTextColor(settings);
|
|
_updateOrderList(settings);
|
|
_updateParagraph(settings);
|
|
_reclaimFocusIfDivertedElsewhere();
|
|
}
|
|
|
|
void onEditorTextSizeChanged(int? size) {
|
|
_updateFontSize(size);
|
|
_reclaimFocusIfDivertedElsewhere();
|
|
}
|
|
|
|
void _updateTextStyle(EditorSettings settings) {
|
|
listTextStyleApply.clear();
|
|
|
|
if (settings.isBold) {
|
|
listTextStyleApply.add(RichTextStyleType.bold);
|
|
}
|
|
|
|
if (settings.isItalic) {
|
|
listTextStyleApply.add(RichTextStyleType.italic);
|
|
}
|
|
|
|
if (settings.isUnderline) {
|
|
listTextStyleApply.add(RichTextStyleType.underline);
|
|
}
|
|
|
|
if (settings.isStrikethrough) {
|
|
listTextStyleApply.add(RichTextStyleType.strikeThrough);
|
|
}
|
|
|
|
log('RichTextWebController::_updateTextStyle(): $listTextStyleApply');
|
|
}
|
|
|
|
void _updateFontName(EditorSettings settings) {
|
|
log('RichTextWebController::_updateFontName():fontName: ${settings.fontName}');
|
|
final matchedFontName = FontNameType.values.firstWhereOrNull((fontName) => fontName.value == settings.fontName);
|
|
log('RichTextWebController::_updateFontName():matchedFontName: $matchedFontName');
|
|
if (matchedFontName != null) {
|
|
selectedFontName.value = matchedFontName;
|
|
}
|
|
}
|
|
|
|
void _updateFontSize(int? size) {
|
|
log('RichTextWebController::_updateFontSize():size: $size');
|
|
if (size != null && fontSizeList.contains(size)) {
|
|
selectedFontSize.value = size;
|
|
}
|
|
}
|
|
|
|
void _updateTextColor(EditorSettings settings) {
|
|
log('RichTextWebController::_updateTextColor():foregroundColor: ${settings.foregroundColor}');
|
|
selectedTextColor.value = settings.foregroundColor;
|
|
}
|
|
|
|
void _updateBackgroundTextColor(EditorSettings settings) {
|
|
log('RichTextWebController::_updateBackgroundTextColor():backgroundColor: ${settings.backgroundColor}');
|
|
selectedTextBackgroundColor.value = settings.backgroundColor;
|
|
}
|
|
|
|
void _updateOrderList(EditorSettings settings) {
|
|
if (settings.isOl) {
|
|
selectedOrderList.value = OrderListType.numberedList;
|
|
} else if (settings.isUl) {
|
|
selectedOrderList.value = OrderListType.bulletedList;
|
|
}
|
|
}
|
|
|
|
void _updateParagraph(EditorSettings settings) {
|
|
if (settings.isAlignCenter) {
|
|
selectedParagraph.value = ParagraphType.alignCenter;
|
|
} else if (settings.isAlignJustify) {
|
|
selectedParagraph.value = ParagraphType.justify;
|
|
} else if (settings.isAlignLeft) {
|
|
selectedParagraph.value = ParagraphType.alignLeft;
|
|
} else if (settings.isAlignRight) {
|
|
selectedParagraph.value = ParagraphType.alignRight;
|
|
}
|
|
}
|
|
|
|
void applyRichTextStyle(BuildContext context, RichTextStyleType textStyleType) {
|
|
switch(textStyleType) {
|
|
case RichTextStyleType.textColor:
|
|
ColorDialogPicker().showTwakeColorPicker(
|
|
context,
|
|
selectedTextColor.value,
|
|
onResetToDefault: () => _applyForegroundColor(Colors.black),
|
|
onSelectColor: _applyForegroundColor
|
|
);
|
|
break;
|
|
case RichTextStyleType.textBackgroundColor:
|
|
ColorDialogPicker().showTwakeColorPicker(
|
|
context,
|
|
selectedTextBackgroundColor.value,
|
|
onResetToDefault: () => applyBackgroundColor(Colors.white),
|
|
onSelectColor: applyBackgroundColor
|
|
);
|
|
break;
|
|
default:
|
|
editorController.execSummernoteAPI(textStyleType.summernoteNameAPI);
|
|
_selectTextStyleType(textStyleType);
|
|
break;
|
|
}
|
|
}
|
|
|
|
void _applyForegroundColor(Color? selectedColor) {
|
|
final newColor = selectedColor ?? Colors.black;
|
|
final colorAsString = newColor.toHexTriplet();
|
|
log('RichTextWebController::_applyForegroundColor():colorAsString: $colorAsString');
|
|
selectedTextColor.value = newColor;
|
|
editorController.execSummernoteAPI(
|
|
RichTextStyleType.textColor.summernoteNameAPI,
|
|
value: colorAsString);
|
|
}
|
|
|
|
void applyBackgroundColor(Color? selectedColor) {
|
|
final newColor = selectedColor ?? Colors.white;
|
|
final colorAsString = newColor.toHexTriplet();
|
|
log('RichTextWebController::_applyBackgroundColor():colorAsString: $colorAsString');
|
|
selectedTextBackgroundColor.value = newColor;
|
|
editorController.execSummernoteAPI(
|
|
RichTextStyleType.textBackgroundColor.summernoteNameAPI,
|
|
value: colorAsString);
|
|
}
|
|
|
|
void _selectTextStyleType(RichTextStyleType textStyleType) {
|
|
if (listTextStyleApply.contains(textStyleType)) {
|
|
listTextStyleApply.remove(textStyleType);
|
|
} else {
|
|
listTextStyleApply.add(textStyleType);
|
|
}
|
|
}
|
|
|
|
bool isTextStyleTypeSelected(RichTextStyleType richTextStyleType) =>
|
|
listTextStyleApply.contains(richTextStyleType);
|
|
|
|
void insertImage(InlineImage inlineImage) {
|
|
editorController.insertImage(
|
|
"<div>${inlineImage.base64Uri ?? ''}</div><br>",
|
|
);
|
|
}
|
|
|
|
void applyNewFontStyle(FontNameType? newFont) {
|
|
final fontSelected = newFont ?? FontNameType.sansSerif;
|
|
selectedFontName.value = fontSelected;
|
|
editorController.execSummernoteAPI(
|
|
RichTextStyleType.fontName.summernoteNameAPI,
|
|
value: fontSelected.value);
|
|
}
|
|
|
|
void applyNewFontSize(int? newSize) {
|
|
selectedFontSize.value = newSize ?? fontSizeDefault;
|
|
editorController.setFontSize(newSize ?? fontSizeDefault);
|
|
}
|
|
|
|
bool get isMenuFontOpen => menuFontStatus.value == DropdownMenuFontStatus.open;
|
|
|
|
bool get isMenuHeaderStyleOpen => menuHeaderStyleStatus.value == DropdownMenuFontStatus.open;
|
|
|
|
void _closeDropdownMenuFont() {
|
|
popBack();
|
|
}
|
|
|
|
void _closeDropdownMenuHeaderStyle() {
|
|
popBack();
|
|
}
|
|
|
|
bool get codeViewEnabled => codeViewState.value == CodeViewState.enabled;
|
|
|
|
Future<bool> get isActivatedCodeView => editorController.isActivatedCodeView();
|
|
|
|
bool _codeViewToggleInFlight = false;
|
|
|
|
bool get isCodeViewToggleInFlight => _codeViewToggleInFlight;
|
|
|
|
/// In code view, or leaving it: the editor HTML may still be raw.
|
|
bool get isCodeViewBusy => codeViewEnabled || _codeViewToggleInFlight;
|
|
|
|
void setEnableCodeView() async {
|
|
// Nothing to restore, and the editor's by-type reply could answer a later user toggle.
|
|
if (!codeViewEnabled) return;
|
|
final isActivated = await isActivatedCodeView;
|
|
if (codeViewEnabled && !isActivated) {
|
|
toggleCodeView();
|
|
}
|
|
}
|
|
|
|
void toggleCodeView() async {
|
|
if (_codeViewToggleInFlight) return;
|
|
_codeViewToggleInFlight = true;
|
|
try {
|
|
// The editor replies through window messages, which may never come back.
|
|
final isActivated = await isActivatedCodeView.timeout(_editorReplyTimeout);
|
|
if (isActivated) {
|
|
await _sanitizeAndLeaveCodeView();
|
|
} else {
|
|
codeViewState.value = CodeViewState.enabled;
|
|
editorController.toggleCodeView();
|
|
formattingOptionsState.value = FormattingOptionsState.disabled;
|
|
}
|
|
} catch (e, st) {
|
|
logError('RichTextWebController::toggleCodeView', exception: e, stackTrace: st);
|
|
_showCodeViewToggleError();
|
|
} finally {
|
|
_codeViewToggleInFlight = false;
|
|
}
|
|
}
|
|
|
|
// Throws before leaving code view when the HTML cannot be read (fail closed).
|
|
Future<void> _sanitizeAndLeaveCodeView() async {
|
|
final rawHtml = await editorController.getText().timeout(_editorReplyTimeout);
|
|
final sanitizedHtml = _codeViewSanitizer.sanitize(rawHtml);
|
|
// In code view, Summernote ignores an empty value and would keep the raw HTML.
|
|
editorController.setText(sanitizedHtml.trim().isEmpty ? _emptyEditorHtml : sanitizedHtml);
|
|
|
|
codeViewState.value = CodeViewState.disabled;
|
|
editorController.toggleCodeView();
|
|
editorController.evaluateJavascriptWeb(
|
|
HtmlUtils.recalculateEditorHeight().name,
|
|
);
|
|
}
|
|
|
|
void _showCodeViewToggleError() {
|
|
if (isClosed || !Get.isRegistered<AppToast>()) return;
|
|
final context = currentOverlayContext;
|
|
if (context == null) return;
|
|
Get.find<AppToast>().showToastErrorMessage(
|
|
context,
|
|
AppLocalizations.of(context).unknownError,
|
|
);
|
|
}
|
|
|
|
void applyHeaderStyle(HeaderStyleType? newStyle) {
|
|
final styleSelected = newStyle ?? HeaderStyleType.normal;
|
|
if (styleSelected == HeaderStyleType.blockquote || styleSelected == HeaderStyleType.code) {
|
|
editorController.execCommand(
|
|
RichTextStyleType.headerStyle.commandAction,
|
|
argument: styleSelected.styleValue);
|
|
editorController.setFocus();
|
|
} else {
|
|
editorController.execSummernoteAPI(styleSelected.summernoteNameAPI);
|
|
}
|
|
}
|
|
|
|
void applyParagraphType(ParagraphType newParagraph) {
|
|
selectedParagraph.value = newParagraph;
|
|
editorController.execSummernoteAPI(newParagraph.summernoteNameAPI);
|
|
menuParagraphController.hideMenu();
|
|
}
|
|
|
|
void closeAllMenuPopup() {
|
|
if (isMenuFontOpen) {
|
|
_closeDropdownMenuFont();
|
|
}
|
|
if (isMenuHeaderStyleOpen) {
|
|
_closeDropdownMenuHeaderStyle();
|
|
}
|
|
if (menuParagraphController.menuIsShowing) {
|
|
menuParagraphController.hideMenu();
|
|
}
|
|
if (menuOrderListController.menuIsShowing) {
|
|
menuOrderListController.hideMenu();
|
|
}
|
|
}
|
|
|
|
void applyOrderListType(OrderListType newOrderList) {
|
|
selectedOrderList.value = newOrderList;
|
|
editorController.execSummernoteAPI(newOrderList.summernoteNameAPI);
|
|
menuOrderListController.hideMenu();
|
|
}
|
|
|
|
Future<void> insertImageAsBase64({required FileInfo fileInfo, int? maxWidth}) async {
|
|
try {
|
|
final bytes = await fileInfo.readBytes();
|
|
if (bytes.isEmpty) {
|
|
logWarning("RichTextWebController::insertImageAsBase64: bytes is empty");
|
|
return;
|
|
}
|
|
final base64Data = base64Encode(bytes);
|
|
final mimeType = HtmlUtils.validateHtmlImageResourceMimeType('image/${fileInfo.fileExtension}');
|
|
editorController.insertHtml(buildInlineImageHtml(
|
|
base64Data: base64Data,
|
|
mimeType: mimeType,
|
|
fileName: fileInfo.fileName,
|
|
maxWidth: maxWidth,
|
|
));
|
|
} catch (e) {
|
|
logWarning('RichTextWebController::insertImageAsBase64:Exception: $e');
|
|
}
|
|
}
|
|
|
|
/// Builds the inline `<img>` tag inserted into the signature editor.
|
|
/// The file name and the MIME type derived from its extension come from the
|
|
/// user's local file picker and are attribute-escaped before being written
|
|
/// into the tag.
|
|
static String buildInlineImageHtml({
|
|
required String base64Data,
|
|
required String mimeType,
|
|
required String fileName,
|
|
int? maxWidth,
|
|
}) {
|
|
const attributeEscape = HtmlEscape(HtmlEscapeMode.attribute);
|
|
final escapedMimeType = attributeEscape.convert(mimeType);
|
|
return '<img src="${HtmlUtils.convertBase64ToImageResourceData(base64Data: base64Data, mimeType: escapedMimeType)}" data-filename="${attributeEscape.convert(fileName)}" alt="Image in my signature" style="max-width:${maxWidth != null ? '${maxWidth}px' : '100%'};" data-mimetype="$escapedMimeType"/>';
|
|
}
|
|
|
|
void toggleFormattingOptions() {
|
|
final newState = isFormattingOptionsEnabled
|
|
? FormattingOptionsState.disabled
|
|
: FormattingOptionsState.enabled;
|
|
|
|
formattingOptionsState.value = newState;
|
|
|
|
if (isFormattingOptionsEnabled) {
|
|
FocusManager.instance.primaryFocus?.unfocus();
|
|
editorController.setFocus();
|
|
}
|
|
}
|
|
|
|
void updateFormattingOptions(bool isDisplayed) {
|
|
formattingOptionsState.value = isDisplayed
|
|
? FormattingOptionsState.enabled
|
|
: FormattingOptionsState.disabled;
|
|
}
|
|
|
|
bool get isFormattingOptionsEnabled => formattingOptionsState.value == FormattingOptionsState.enabled;
|
|
|
|
void openInsertLink() {
|
|
FocusManager.instance.primaryFocus?.unfocus();
|
|
editorController.setFocus();
|
|
editorController.openInsertLinkDialog();
|
|
}
|
|
|
|
@override
|
|
void onClose() {
|
|
menuParagraphController.dispose();
|
|
menuOrderListController.dispose();
|
|
if (PlatformInfo.isWeb || editorController.editorController != null) {
|
|
editorController.clear();
|
|
}
|
|
super.onClose();
|
|
}
|
|
} |