Skip to content

Commit

Permalink
Merge pull request #2 from michaldivis/v0.1.2-alpha
Browse files Browse the repository at this point in the history
v0.1.2
  • Loading branch information
michaldivis authored Dec 9, 2021
2 parents b0b2ff3 + 1fe50e7 commit 4451b8f
Show file tree
Hide file tree
Showing 5 changed files with 199 additions and 28 deletions.
26 changes: 22 additions & 4 deletions demos/DarkHtmlViewerBasicDemo/DemoView.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,18 +32,36 @@
Padding="5"
Background="#eee">
<WrapPanel>
<Button
Margin="5"
Padding="10,5,10,5"
Command="{Binding ElementName=darkHtmlViewer, Path=ScrollCommand}"
CommandParameter="footer"
Content="Scroll to footer" />
<Button
Margin="5"
Padding="10,5,10,5"
Command="{Binding ElementName=darkHtmlViewer, Path=ScrollOnNextLoadCommand}"
CommandParameter="footer"
Content="Scroll to footer on next load" />
<Button
Margin="5"
Padding="10,5,10,5"
Command="{Binding ElementName=darkHtmlViewer, Path=LoadAndScrollCommand}"
CommandParameter="{Binding TestLoadAndScrollData}"
Content="Load page 1 and scroll to footer" />
Content="Load and scroll" />
<Button
Margin="5"
Padding="10,5,10,5"
Command="{Binding ElementName=darkHtmlViewer, Path=ScrollCommand}"
CommandParameter="footer"
Content="Scroll to footer" />
Command="{Binding ElementName=darkHtmlViewer, Path=SearchCommand}"
CommandParameter="tin"
Content="Search" />
<Button
Margin="5"
Padding="10,5,10,5"
Command="{Binding ElementName=darkHtmlViewer, Path=SearchOnNextLoadCommand}"
CommandParameter="tin"
Content="Search on next load" />
<Button
Margin="5"
Padding="10,5,10,5"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<Configuration>Release</Configuration>
<Platform>Any CPU</Platform>
<PublishDir>..\..\artifacts\</PublishDir>
<PublishProtocol>FileSystem</PublishProtocol>
<TargetFramework>net5.0-windows</TargetFramework>
<RuntimeIdentifier>win-x64</RuntimeIdentifier>
<SelfContained>false</SelfContained>
<PublishSingleFile>False</PublishSingleFile>
<PublishReadyToRun>False</PublishReadyToRun>
</PropertyGroup>
</Project>
22 changes: 20 additions & 2 deletions src/DarkHtmlViewer/DarkHtmlTempFileManager.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System;
using System.IO;
using System.Text.RegularExpressions;

namespace DarkHtmlViewer
{
Expand All @@ -22,21 +23,26 @@ private void Initialize()
_tempFileDir = GetTempFileDirPath();
_tempFilePath = Path.Combine(_tempFileDir, $"{_instanceId}_tmp_{_count}.html");

Create(null);
Create("<p></p>");
}

public void Create(string html)
{
Directory.CreateDirectory(_tempFileDir);

File.Delete(_tempFilePath);
DeleteTempFile();

_count++;
_tempFilePath = Path.Combine(_tempFileDir, $"{_instanceId}_tmp_{_count}.html");

File.WriteAllText(_tempFilePath, html);
}

public void DeleteTempFile()
{
File.Delete(_tempFilePath);
}

