Re-implemented signature page to support different signatures for different actions

This commit is contained in:
Aleh Khantsevich
2024-06-13 00:51:59 +02:00
parent 0ccf67000c
commit b54555a4f7
19 changed files with 1164 additions and 1303 deletions

View File

@@ -8,6 +8,10 @@ namespace Wino.Core.Domain.Entities
[PrimaryKey]
public Guid Id { get; set; }
public string Name { get; set; }
public string HtmlBody { get; set; }
public Guid MailAccountId { get; set; }
}
}

View File

@@ -44,12 +44,6 @@ namespace Wino.Core.Domain.Entities
/// </summary>
public string AccountColorHex { get; set; }
/// <summary>
/// Gets or sets the signature to be used for this account.
/// Null if no signature should be used.
/// </summary>
public Guid? SignatureId { get; set; }
/// <summary>
/// Gets or sets whether the account has any reason for an interactive user action to fix continue operating.
/// </summary>

View File

@@ -30,5 +30,20 @@ namespace Wino.Core.Domain.Entities
/// Null if the account provider type doesn't support Focused inbox.
/// </summary>
public bool? IsFocusedInboxEnabled { get; set; }
/// <summary>
/// Gets or sets whether signature should be appended automatically.
/// </summary>
public bool IsSignatureEnabled { get; set; }
/// <summary>
/// Gets or sets signature for new messages. Null if signature is not needed.
/// </summary>
public Guid? SignatureIdForNewMessages { get; set; }
/// <summary>
/// Gets or sets signature for following messages. Null if signature is not needed.
/// </summary>
public Guid? SignatureIdForFollowingMessages { get; set; }
}
}

View File

@@ -39,5 +39,11 @@ namespace Wino.Core.Domain.Interfaces
/// <param name="reason">The reason behind the picking operation
/// <returns>Selected folder structure. Null if none.</returns>
Task<IMailItemFolder> PickFolderAsync(Guid accountId, PickFolderReason reason, IFolderService folderService);
/// <summary>
/// Presents a dialog to the user for signature creation/modification.
/// </summary>
/// <returns>Signature information. Null if canceled.</returns>
Task<AccountSignature> ShowSignatureEditorDialog(AccountSignature signatureModel = null);
}
}

View File

@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Wino.Core.Domain.Entities;
@@ -7,27 +8,40 @@ namespace Wino.Core.Domain.Interfaces
public interface ISignatureService
{
/// <summary>
/// Returns the assigned account signature for the account.
/// Get one signature by Id.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
Task<AccountSignature> GetAccountSignatureAsync(Guid accountId);
/// <param name="signatureId">Signature Id.</param>
Task<AccountSignature> GetSignatureAsync(Guid signatureId);
/// <summary>
/// Creates the initial signature for new created accounts.
/// Returns all signatures for specified account.
/// </summary>
/// <param name="accountId"></param>
/// <returns></returns>
/// <param name="accountId">Account id</param>
Task<List<AccountSignature>> GetSignaturesAsync(Guid accountId);
/// <summary>
/// Creates a new signature for the account.
/// </summary>
/// <param name="signature">Signature that should be created. It should contain ID and account to which it belongs.</param>
Task<AccountSignature> CreateSignatureAsync(AccountSignature signature);
/// <summary>
/// Creates a default Wino signature for the account.
/// Needed only for initial account setup.
/// </summary>
/// <param name="accountId">Account Id.</param>
Task<AccountSignature> CreateDefaultSignatureAsync(Guid accountId);
/// <summary>
/// Updates account's existing signature with the given HTML signature.
/// Updates existing signature.
/// </summary>
Task<AccountSignature> UpdateAccountSignatureAsync(Guid accountId, string htmlBody);
/// <param name="signature">Signature that should be updated. It should contain ID and account to which it belongs.</param>
Task<AccountSignature> UpdateSignatureAsync(AccountSignature signature);
/// <summary>
/// Disabled signature for the account and deletes existing signature.
/// Deletes existing signature.
/// </summary>
Task DeleteAccountSignatureAssignment(Guid accountId);
/// <param name="signature">Signature that should be deleted.</param>
Task<AccountSignature> DeleteSignatureAsync(AccountSignature signature);
}
}

View File

@@ -28,6 +28,7 @@
"Buttons_Create": "Create",
"Buttons_CreateAccount": "Create Account",
"Buttons_Delete": "Delete",
"Buttons_Edit": "Edit",
"Buttons_Discard": "Discard",
"Buttons_EnableImageRendering": "Enable",
"Buttons_No": "No",
@@ -450,7 +451,7 @@
"SettingsShowSenderPictures_Title": "Show Sender Avatars",
"SettingsPrefer24HourClock_Title": "Display Clock Format in 24 Hours",
"SettingsPrefer24HourClock_Description": "Mail recieve times will be displayed in 24 hour format instead of 12 (AM/PM)",
"SettingsSignature_Description": "Edit or remove account signature",
"SettingsSignature_Description": "Manage account signatures",
"SettingsSignature_Title": "Signature",
"SettingsStartupItem_Description": "Primary account item to load Inbox at startup.",
"SettingsStartupItem_Title": "Startup Item",
@@ -493,5 +494,21 @@
"WinoUpgradeDescription": "Wino offers 3 accounts to start with for free. If you need more than 3 accounts, please upgrade",
"WinoUpgradeMessage": "Upgrade to Unlimited Accounts",
"WinoUpgradeRemainingAccountsMessage": "{0} out of {1} free accounts used.",
"Yesterday": "Yesterday"
"Yesterday": "Yesterday",
"SignatureEditorDialog_Title": "Signature Editor",
"SignatureEditorDialog_SignatureName_Placeholder": "Name your signature",
"SignatureEditorDialog_SignatureName_TitleNew": "Signature name",
"SignatureEditorDialog_SignatureName_TitleEdit": "Current signature name: {0}",
"SignatureDeleteDialog_Title": "Delete signature",
"SignatureDeleteDialog_Message": "Are you sure you want to delete \"{0}\" signature?",
"SettingsSignature_ForNewMessages_Title": "For New Messages",
"SettingsSignature_ForFollowingMessages_Title": "For Replies/Forwards",
"SettingsSignature_SignatureDefaults": "Signature defaults",
"SettingsSignature_Signatures": "Signatures",
"SettingsSignature_AddCustomSignature_Title": "Add custom signature",
"SettingsSignature_AddCustomSignature_Button": "Add signature",
"SettingsSignature_EditSignature_Title": "Edit signature",
"SettingsSignature_DeleteSignature_Title": "Delete signature",
"SettingsSignature_NoneSignatureName": "None"
}

File diff suppressed because it is too large Load Diff

View File

