using System; using System.Collections.Generic; using System.Text; using System.Text.RegularExpressions; using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Documents; using Avalonia.Controls.Metadata; using Avalonia.Controls.Primitives; using Avalonia.Input.Platform; using Avalonia.Threading; namespace ControlCatalog.Controls { /// /// The language a highlights. /// public enum CodeLanguage { Xaml, CSharp } /// /// A read-only, syntax-highlighted snippet with a copy button, collapsed until the reader asks for it. /// Highlighting is a small hand-rolled tokenizer rather than a dependency, and every colour comes from /// the catalog theme dictionaries so it reads in both variants. /// [TemplatePart(PART_Text, typeof(SelectableTextBlock))] [TemplatePart(PART_CopyButton, typeof(Button))] public partial class CodeBlock : TemplatedControl { private const string PART_Text = "PART_Text"; private const string PART_CopyButton = "PART_CopyButton"; public static readonly StyledProperty CodeProperty = AvaloniaProperty.Register(nameof(Code)); public static readonly StyledProperty LanguageProperty = AvaloniaProperty.Register(nameof(Language)); public static readonly StyledProperty IsExpandedProperty = AvaloniaProperty.Register(nameof(IsExpanded), true); /// /// Snippets longer than this start collapsed. Catalog snippets are short by design (the median is /// four lines), so showing them costs less than a row that says nothing; only the rare long one /// is worth hiding. /// private const int CollapseThreshold = 12; private SelectableTextBlock? _text; private Button? _copyButton; private IDisposable? _copyReset; /// /// The snippet. Leading indentation common to every line is trimmed when it is rendered. /// public string? Code { get => GetValue(CodeProperty); set => SetValue(CodeProperty, value); } public CodeLanguage Language { get => GetValue(LanguageProperty); set => SetValue(LanguageProperty, value); } /// /// Whether the snippet is showing. Short snippets start open; ones longer than /// lines start collapsed. /// public bool IsExpanded { get => GetValue(IsExpandedProperty); set => SetValue(IsExpandedProperty, value); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (_copyButton != null) { _copyButton.Click -= OnCopyClick; } _text = e.NameScope.Find(PART_Text); _copyButton = e.NameScope.Find