public string GetFilePath()
{
return _tempFilePath;
Expand All @@ -46,5 +52,17 @@ private string GetTempFileDirPath()
{
return Path.Combine(Path.GetTempPath(), "tmp_html");
}

public bool IsTempFilePath(string text)
{
if (string.IsNullOrEmpty(text))
{
return false;
}

var pattern = _instanceId + @"_tmp_\d+\.html";
var match = Regex.Match(text, pattern);
return match.Success;
}
}
}
10 changes: 6 additions & 4 deletions src/DarkHtmlViewer/DarkHtmlViewer.csproj
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0-windows</TargetFramework>
<TargetFrameworks>netcoreapp3.1;net5.0-windows;net6.0-windows</TargetFrameworks>
<UseWPF>true</UseWPF>
<Version>0.1.1-alpha</Version>
<Version>0.1.2-alpha</Version>
<Authors>Michal Diviš</Authors>
<Description>A simple HTML viewer control for WPF (using WebView2)</Description>
<PackageLicenseExpression>MIT</PackageLicenseExpression>
Expand All @@ -12,11 +12,13 @@
<PackageIcon>icon.png</PackageIcon>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageId>Divis.DarkHtmlViewer</PackageId>
<PackageReleaseNotes>more functionality and some tweaks</PackageReleaseNotes>
<LangVersion>9.0</LangVersion>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Divis.DarkHelpers" Version="0.1.3" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.818.41" />
<PackageReference Include="Divis.DarkHelpers" Version="0.1.7" />
<PackageReference Include="Microsoft.Web.WebView2" Version="1.0.1054.31" />
</ItemGroup>

<ItemGroup>
Expand Down
152 changes: 134 additions & 18 deletions src/DarkHtmlViewer/DarkHtmlViewer.xaml.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using DarkHelpers.Commands;
using Microsoft.Web.WebView2.Core;
using System;
using System.IO;
using System.Threading.Tasks;
Expand Down Expand Up @@ -47,8 +48,11 @@ public ICommand LinkClickedCommand
#region Commands

public ICommand LoadCommand => new DarkCommand<string>(LoadHtmlContent);
public ICommand LoadAndScrollCommand => new DarkCommand<LoadAndScrollData>(LoadAndScroll);
public ICommand ScrollCommand => new DarkAsyncCommand<string>(ScrollAsync);
public ICommand LoadAndScrollCommand => new DarkAsyncCommand<LoadAndScrollData>(LoadAndScrollAsync);
public ICommand ScrollOnNextLoadCommand => new DarkCommand<string>(ScrollOnNextLoad);
public ICommand SearchCommand => new DarkAsyncCommand<string>(SearchAsync);
public ICommand SearchOnNextLoadCommand => new DarkCommand<string>(SearchOnNextLoad);
public ICommand PrintCommand => new DarkAsyncCommand(PrintAsync);

#endregion
Expand All @@ -64,15 +68,47 @@ public DarkHtmlViewer()

#region Initialization

private void InitializeWebView2()
private bool _initialized;
private string _loadAfterInitialization = null;
private async void InitializeWebView2()
{
webView2.Source = new Uri(_fileManager.GetFilePath());
var initFilePath = _fileManager.GetFilePath();

webView2.CoreWebView2InitializationCompleted += WebView2_CoreWebView2InitializationCompleted;
webView2.NavigationStarting += WebView2_NavigationStarting;
webView2.NavigationCompleted += WebView2_NavigationCompleted;

var appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
var dataFolder = Path.Combine(appDataDir, "webView2_env");
var env = await CoreWebView2Environment.CreateAsync(null, dataFolder);

await webView2.EnsureCoreWebView2Async(env);

SetWebViewSource(initFilePath);

webView2.Visibility = Visibility.Visible;

_initialized = true;

LoadQeuedContentIfAny();
}

private void SetWebViewSource(string uri)
{
webView2.CoreWebView2?.Navigate(uri);
}

private void LoadQeuedContentIfAny()
{
if (_loadAfterInitialization is null)
{
return;
}

LoadHtmlContent(_loadAfterInitialization);
}