@@ -244,9 +244,7 @@ namespace Wino.Core.Services
await Connection.Table<TokenInformation>().Where(a => a.AccountId == account.Id).DeleteAsync();
await Connection.Table<MailItemFolder>().DeleteAsync(a => a.MailAccountId == account.Id);
if (account.SignatureId != null)
await Connection.Table<AccountSignature>().DeleteAsync(a => a.Id == account.SignatureId);
await Connection.Table<AccountSignature>().DeleteAsync(a => a.MailAccountId == account.Id);
// Account belongs to a merged inbox.
// In case of there'll be a single account in the merged inbox, remove the merged inbox as well.
@@ -355,12 +353,14 @@ namespace Wino.Core.Services
if (isMicrosoftProvider)
account.Preferences.IsFocusedInboxEnabled = true;
await Connection.InsertAsync(preferences);
// Create default signature.
// Setup default signature.
var defaultSignature = await _signatureService.CreateDefaultSignatureAsync(account.Id);
account.SignatureId = defaultSignature.Id;
account.Preferences.SignatureIdForNewMessages = defaultSignature.Id;
account.Preferences.SignatureIdForFollowingMessages = defaultSignature.Id;
account.Preferences.IsSignatureEnabled = true;
await Connection.InsertAsync(preferences);
if (customServerInformation != null)
await Connection.InsertAsync(customServerInformation);
@@ -397,7 +397,5 @@ namespace Wino.Core.Services
return account.SynchronizationDeltaIdentifier;
}
}
}

View File

@@ -673,16 +673,26 @@ namespace Wino.Core.Services
builder.HtmlBody = visitor.HtmlBody;
}
else
// Append signatures if needed.
if (account.Preferences.IsSignatureEnabled)
{
// Add signature if any.
var accountSignature = await _signatureService.GetAccountSignatureAsync(account.Id);
var signatureId = reason == DraftCreationReason.Empty ?
account.Preferences.SignatureIdForNewMessages :
account.Preferences.SignatureIdForFollowingMessages;
if (accountSignature != null)
if (signatureId != null)
{
// Leave some space for new mail content.
var signature = await _signatureService.GetSignatureAsync(signatureId.Value);
builder.HtmlBody = @$"<html><br><br>{accountSignature.HtmlBody}</html>";
if (string.IsNullOrWhiteSpace(builder.HtmlBody))
{
builder.HtmlBody = @$"<html><br><br>{signature.HtmlBody}</html>";
}
else
{
builder.HtmlBody += @$"{signature.HtmlBody}";
}
}
}
@@ -726,7 +736,7 @@ namespace Wino.Core.Services
message.Body = builder.ToMessageBody();
}
InternetAddressList ExtractRecipients(string parameterValue)
static InternetAddressList ExtractRecipients(string parameterValue)
{
var list = new InternetAddressList();

View File

@@ -1,91 +1,58 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Wino.Core.Domain.Entities;
using Wino.Core.Domain.Interfaces;
namespace Wino.Core.Services
{
public class SignatureService : BaseDatabaseService, ISignatureService
public class SignatureService(IDatabaseService databaseService) : BaseDatabaseService(databaseService), ISignatureService
{
public SignatureService(IDatabaseService databaseService) : base(databaseService) { }
public async Task<AccountSignature> CreateDefaultSignatureAsync(Guid accountId)
public async Task<AccountSignature> GetSignatureAsync(Guid signatureId)
{
var account = await Connection.Table<MailAccount>().FirstOrDefaultAsync(a => a.Id == accountId);
var defaultSignature = GetDefaultSignature();
await Connection.InsertAsync(defaultSignature);
account.SignatureId = defaultSignature.Id;
await Connection.UpdateAsync(account);
return defaultSignature;
return await Connection.Table<AccountSignature>().FirstAsync(s => s.Id == signatureId);
}
public async Task DeleteAccountSignatureAssignment(Guid accountId)
public async Task<List<AccountSignature>> GetSignaturesAsync(Guid accountId)
{
var existingSignature = await GetAccountSignatureAsync(accountId);
if (existingSignature != null)
{
await Connection.DeleteAsync(existingSignature);
var account = await Connection.Table<MailAccount>().FirstOrDefaultAsync(a => a.Id == accountId);
account.SignatureId = null;
await Connection.UpdateAsync(account);
}
return await Connection.Table<AccountSignature>().Where(s => s.MailAccountId == accountId).ToListAsync();
}
public async Task<AccountSignature> GetAccountSignatureAsync(Guid accountId)
public async Task<AccountSignature> CreateSignatureAsync(AccountSignature signature)
{
var account = await Connection.Table<MailAccount>().FirstOrDefaultAsync(a => a.Id == accountId);
if (account?.SignatureId == null)
return null;
return await Connection.Table<AccountSignature>().FirstOrDefaultAsync(a => a.Id == account.SignatureId);
}
public async Task<AccountSignature> UpdateAccountSignatureAsync(Guid accountId, string htmlBody)
{
var signature = await GetAccountSignatureAsync(accountId);
var account = await Connection.Table<MailAccount>().FirstOrDefaultAsync(a => a.Id == accountId);
if (signature == null)
{
signature = new AccountSignature()
{
Id = Guid.NewGuid(),
HtmlBody = htmlBody
};
await Connection.InsertAsync(signature);
}
else
{
signature.HtmlBody = htmlBody;
await Connection.UpdateAsync(signature);
}
account.SignatureId = signature.Id;
await Connection.UpdateAsync(account);
await Connection.InsertAsync(signature);
return signature;
}
private AccountSignature GetDefaultSignature()
public async Task<AccountSignature> CreateDefaultSignatureAsync(Guid accountId)
{
return new AccountSignature()
var defaultSignature = new AccountSignature()
{
Id = Guid.NewGuid(),
MailAccountId = accountId,
// TODO: Should be translated?
Name = "Wino Default Signature",
HtmlBody = @"<p>Sent from <a href=""https://github.com/bkaankose/Wino-Mail/"">Wino Mail</a> for Windows</p>"
};
await Connection.InsertAsync(defaultSignature);
return defaultSignature;
}
public async Task<AccountSignature> UpdateSignatureAsync(AccountSignature signature)
{
await Connection.UpdateAsync(signature);
return signature;
}
public async Task<AccountSignature> DeleteSignatureAsync(AccountSignature signature)
{
await Connection.DeleteAsync(signature);
return signature;
}
}
}

View File

@@ -24,7 +24,7 @@ namespace Wino.Mail.ViewModels
private readonly IFolderService _folderService;
public MailAccount Account { get; set; }
public ObservableCollection<IMailItemFolder> CurrentFolders { get; set; } = new ObservableCollection<IMailItemFolder>();
public ObservableCollection<IMailItemFolder> CurrentFolders { get; set; } = [];
[ObservableProperty]
private bool isFocusedInboxEnabled;
@@ -32,6 +32,9 @@ namespace Wino.Mail.ViewModels
[ObservableProperty]
private bool areNotificationsEnabled;
[ObservableProperty]
private bool isSignatureEnabled;
[ObservableProperty]
private bool isAppendMessageSettingVisible;
@@ -116,6 +119,7 @@ namespace Wino.Mail.ViewModels
IsFocusedInboxEnabled = Account.Preferences.IsFocusedInboxEnabled.GetValueOrDefault();
AreNotificationsEnabled = Account.Preferences.IsNotificationsEnabled;
IsSignatureEnabled = Account.Preferences.IsSignatureEnabled;
IsAppendMessageSettingVisible = Account.ProviderType == MailProviderType.IMAP4;
IsAppendMessageSettinEnabled = Account.Preferences.ShouldAppendMessagesToSentFolder;
@@ -135,23 +139,24 @@ namespace Wino.Mail.ViewModels
{
base.OnPropertyChanged(e);
if (e.PropertyName == nameof(IsFocusedInboxEnabled) && IsFocusedInboxSupportedForAccount)
switch (e.PropertyName)
{
Account.Preferences.IsFocusedInboxEnabled = IsFocusedInboxEnabled;
await _accountService.UpdateAccountAsync(Account);
}
else if (e.PropertyName == nameof(AreNotificationsEnabled))
{
Account.Preferences.IsNotificationsEnabled = AreNotificationsEnabled;
await _accountService.UpdateAccountAsync(Account);
}
else if (e.PropertyName == nameof(IsAppendMessageSettinEnabled))
{
Account.Preferences.ShouldAppendMessagesToSentFolder = IsAppendMessageSettinEnabled;
await _accountService.UpdateAccountAsync(Account);
case nameof(IsFocusedInboxEnabled) when IsFocusedInboxSupportedForAccount:
Account.Preferences.IsFocusedInboxEnabled = IsFocusedInboxEnabled;
await _accountService.UpdateAccountAsync(Account);
break;
case nameof(AreNotificationsEnabled):
Account.Preferences.IsNotificationsEnabled = AreNotificationsEnabled;
await _accountService.UpdateAccountAsync(Account);
break;
case nameof(IsAppendMessageSettinEnabled):
Account.Preferences.ShouldAppendMessagesToSentFolder = IsAppendMessageSettinEnabled;
await _accountService.UpdateAccountAsync(Account);
break;
case nameof(IsSignatureEnabled):
Account.Preferences.IsSignatureEnabled = IsSignatureEnabled;
await _accountService.UpdateAccountAsync(Account);
break;
}
}
}

