Skip to content
This repository was archived by the owner on Mar 14, 2024. It is now read-only.

Add support for in-document linking (e.g. #my-id). #50

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion Documents/Markdig-readme.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
# Markdig [![Build status](https://ci.appveyor.com/api/projects/status/hk391x8jcskxt1u8?svg=true)](https://ci.appveyor.com/project/xoofx/markdig) [![NuGet](https://img.shields.io/nuget/v/Markdig.svg)](https://www.nuget.org/packages/Markdig/) [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=FRGHXBTP442JL)
* [Markdig](#markdig)
* [Features](#features)
* [Documentation](#documentation)
* [Download](#download)
* [Usage](#usage)


# Markdig [![Build status](https://ci.appveyor.com/api/projects/status/hk391x8jcskxt1u8?svg=true)](https://ci.appveyor.com/project/xoofx/markdig) [![NuGet](https://img.shields.io/nuget/v/Markdig.svg)](https://www.nuget.org/packages/Markdig/) [![Donate](https://www.paypalobjects.com/en_US/i/btn/btn_donate_SM.gif)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=FRGHXBTP442JL)

| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
Expand Down
5 changes: 5 additions & 0 deletions src/Markdig.Wpf/Commands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -20,5 +20,10 @@ public static class Commands
/// Routed command for Images.
/// </summary>
public static RoutedCommand Image { get; } = new RoutedCommand(nameof(Image), typeof(Commands));

/// <summary>
/// Routed command for navigating to a heading in a document. Command parameter contains the heading id
/// </summary>
public static RoutedCommand Navigate { get; } = new RoutedCommand(nameof(Navigate), typeof(Commands));
}
}
3 changes: 2 additions & 1 deletion src/Markdig.Wpf/MarkdownExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ public static MarkdownPipelineBuilder UseSupportedExtensions(this MarkdownPipeli
.UseGridTables()
.UsePipeTables()
.UseTaskLists()
.UseAutoLinks();
.UseAutoLinks()
.UseAutoIdentifiers();
}
}
}
99 changes: 99 additions & 0 deletions src/Markdig.Wpf/MarkdownViewer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
// This file is licensed under the MIT license.
// See the LICENSE.md file in the project root for more information.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;

namespace Markdig.Wpf
{
Expand Down Expand Up @@ -35,11 +38,28 @@ public class MarkdownViewer : Control
public static readonly DependencyProperty PipelineProperty =
DependencyProperty.Register(nameof(Pipeline), typeof(MarkdownPipeline), typeof(MarkdownViewer), new FrameworkPropertyMetadata(PipelineChanged));

/// <summary>
/// Defines the MarkdownViewer.AnchorName attached property used for in-document linking (e.g. "#my-id")
/// </summary>
public static readonly DependencyProperty AnchorNameProperty = DependencyProperty.RegisterAttached(
"AnchorName", typeof(string), typeof(MarkdownViewer), new PropertyMetadata(default(string)));

public static void SetAnchorName(DependencyObject element, string value)
{
element.SetValue(AnchorNameProperty, value);
}

public static string GetAnchorName(DependencyObject element)
{
return (string)element.GetValue(AnchorNameProperty);
}
static MarkdownViewer()
{
DefaultStyleKeyProperty.OverrideMetadata(typeof(MarkdownViewer), new FrameworkPropertyMetadata(typeof(MarkdownViewer)));
}

private FlowDocumentScrollViewer? docViewer;

/// <summary>
/// Gets the flow document to display.
/// </summary>
Expand Down Expand Up @@ -79,9 +99,88 @@ private static void PipelineChanged(object sender, DependencyPropertyChangedEven
control.RefreshDocument();
}

public MarkdownViewer()
{
CommandBindings.Add(new CommandBinding(Commands.Navigate, NavigateCommandExecuted));
}

private void NavigateCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
string url = e.Parameter?.ToString() ?? "";
if (url.Length > 1 && url[0] == '#')
{
string anchorName = url.Substring(1);
e.Handled = NavigateTo(anchorName);
}
}

protected virtual void RefreshDocument()
{
Document = Markdown != null ? Wpf.Markdown.ToFlowDocument(Markdown, Pipeline ?? DefaultPipeline) : null;
}

public override void OnApplyTemplate()
{
docViewer = GetTemplateChild("PART_DocViewer") as FlowDocumentScrollViewer;

base.OnApplyTemplate();
}

public bool NavigateTo(string anchorName)
{
if (Document == null)
throw new InvalidOperationException("No rendered content found");

foreach (var block in Document.Blocks)
{
string blockAnchorName = GetAnchorName(block);
if (String.Equals(blockAnchorName, anchorName, StringComparison.OrdinalIgnoreCase))
{
return ScrollIntoView(block);
}
}

return false;
}

private bool ScrollIntoView(Block block)
Copy link

@JD-Howard JD-Howard Jan 14, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I pulled this concept into my own customizations. This scroll into view method is fine in theory, but not always. The document start location literally shifts around; probably based on scroll state. The following is normalizing the problem I am having:

var objTop = block.ContentStart.GetCharacterRect(LogicalDirection.Forward).Top;
var docTop = _viewer.Document.ContentStart.GetCharacterRect(LogicalDirection.Forward).Top;
scrollViewer.ScrollToVerticalOffset(Math.Abs(docTop) + objTop);

{
if (docViewer == null)
return false;
double top = block.ContentStart.GetCharacterRect(LogicalDirection.Forward).Top;
var scrollViewer = FindVisualChild<ScrollViewer>(docViewer);
if (scrollViewer != null)
{
scrollViewer.ScrollToVerticalOffset(top);
return true;
}

return false;
}

/// <summary>
/// Gets a visual child of the specific type.
/// </summary>
/// <typeparam name="T">The type of child to find.</typeparam>
/// <param name="element">Where to start the "search".</param>
/// <returns>The child or null.</returns>
public static T? FindVisualChild<T>(
DependencyObject element) where T : class
{
if (element is T retVal)
return retVal;

int childCnt = VisualTreeHelper.GetChildrenCount(element);
for (int i = 0; i < childCnt; ++i)
{
DependencyObject child = VisualTreeHelper.GetChild(element, i);

var result = FindVisualChild<T>(child);
if (result != null)
return result;
}

return null;
}
}
}
8 changes: 7 additions & 1 deletion src/Markdig.Wpf/Renderers/Wpf/HeadingRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
using System;
using System.Windows;
using System.Windows.Documents;

