-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTextBlock.cs
86 lines (63 loc) · 2.36 KB
/
TextBlock.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Developed by Bulat Bagaviev (@sunnyyssh).
// This file is licensed to you under the MIT license.
using System.Diagnostics.CodeAnalysis;
using Sunnyyssh.ConsoleUI.Binding;
namespace Sunnyyssh.ConsoleUI;
public sealed class TextBlock : UIElement
{
private static readonly string DefaultText = string.Empty;
private string? _text;
private IObservable<string?, ValueChangedEventArgs<string?>>? _observing;
public Color Background { get; init; } = Color.Default;
public Color Foreground { get; init; } = Color.Default;
public VerticalAligning TextVerticalAligning { get; init; } = VerticalAligning.Center;
public HorizontalAligning TextHorizontalAligning { get; init; } = HorizontalAligning.Center;
public bool WordWrap { get; init; } = true;
[NotNull]
public string? Text
{
get => _text ?? DefaultText;
set
{
_text = value;
Redraw(CreateDrawState());
}
}
public void Observe(IObservable<string?, ValueChangedEventArgs<string?>> textObservable)
{
ArgumentNullException.ThrowIfNull(textObservable, nameof(textObservable));
if (_observing is not null)
{
_observing.Updated -= HandleObservableTextUpdate;
}
_observing = textObservable;
_observing.Updated += HandleObservableTextUpdate;
Text = _observing.Value;
}
public void Unobserve()
{
if (_observing is null)
{
throw new InvalidOperationException("Nothing was observed.");
}
_observing.Updated -= HandleObservableTextUpdate;
_observing = null;
Text = null;
}
private void HandleObservableTextUpdate(IObservable<string?, UpdatedEventArgs> updated, UpdatedEventArgs args)
{
Text = updated.Value;
}
protected override DrawState CreateDrawState()
{
var builder = new DrawStateBuilder(Width, Height);
builder.Fill(Background);
TextHelper.PlaceText(0, 0, Width, Height,
WordWrap, Text, Background, Foreground,
TextVerticalAligning, TextHorizontalAligning, builder);
return builder.ToDrawState();
}
internal TextBlock(int width, int height, OverlappingPriority priority = OverlappingPriority.Medium)
: base(width, height, priority)
{ }
}