View File

@@ -1,57 +1,71 @@
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using MoreLinq;
using MoreLinq.Extensions;
using Wino.Core.Domain;
using Wino.Core.Domain.Entities;
using Wino.Core.Domain.Enums;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Domain.Models.Navigation;
using Wino.Core.Domain.Models.Reader;
using Wino.Core.Messages.Mails;
namespace Wino.Mail.ViewModels
{
public partial class SignatureManagementPageViewModel : BaseViewModel
public partial class SignatureManagementPageViewModel(IDialogService dialogService,
ISignatureService signatureService,
IAccountService accountService) : BaseViewModel(dialogService)
{
public Func<Task<string>> GetHTMLBodyFunction;
public Func<Task<string>> GetTextBodyFunction;
public List<EditorToolbarSection> ToolbarSections { get; set; } = new List<EditorToolbarSection>()
{
new EditorToolbarSection(){ SectionType = EditorToolbarSectionType.Format },
new EditorToolbarSection(){ SectionType = EditorToolbarSectionType.Insert },
};
[ObservableProperty]
private EditorToolbarSection selectedToolbarSection;
public ObservableCollection<AccountSignature> Signatures { get; set; } = [];
[ObservableProperty]
private bool isSignatureEnabled;
public MailAccount Account { get; set; }
private int signatureForNewMessagesIndex;
public AsyncRelayCommand SaveSignatureCommand { get; set; }
public Guid EmptyGuid { get; } = Guid.Empty;
public INativeAppService NativeAppService { get; }
private readonly ISignatureService _signatureService;
private readonly IAccountService _accountService;
public SignatureManagementPageViewModel(IDialogService dialogService,
INativeAppService nativeAppService,
ISignatureService signatureService,
IAccountService accountService) : base(dialogService)
public int SignatureForNewMessagesIndex
{
SelectedToolbarSection = ToolbarSections[0];
NativeAppService = nativeAppService;
_signatureService = signatureService;
_accountService = accountService;
SaveSignatureCommand = new AsyncRelayCommand(SaveSignatureAsync);
get => signatureForNewMessagesIndex;
set
{
if (value == -1)
{
SetProperty(ref signatureForNewMessagesIndex, 0);
}
else
{
SetProperty(ref signatureForNewMessagesIndex, value);
}
}
}
private int signatureForFollowingMessagesIndex;
public int SignatureForFollowingMessagesIndex
{
get => signatureForFollowingMessagesIndex;
set
{
if (value == -1)
{
SetProperty(ref signatureForFollowingMessagesIndex, 0);
}
else
{
SetProperty(ref signatureForFollowingMessagesIndex, value);
}
}
}
private MailAccount Account { get; set; }
private readonly ISignatureService _signatureService = signatureService;
private readonly IAccountService _accountService = accountService;
public override async void OnNavigatedTo(NavigationMode mode, object parameters)
{
base.OnNavigatedTo(mode, parameters);
@@ -59,35 +73,89 @@ namespace Wino.Mail.ViewModels
if (parameters is Guid accountId)
Account = await _accountService.GetAccountAsync(accountId);
if (Account != null)
if (Account == null) return;
var dbSignatures = await _signatureService.GetSignaturesAsync(Account.Id);
IsSignatureEnabled = Account.Preferences.IsSignatureEnabled;
Signatures.Clear();
Signatures.Add(new AccountSignature { Id = EmptyGuid, Name = Translator.SettingsSignature_NoneSignatureName });
dbSignatures.ForEach(Signatures.Add);
SignatureForNewMessagesIndex = Signatures.IndexOf(Signatures.FirstOrDefault(x => x.Id == Account.Preferences.SignatureIdForNewMessages));
SignatureForFollowingMessagesIndex = Signatures.IndexOf(Signatures.FirstOrDefault(x => x.Id == Account.Preferences.SignatureIdForFollowingMessages));
}
protected override async void OnPropertyChanged(PropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
switch (e.PropertyName)
{
var accountSignature = await _signatureService.GetAccountSignatureAsync(Account.Id);
IsSignatureEnabled = accountSignature != null;
if (IsSignatureEnabled)
Messenger.Send(new HtmlRenderingRequested(accountSignature.HtmlBody));
else
Messenger.Send(new HtmlRenderingRequested(string.Empty)); // To get the theme changes. Render empty html.
case nameof(IsSignatureEnabled):
Account.Preferences.IsSignatureEnabled = IsSignatureEnabled;
await _accountService.UpdateAccountAsync(Account);
break;
case nameof(SignatureForNewMessagesIndex):
Account.Preferences.SignatureIdForNewMessages = SignatureForNewMessagesIndex > -1
&& Signatures[SignatureForNewMessagesIndex].Id != EmptyGuid
? Signatures[SignatureForNewMessagesIndex].Id : null;
await _accountService.UpdateAccountAsync(Account);
break;
case nameof(SignatureForFollowingMessagesIndex):
Account.Preferences.SignatureIdForFollowingMessages = SignatureForFollowingMessagesIndex > -1
&& Signatures[SignatureForFollowingMessagesIndex].Id != EmptyGuid
? Signatures[SignatureForFollowingMessagesIndex].Id : null;
await _accountService.UpdateAccountAsync(Account);
break;
}
}
private async Task SaveSignatureAsync()
[RelayCommand]
private async Task OpenSignatureEditorCreateAsync()
{
if (IsSignatureEnabled)
{
var newSignature = Regex.Unescape(await GetHTMLBodyFunction());
var dialogResult = await DialogService.ShowSignatureEditorDialog();
await _signatureService.UpdateAccountSignatureAsync(Account.Id, newSignature);
if (dialogResult == null) return;
DialogService.InfoBarMessage(Translator.Info_SignatureSavedTitle, Translator.Info_SignatureSavedMessage, Core.Domain.Enums.InfoBarMessageType.Success);
}
else
{
await _signatureService.DeleteAccountSignatureAssignment(Account.Id);
dialogResult.MailAccountId = Account.Id;
Signatures.Add(dialogResult);
await _signatureService.CreateSignatureAsync(dialogResult);
}
DialogService.InfoBarMessage(Translator.Info_SignatureDisabledTitle, Translator.Info_SignatureDisabledMessage, Core.Domain.Enums.InfoBarMessageType.Success);
}
[RelayCommand]
private async Task OpenSignatureEditorEditAsync(AccountSignature signatureModel)
{
var dialogResult = await DialogService.ShowSignatureEditorDialog(signatureModel);
if (dialogResult == null) return;
var indexOfCurrentSignature = Signatures.IndexOf(signatureModel);
var signatureNewMessagesIndex = SignatureForNewMessagesIndex;
var signatureFollowingMessagesIndex = SignatureForFollowingMessagesIndex;
Signatures[indexOfCurrentSignature] = dialogResult;
// Reset selection to point updated signature.
// When Item updated/removed index switches to -1. We save index that was used before and update -1 to it.
if (signatureNewMessagesIndex == indexOfCurrentSignature)
SignatureForNewMessagesIndex = indexOfCurrentSignature;
if (signatureFollowingMessagesIndex == indexOfCurrentSignature)
SignatureForFollowingMessagesIndex = indexOfCurrentSignature;
await _signatureService.UpdateSignatureAsync(dialogResult);
}
[RelayCommand]
private async Task RemoveSignatureAsync(AccountSignature signatureModel)
{
var dialogResult = await DialogService.ShowConfirmationDialogAsync(string.Format(Translator.SignatureDeleteDialog_Message, signatureModel.Name), Translator.SignatureDeleteDialog_Title, Translator.Buttons_Delete);
if (!dialogResult) return;
Signatures.Remove(signatureModel);
await _signatureService.DeleteSignatureAsync(signatureModel);
}
}
}