using Markdig.Renderers.Html;
using Markdig.Syntax;
using Markdig.Wpf;

Expand Down Expand Up @@ -36,6 +36,12 @@ protected override void Write(WpfRenderer renderer, HeadingBlock obj)
paragraph.SetResourceReference(FrameworkContentElement.StyleProperty, styleKey);
}

var attributes = obj.TryGetAttributes();
if (!String.IsNullOrEmpty(attributes?.Id))
{
MarkdownViewer.SetAnchorName(paragraph, attributes.Id);
}

renderer.Push(paragraph);
renderer.WriteLeafInline(obj);
renderer.Pop();
Expand Down
5 changes: 2 additions & 3 deletions src/Markdig.Wpf/Renderers/Wpf/Inlines/LinkInlineRenderer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ protected override void Write(WpfRenderer renderer, LinkInline link)

var url = link.GetDynamicUrl != null ? link.GetDynamicUrl() ?? link.Url : link.Url;

if (!Uri.IsWellFormedUriString(url, UriKind.RelativeOrAbsolute))
if (!Uri.TryCreate(url, UriKind.RelativeOrAbsolute, out _))
{
url = "#";
}
Expand All @@ -53,12 +53,11 @@ protected override void Write(WpfRenderer renderer, LinkInline link)
{
var hyperlink = new Hyperlink
{
Command = Commands.Hyperlink,
Command = url.StartsWith("#") ? Commands.Navigate : Commands.Hyperlink,
CommandParameter = url,
NavigateUri = new Uri(url, UriKind.RelativeOrAbsolute),
ToolTip = !string.IsNullOrEmpty(link.Title) ? link.Title : null,
};

hyperlink.SetResourceReference(FrameworkContentElement.StyleProperty, Styles.HyperlinkStyleKey);

renderer.Push(hyperlink);
Expand Down
1 change: 1 addition & 0 deletions src/Markdig.Wpf/Themes/generic.xaml
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@
<Setter.Value>
<ControlTemplate TargetType="markdig:MarkdownViewer">
<FlowDocumentScrollViewer Document="{TemplateBinding Document}"
x:Name="PART_DocViewer"
ScrollViewer.VerticalScrollBarVisibility="Auto"/>
</ControlTemplate>
</Setter.Value>
Expand Down