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

@@ -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>