View File

@@ -0,0 +1,266 @@
<ContentDialog
x:Class="Wino.Dialogs.SignatureEditorDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:accounts="using:Wino.Core.Domain.Models.Accounts"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:domain="using:Wino.Core.Domain"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:muxc="using:Microsoft.UI.Xaml.Controls"
Title="{x:Bind domain:Translator.SignatureEditorDialog_Title}"
HorizontalContentAlignment="Stretch"
Closed="DialogClosed"
DefaultButton="Primary"
IsPrimaryButtonEnabled="False"
Opened="SignatureDialogOpened"
PrimaryButtonClick="SaveClicked"
PrimaryButtonText="{x:Bind domain:Translator.Buttons_Save}"
SecondaryButtonClick="CancelClicked"
SecondaryButtonText="{x:Bind domain:Translator.Buttons_Cancel}"
Style="{StaticResource WinoDialogStyle}"
mc:Ignorable="d">
<ContentDialog.Resources>
<x:Double x:Key="ContentDialogMaxWidth">1200</x:Double>
</ContentDialog.Resources>
<Grid Margin="0,20,0,0" RowSpacing="30">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="400" />
</Grid.RowDefinitions>
<TextBox
x:Name="SignatureNameTextBox"
MinWidth="300"
MaxWidth="500"
HorizontalAlignment="Left"
Header="{x:Bind SignatureNameHeader}"
PlaceholderText="{x:Bind domain:Translator.SignatureEditorDialog_SignatureName_Placeholder}"
TextChanged="SignatureNameTextBoxTextChanged" />
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="500" />
</Grid.RowDefinitions>
<CommandBar
Grid.Row="0"
HorizontalAlignment="Left"
Background="Transparent"
DefaultLabelPosition="Collapsed"
IsOpen="False">
<AppBarButton
x:Name="BoldButton"
Width="48"
Click="BoldButtonClicked"
Label="Bold"
ToolTipService.ToolTip="Bold">
<AppBarButton.Icon>
<PathIcon Data="{StaticResource BoldPathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton
x:Name="ItalicButton"
Width="48"
Click="ItalicButtonClicked"
Label="Italic"
ToolTipService.ToolTip="Italic">
<AppBarButton.Icon>
<PathIcon Data="{StaticResource ItalicPathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton
x:Name="UnderlineButton"
Width="48"
Click="UnderlineButtonClicked"
Label="Underline"
ToolTipService.ToolTip="Underline">
<AppBarButton.Icon>
<PathIcon Data="{StaticResource UnderlinePathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton
x:Name="StrokeButton"
Width="48"
Click="StrokeButtonClicked"
Label="Stroke"
ToolTipService.ToolTip="Stroke">
<AppBarButton.Icon>
<PathIcon Data="{StaticResource StrikePathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
<AppBarSeparator />
<AppBarToggleButton
x:Name="BulletListButton"
Width="48"
Click="BulletListButtonClicked"
Label="Stroke"
ToolTipService.ToolTip="Stroke">
<AppBarToggleButton.Icon>
<PathIcon Data="{StaticResource BulletedListPathIcon}" />
</AppBarToggleButton.Icon>
</AppBarToggleButton>
<AppBarToggleButton
x:Name="OrderedListButton"
Width="48"
Click="OrderedListButtonClicked"
Label="Stroke"
ToolTipService.ToolTip="Stroke">
<AppBarToggleButton.Icon>
<PathIcon Data="{StaticResource OrderedListPathIcon}" />
</AppBarToggleButton.Icon>
</AppBarToggleButton>
<AppBarButton
x:Name="DecreaseIndentButton"
Width="48"
Click="DecreaseIndentClicked"
Label="Stroke"
ToolTipService.ToolTip="Stroke">
<AppBarButton.Icon>
<PathIcon Data="{StaticResource DecreaseIndentPathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton
x:Name="IncreaseIndentButton"
Width="48"
Click="IncreaseIndentClicked"
Label="Stroke"
ToolTipService.ToolTip="Stroke">
<AppBarButton.Icon>
<PathIcon Data="{StaticResource IncreaseIndentPathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
<AppBarSeparator />
<AppBarToggleButton
x:Name="DirectionButton"
Width="48"
Click="DirectionButtonClicked">
<AppBarToggleButton.Icon>
<PathIcon Data="{StaticResource ParagraphPathIcon}" />
</AppBarToggleButton.Icon>
</AppBarToggleButton>
<AppBarElementContainer VerticalAlignment="Center">
<ComboBox x:Name="AlignmentListView" SelectionChanged="AlignmentChanged">
<ComboBoxItem Tag="left">
<StackPanel Orientation="Horizontal" Spacing="8">
<Viewbox Width="16">
<PathIcon Data="{StaticResource AlignLeftPathIcon}" />
</Viewbox>
<TextBlock VerticalAlignment="Center" Text="{x:Bind domain:Translator.Left}" />
</StackPanel>
</ComboBoxItem>
<ComboBoxItem Tag="center">
<StackPanel Orientation="Horizontal" Spacing="8">
<Viewbox Width="16">
<PathIcon Data="{StaticResource AlignCenterPathIcon}" />
</Viewbox>
<TextBlock VerticalAlignment="Center" Text="{x:Bind domain:Translator.Center}" />
</StackPanel>
</ComboBoxItem>
<ComboBoxItem Tag="right">
<StackPanel Orientation="Horizontal" Spacing="8">
<Viewbox Width="16">
<PathIcon Data="{StaticResource AlignRightPathIcon}" />
</Viewbox>
<TextBlock VerticalAlignment="Center" Text="{x:Bind domain:Translator.Right}" />
</StackPanel>
</ComboBoxItem>
<ComboBoxItem Tag="justify">
<StackPanel Orientation="Horizontal" Spacing="8">
<Viewbox Width="16">
<PathIcon Data="{StaticResource AlignJustifyPathIcon}" />
</Viewbox>
<TextBlock VerticalAlignment="Center" Text="{x:Bind domain:Translator.Justify}" />
</StackPanel>
</ComboBoxItem>
</ComboBox>
</AppBarElementContainer>
<AppBarSeparator />
<AppBarButton
x:Name="AddImageButton"
Width="48"
Click="AddImageClicked"
ToolTipService.ToolTip="Add Image">
<AppBarButton.Icon>
<PathIcon Data="{StaticResource AddPhotoPathIcon}" />
</AppBarButton.Icon>
<AppBarButton.Content>
<StackPanel Orientation="Horizontal" Spacing="8">
<Viewbox Width="16" VerticalAlignment="Center">
<PathIcon Data="{StaticResource AddPhotoPathIcon}" />
</Viewbox>
<TextBlock Text="{x:Bind domain:Translator.Photos}" />
</StackPanel>
</AppBarButton.Content>
</AppBarButton>
<AppBarButton
x:Name="EmojiButton"
Width="48"
Click="EmojiButtonClicked"
ToolTipService.ToolTip="Add Emoji">
<AppBarButton.Content>
<StackPanel Orientation="Horizontal" Spacing="8">
<Viewbox Width="16" VerticalAlignment="Center">
<PathIcon Data="{StaticResource EmojiPathIcon}" />
</Viewbox>
<TextBlock Text="{x:Bind domain:Translator.Emoji}" />
</StackPanel>
</AppBarButton.Content>
<AppBarButton.Icon>
<PathIcon Data="{StaticResource EmojiPathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
<AppBarButton
x:Name="LinkButton"
Width="48"
Click="HyperlinkAddClicked"
Label="Add Link"
ToolTipService.ToolTip="Add Link">
<AppBarButton.Flyout>
<Flyout x:Name="HyperlinkFlyout">
<StackPanel Width="250" Spacing="6">
<TextBox x:Name="HyperlinkTextBox" Header="Text" />
<TextBox
x:Name="LinkUrlTextBox"
Header="Link"
PlaceholderText="https://" />
<Button
x:Name="AddHyperlinkButton"
Margin="0,6"
HorizontalAlignment="Stretch"
Click="HyperlinkAddClicked"
Content="{x:Bind domain:Translator.AddHyperlink}" />
</StackPanel>
</Flyout>
</AppBarButton.Flyout>
<AppBarButton.Content>
<StackPanel Orientation="Horizontal" Spacing="8">
<Viewbox Width="16" VerticalAlignment="Center">
<PathIcon Data="{StaticResource AddLinkPathIcon}" />
</Viewbox>
<TextBlock Text="Link" />
</StackPanel>
</AppBarButton.Content>
<AppBarButton.Icon>
<PathIcon Data="{StaticResource AddLinkPathIcon}" />
</AppBarButton.Icon>
</AppBarButton>
</CommandBar>
<Grid Grid.Row="1" CornerRadius="10">
<muxc:WebView2
x:Name="Chromium"
Width="Auto"
Height="Auto"
BorderBrush="LightGray"
BorderThickness="1" />
</Grid>
</Grid>
</Grid>
</ContentDialog>