private void WebView2_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
private void WebView2_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
DisableAllExtraFunctionality();
}
Expand All @@ -92,21 +128,28 @@ private static void OnHtmlContentCallBack(DependencyObject sender, DependencyPro

private void LoadHtmlContent(string html)
{
if (_initialized is false)
{
_loadAfterInitialization = html;
return;
}

_fileManager.Create(html);
webView2.Source = new Uri(_fileManager.GetFilePath());
var htmlFilePath = _fileManager.GetFilePath();
SetWebViewSource(htmlFilePath);
}

#endregion

#region Navigation

private void WebView2_NavigationStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
private void WebView2_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
{
string linkName = Path.GetFileName(e.Uri);
var linkName = Path.GetFileName(e.Uri);

string currentFileName = Path.GetFileName(_fileManager.GetFilePath());
var isTempFileName = _fileManager.IsTempFilePath(linkName);

if (linkName == currentFileName)
if (isTempFileName)
{
return;
}
Expand All @@ -118,7 +161,7 @@ private void WebView2_NavigationStarting(object sender, Microsoft.Web.WebView2.C

private void TriggerLinkClicked(string link)
{
bool canExecute = LinkClickedCommand?.CanExecute(link) ?? false;
var canExecute = LinkClickedCommand?.CanExecute(link) ?? false;

if (canExecute is false)
{
Expand All @@ -128,20 +171,83 @@ private void TriggerLinkClicked(string link)
LinkClickedCommand?.Execute(link);
}

private async void WebView2_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
if (_scrollToNext is not null)
{
await ScrollAsync(_scrollToNext);
_scrollToNext = null;
}

if (_textToFind is not null)
{
await SearchAsync(_textToFind);
_textToFind = null;
}
}

#endregion

#region Scroll to

private async Task ScrollAsync(string link)
private string _scrollToNext = null;

private async Task ScrollAsync(string elementId)
{
string script = $"document.getElementById(\"{link}\").scrollIntoView();";
var script = $"document.getElementById(\"{elementId}\").scrollIntoView();";
await webView2.ExecuteScriptAsync(script);
}

private async Task LoadAndScrollAsync(LoadAndScrollData data)
private void ScrollOnNextLoad(string link)
{
_scrollToNext = link;
}

private void LoadAndScroll(LoadAndScrollData data)
{
ScrollOnNextLoad(data.Link);
LoadHtmlContent(data.HtmlContent);
await ScrollAsync(data.Link);
}

#endregion

#region Search

private string _textToFind = null;

private async Task SearchAsync(string text)
{
var clean = CleanSearchText(text);
if (string.IsNullOrEmpty(clean))
{
return;
}

//TODO try to find a way to highlight all occurances instead of just the first one
var script = $"window.find('{clean}');";
await webView2.ExecuteScriptAsync(script);
}

private string CleanSearchText(string text)
{
if (string.IsNullOrEmpty(text))
{
return null;
}

var clean = text.Replace("'", "");

if (string.IsNullOrEmpty(clean))
{
return null;
}

return clean;
}

private void SearchOnNextLoad(string text)
{
_textToFind = text;
}

#endregion
Expand All @@ -168,11 +274,21 @@ private void DisableAllExtraFunctionality()
webView2.CoreWebView2.Settings.IsWebMessageEnabled = false;
webView2.CoreWebView2.Settings.IsZoomControlEnabled = false;
webView2.CoreWebView2.Settings.IsBuiltInErrorPageEnabled = false;
webView2.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = true;
webView2.CoreWebView2.Settings.IsGeneralAutofillEnabled = false;
webView2.CoreWebView2.Settings.IsPasswordAutosaveEnabled = false;
}

//TODO implement this when the WebView2 v1.0.865 is out of prerelase
//webView2.CoreWebView2.Settings.AreBrowserAcceleratorKeysEnabled = false;
//webView2.CoreWebView2.Settings.IsGeneralAutofillEnabled = false;
//webView2.CoreWebView2.Settings.IsPasswordAutofillEnabled = false;
#endregion

#region Cleanup

/// <summary>
/// Removes the temporary files created by the control
/// </summary>
public void Cleanup()
{
_fileManager.DeleteTempFile();
}

#endregion
Expand Down

0 comments on commit 4451b8f

Please sign in to comment.