View File

@@ -0,0 +1,373 @@
using System;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Windows.UI.ViewManagement.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Wino.Core.Domain;
using Wino.Core.Domain.Entities;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Messages.Mails;
using Wino.Views.Settings;
namespace Wino.Dialogs
{
public sealed partial class SignatureEditorDialog : ContentDialog
{
private Func<Task<string>> _getHTMLBodyFunction;
private readonly TaskCompletionSource<bool> _domLoadedTask = new TaskCompletionSource<bool>();
private readonly INativeAppService _nativeAppService = App.Current.Services.GetService<INativeAppService>();
public string SignatureNameHeader { get; set; }
public AccountSignature Result;
public bool IsComposerDarkMode
{
get { return (bool)GetValue(IsComposerDarkModeProperty); }
set { SetValue(IsComposerDarkModeProperty, value); }
}
public static readonly DependencyProperty IsComposerDarkModeProperty = DependencyProperty.Register(nameof(IsComposerDarkMode), typeof(bool), typeof(SignatureManagementPage), new PropertyMetadata(false, OnIsComposerDarkModeChanged));
public SignatureEditorDialog()
{
InitializeComponent();
SignatureNameHeader = Translator.SignatureEditorDialog_SignatureName_TitleNew;
Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--enable-features=OverlayScrollbar,OverlayScrollbarWinStyle,OverlayScrollbarWinStyleAnimation");
// TODO: Should be added additional logic to enable/disable primary button when webview content changed.
IsPrimaryButtonEnabled = true;
}
public SignatureEditorDialog(AccountSignature signatureModel)
{
InitializeComponent();
SignatureNameHeader = string.Format(Translator.SignatureEditorDialog_SignatureName_TitleEdit, signatureModel.Name);
Result = new AccountSignature
{
Id = signatureModel.Id,
Name = signatureModel.Name,
MailAccountId = signatureModel.MailAccountId,
HtmlBody = signatureModel.HtmlBody
};
Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--enable-features=OverlayScrollbar,OverlayScrollbarWinStyle,OverlayScrollbarWinStyleAnimation");
// TODO: Should be added additional logic to enable/disable primary button when webview content changed.
IsPrimaryButtonEnabled = true;
}
private async void SignatureDialogOpened(ContentDialog sender, ContentDialogOpenedEventArgs args)
{
Chromium.CoreWebView2Initialized -= ChromiumInitialized;
Chromium.CoreWebView2Initialized += ChromiumInitialized;
await Chromium.EnsureCoreWebView2Async();
_getHTMLBodyFunction = new Func<Task<string>>(async () =>
{
var quillContent = await InvokeScriptSafeAsync("GetHTMLContent();");
return JsonConvert.DeserializeObject<string>(quillContent);
});
var underlyingThemeService = App.Current.Services.GetService<IUnderlyingThemeService>();
IsComposerDarkMode = underlyingThemeService.IsUnderlyingThemeDark();
await RenderInternalAsync(Result?.HtmlBody ?? string.Empty);
}
private void DialogClosed(ContentDialog sender, ContentDialogClosedEventArgs args)
{
Chromium.CoreWebView2Initialized -= ChromiumInitialized;
if (Chromium.CoreWebView2 != null)
{
Chromium.CoreWebView2.DOMContentLoaded -= DOMLoaded;
Chromium.CoreWebView2.WebMessageReceived -= ScriptMessageRecieved;
}
}
private async void SaveClicked(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
var newSignature = Regex.Unescape(await _getHTMLBodyFunction());
if (Result == null)
{
Result = new AccountSignature
{
Id = Guid.NewGuid(),
Name = SignatureNameTextBox.Text.Trim(),
HtmlBody = newSignature
};
}
else
{
Result.Name = SignatureNameTextBox.Text.Trim();
Result.HtmlBody = newSignature;
}
Hide();
}
private void CancelClicked(ContentDialog sender, ContentDialogButtonClickEventArgs args)
{
Hide();
}
private async void HyperlinkAddClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync($"addHyperlink('{LinkUrlTextBox.Text}')");
LinkUrlTextBox.Text = string.Empty;
HyperlinkFlyout.Hide();
}
private async void BoldButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('boldButton').click();");
}
private async void ItalicButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('italicButton').click();");
}
private async void UnderlineButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('underlineButton').click();");
}
private async void StrokeButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('strikeButton').click();");
}
private async void BulletListButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('bulletListButton').click();");
}
private async void OrderedListButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('orderedListButton').click();");
}
private async void IncreaseIndentClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('increaseIndentButton').click();");
}
private async void DecreaseIndentClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('decreaseIndentButton').click();");
}
private async void DirectionButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('directionButton').click();");
}
private async void AlignmentChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = AlignmentListView.SelectedItem as ComboBoxItem;
var alignment = selectedItem.Tag.ToString();
switch (alignment)
{
case "left":
await InvokeScriptSafeAsync("document.getElementById('ql-align-left').click();");
break;
case "center":
await InvokeScriptSafeAsync("document.getElementById('ql-align-center').click();");
break;
case "right":
await InvokeScriptSafeAsync("document.getElementById('ql-align-right').click();");
break;
case "justify":
await InvokeScriptSafeAsync("document.getElementById('ql-align-justify').click();");
break;
}
}
public async Task<string> ExecuteScriptFunctionAsync(string functionName, params object[] parameters)
{
string script = functionName + "(";
for (int i = 0; i < parameters.Length; i++)
{
script += JsonConvert.SerializeObject(parameters[i]);
if (i < parameters.Length - 1)
{
script += ", ";
}
}
script += ");";
return await Chromium.ExecuteScriptAsync(script);
}
private async Task<string> InvokeScriptSafeAsync(string function)
{
try
{
return await Chromium.ExecuteScriptAsync(function);
}
catch { }
return string.Empty;
}
private async void AddImageClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('addImageButton').click();");
}
private async Task FocusEditorAsync()
{
await InvokeScriptSafeAsync("quill.focus();");
Chromium.Focus(FocusState.Keyboard);
Chromium.Focus(FocusState.Programmatic);
}
private async void EmojiButtonClicked(object sender, RoutedEventArgs e)
{
CoreInputView.GetForCurrentView().TryShow(CoreInputViewKind.Emoji);
await FocusEditorAsync();
}
private async Task<string> TryGetSelectedTextAsync()
{
try
{
return await Chromium.ExecuteScriptAsync("getSelectedText();");
}
catch { }
return string.Empty;
}
private async void LinkButtonClicked(object sender, RoutedEventArgs e)
{
// Get selected text from Quill.
HyperlinkTextBox.Text = await TryGetSelectedTextAsync();
}
private async Task UpdateEditorThemeAsync()
{
await _domLoadedTask.Task;
if (IsComposerDarkMode)
{
await InvokeScriptSafeAsync("DarkReader.enable();");
}
else
{
await InvokeScriptSafeAsync("DarkReader.disable();");
}
}
private async Task RenderInternalAsync(string htmlBody)
{
await _domLoadedTask.Task;
await UpdateEditorThemeAsync();
if (string.IsNullOrEmpty(htmlBody))
{
await ExecuteScriptFunctionAsync("RenderHTML", " ");
}
else
{
await ExecuteScriptFunctionAsync("RenderHTML", htmlBody);
await FocusEditorAsync();
}
}
private async void ChromiumInitialized(Microsoft.UI.Xaml.Controls.WebView2 sender, Microsoft.UI.Xaml.Controls.CoreWebView2InitializedEventArgs args)
{
var editorBundlePath = (await _nativeAppService.GetQuillEditorBundlePathAsync()).Replace("full.html", string.Empty);
Chromium.CoreWebView2.SetVirtualHostNameToFolderMapping("app.example", editorBundlePath, CoreWebView2HostResourceAccessKind.Allow);
Chromium.Source = new Uri("https://app.example/full.html");
Chromium.CoreWebView2.DOMContentLoaded -= DOMLoaded;
Chromium.CoreWebView2.DOMContentLoaded += DOMLoaded;
Chromium.CoreWebView2.WebMessageReceived -= ScriptMessageRecieved;
Chromium.CoreWebView2.WebMessageReceived += ScriptMessageRecieved;
}
private static async void OnIsComposerDarkModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
//if (obj is ComposePage page)
//{
// await page.UpdateEditorThemeAsync();
//}
}
private void ScriptMessageRecieved(CoreWebView2 sender, CoreWebView2WebMessageReceivedEventArgs args)
{
var change = JsonConvert.DeserializeObject<string>(args.WebMessageAsJson);
bool isEnabled = change.EndsWith("ql-active");
if (change.StartsWith("ql-bold"))
BoldButton.IsFocusEngaged = isEnabled;
else if (change.StartsWith("ql-italic"))
ItalicButton.IsEnabled = isEnabled;
else if (change.StartsWith("ql-underline"))
UnderlineButton.IsEnabled = isEnabled;
else if (change.StartsWith("ql-strike"))
StrokeButton.IsEnabled = isEnabled;
else if (change.StartsWith("orderedListButton"))
OrderedListButton.IsChecked = isEnabled;
else if (change.StartsWith("bulletListButton"))
BulletListButton.IsChecked = isEnabled;
else if (change.StartsWith("ql-direction"))
DirectionButton.IsChecked = isEnabled;
else if (change.StartsWith("ql-align-left"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 0;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
else if (change.StartsWith("ql-align-center"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 1;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
else if (change.StartsWith("ql-align-right"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 2;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
else if (change.StartsWith("ql-align-justify"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 3;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
}
private void DOMLoaded(CoreWebView2 sender, CoreWebView2DOMContentLoadedEventArgs args) => _domLoadedTask.TrySetResult(true);
public async void Receive(HtmlRenderingRequested message)
{
await RenderInternalAsync(message.HtmlBody);
}
private void SignatureNameTextBoxTextChanged(object sender, TextChangedEventArgs e) => IsPrimaryButtonEnabled = !string.IsNullOrWhiteSpace(SignatureNameTextBox.Text);
}
}

View File

@@ -331,6 +331,27 @@ namespace Wino.Services
return accountPicker.PickedAccount;
}
public async Task<AccountSignature> ShowSignatureEditorDialog(AccountSignature signatureModel = null)
{
SignatureEditorDialog signatureEditorDialog;
if (signatureModel != null)
{
signatureEditorDialog = new SignatureEditorDialog(signatureModel)
{
RequestedTheme = _themeService.RootTheme.ToWindowsElementTheme()
};
}
else
{
signatureEditorDialog = new SignatureEditorDialog()
{
RequestedTheme = _themeService.RootTheme.ToWindowsElementTheme()
};
}
var result = await HandleDialogPresentationAsync(signatureEditorDialog);
return result == ContentDialogResult.Primary ? signatureEditorDialog.Result : null;
}
}
}

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -1,320 +1,12 @@
using System;
using System.Threading.Tasks;
using CommunityToolkit.Mvvm.Messaging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Web.WebView2.Core;
using Newtonsoft.Json;
using Windows.UI.ViewManagement.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Wino.Core.Domain.Interfaces;
using Wino.Core.Messages.Mails;
using Wino.Views.Abstract;
using Wino.Views.Abstract;
namespace Wino.Views.Settings
{
public sealed partial class SignatureManagementPage : SignatureManagementPageAbstract, IRecipient<HtmlRenderingRequested>
public sealed partial class SignatureManagementPage : SignatureManagementPageAbstract
{
private TaskCompletionSource<bool> DOMLoadedTask = new TaskCompletionSource<bool>();
public bool IsComposerDarkMode
{
get { return (bool)GetValue(IsComposerDarkModeProperty); }
set { SetValue(IsComposerDarkModeProperty, value); }
}
public static readonly DependencyProperty IsComposerDarkModeProperty = DependencyProperty.Register(nameof(IsComposerDarkMode), typeof(bool), typeof(SignatureManagementPage), new PropertyMetadata(false, OnIsComposerDarkModeChanged));
public SignatureManagementPage()
{
this.InitializeComponent();
// Environment.SetEnvironmentVariable("WEBVIEW2_DEFAULT_BACKGROUND_COLOR", "00FFFFFF");
Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--enable-features=OverlayScrollbar,OverlayScrollbarWinStyle,OverlayScrollbarWinStyleAnimation");
}
protected override void OnNavigatedFrom(NavigationEventArgs e)
{
base.OnNavigatedFrom(e);
Chromium.CoreWebView2Initialized -= ChromiumInitialized;
if (Chromium.CoreWebView2 != null)
{
Chromium.CoreWebView2.DOMContentLoaded -= DOMLoaded;
Chromium.CoreWebView2.WebMessageReceived -= ScriptMessageRecieved;
}
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
Chromium.CoreWebView2Initialized -= ChromiumInitialized;
Chromium.CoreWebView2Initialized += ChromiumInitialized;
await Chromium.EnsureCoreWebView2Async();
ViewModel.GetHTMLBodyFunction = new Func<Task<string>>(async () =>
{
var quillContent = await InvokeScriptSafeAsync("GetHTMLContent();");
return JsonConvert.DeserializeObject<string>(quillContent);
});
ViewModel.GetTextBodyFunction = new Func<Task<string>>(() => InvokeScriptSafeAsync("GetTextContent();"));
var underlyingThemeService = App.Current.Services.GetService<IUnderlyingThemeService>();
IsComposerDarkMode = underlyingThemeService.IsUnderlyingThemeDark();
}
private async void HyperlinkAddClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync($"addHyperlink('{LinkUrlTextBox.Text}')");
LinkUrlTextBox.Text = string.Empty;
HyperlinkFlyout.Hide();
}
private async void BoldButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('boldButton').click();");
}
private async void ItalicButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('italicButton').click();");
}
private async void UnderlineButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('underlineButton').click();");
}
private async void StrokeButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('strikeButton').click();");
}
private async void BulletListButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('bulletListButton').click();");
}
private async void OrderedListButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('orderedListButton').click();");
}
private async void IncreaseIndentClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('increaseIndentButton').click();");
}
private async void DecreaseIndentClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('decreaseIndentButton').click();");
}
private async void DirectionButtonClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('directionButton').click();");
}
private async void AlignmentChanged(object sender, SelectionChangedEventArgs e)
{
var selectedItem = AlignmentListView.SelectedItem as ComboBoxItem;
var alignment = selectedItem.Tag.ToString();
switch (alignment)
{
case "left":
await InvokeScriptSafeAsync("document.getElementById('ql-align-left').click();");
break;
case "center":
await InvokeScriptSafeAsync("document.getElementById('ql-align-center').click();");
break;
case "right":
await InvokeScriptSafeAsync("document.getElementById('ql-align-right').click();");
break;
case "justify":
await InvokeScriptSafeAsync("document.getElementById('ql-align-justify').click();");
break;
}
}
public async Task<string> ExecuteScriptFunctionAsync(string functionName, params object[] parameters)
{
string script = functionName + "(";
for (int i = 0; i < parameters.Length; i++)
{
script += JsonConvert.SerializeObject(parameters[i]);
if (i < parameters.Length - 1)
{
script += ", ";
}
}
script += ");";
return await Chromium.ExecuteScriptAsync(script);
}
private async Task<string> InvokeScriptSafeAsync(string function)
{
try
{
return await Chromium.ExecuteScriptAsync(function);
}
catch (Exception) { }
return string.Empty;
}
private async void AddImageClicked(object sender, RoutedEventArgs e)
{
await InvokeScriptSafeAsync("document.getElementById('addImageButton').click();");
}
private async Task FocusEditorAsync()
{
await InvokeScriptSafeAsync("quill.focus();");
Chromium.Focus(FocusState.Keyboard);
Chromium.Focus(FocusState.Programmatic);
}
private async void EmojiButtonClicked(object sender, RoutedEventArgs e)
{
CoreInputView.GetForCurrentView().TryShow(CoreInputViewKind.Emoji);
await FocusEditorAsync();
}
private async Task<string> TryGetSelectedTextAsync()
{
try
{
return await Chromium.ExecuteScriptAsync("getSelectedText();");
}
catch (Exception) { }
return string.Empty;
}
private async void LinkButtonClicked(object sender, RoutedEventArgs e)
{
// Get selected text from Quill.
HyperlinkTextBox.Text = await TryGetSelectedTextAsync();
}
private async Task UpdateEditorThemeAsync()
{
await DOMLoadedTask.Task;
if (IsComposerDarkMode)
{
await InvokeScriptSafeAsync("DarkReader.enable();");
}
else
{
await InvokeScriptSafeAsync("DarkReader.disable();");
}
}
private async Task RenderInternalAsync(string htmlBody)
{
await DOMLoadedTask.Task;
await UpdateEditorThemeAsync();
if (string.IsNullOrEmpty(htmlBody))
{
await ExecuteScriptFunctionAsync("RenderHTML", " ");
}
else
{
await ExecuteScriptFunctionAsync("RenderHTML", htmlBody);
await FocusEditorAsync();
}
}
private async void ChromiumInitialized(Microsoft.UI.Xaml.Controls.WebView2 sender, Microsoft.UI.Xaml.Controls.CoreWebView2InitializedEventArgs args)
{
var editorBundlePath = (await ViewModel.NativeAppService.GetQuillEditorBundlePathAsync()).Replace("full.html", string.Empty);
Chromium.CoreWebView2.SetVirtualHostNameToFolderMapping("app.example", editorBundlePath, CoreWebView2HostResourceAccessKind.Allow);
Chromium.Source = new Uri("https://app.example/full.html");
Chromium.CoreWebView2.DOMContentLoaded -= DOMLoaded;
Chromium.CoreWebView2.DOMContentLoaded += DOMLoaded;
Chromium.CoreWebView2.WebMessageReceived -= ScriptMessageRecieved;
Chromium.CoreWebView2.WebMessageReceived += ScriptMessageRecieved;
}
private static async void OnIsComposerDarkModeChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
if (obj is ComposePage page)
{
await page.UpdateEditorThemeAsync();
}
}
private void ScriptMessageRecieved(CoreWebView2 sender, CoreWebView2WebMessageReceivedEventArgs args)
{
var change = JsonConvert.DeserializeObject<string>(args.WebMessageAsJson);
bool isEnabled = change.EndsWith("ql-active");
if (change.StartsWith("ql-bold"))
BoldButton.IsChecked = isEnabled;
else if (change.StartsWith("ql-italic"))
ItalicButton.IsChecked = isEnabled;
else if (change.StartsWith("ql-underline"))
UnderlineButton.IsChecked = isEnabled;
else if (change.StartsWith("ql-strike"))
StrokeButton.IsChecked = isEnabled;
else if (change.StartsWith("orderedListButton"))
OrderedListButton.IsChecked = isEnabled;
else if (change.StartsWith("bulletListButton"))
BulletListButton.IsChecked = isEnabled;
else if (change.StartsWith("ql-direction"))
DirectionButton.IsChecked = isEnabled;
else if (change.StartsWith("ql-align-left"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 0;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
else if (change.StartsWith("ql-align-center"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 1;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
else if (change.StartsWith("ql-align-right"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 2;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
else if (change.StartsWith("ql-align-justify"))
{
AlignmentListView.SelectionChanged -= AlignmentChanged;
AlignmentListView.SelectedIndex = 3;
AlignmentListView.SelectionChanged += AlignmentChanged;
}
}
private void DOMLoaded(CoreWebView2 sender, CoreWebView2DOMContentLoadedEventArgs args) => DOMLoadedTask.TrySetResult(true);
public async void Receive(HtmlRenderingRequested message)
{
await RenderInternalAsync(message.HtmlBody);
}
}
}

View File

@@ -259,6 +259,9 @@
<Compile Include="Dialogs\MoveMailDialog.xaml.cs">
<DependentUpon>MoveMailDialog.xaml</DependentUpon>
</Compile>
<Compile Include="Dialogs\SignatureEditorDialog.xaml.cs">
<DependentUpon>SignatureEditorDialog.xaml</DependentUpon>
</Compile>
<Compile Include="Dialogs\NewImapSetupDialog.xaml.cs">
<DependentUpon>NewImapSetupDialog.xaml</DependentUpon>
</Compile>
@@ -492,6 +495,10 @@
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="Dialogs\SignatureEditorDialog.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Dialogs\NewImapSetupDialog.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>