-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
115 lines (95 loc) · 3.29 KB
/
Program.cs
File metadata and controls
115 lines (95 loc) · 3.29 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
using System;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using AngleSharp;
using AngleSharp.Dom;
using AngleSharp.Css.Dom;
using AngleSharp.Html.Dom;
namespace BulletListFormatter
{
/// <summary>
/// https://chat.openai.com/chat/b6894f2e-b60b-43dc-bb18-e1b5f8493b38
/// </summary>
class Program
{
[STAThread]
static async Task Main(string[] args)
{
string htmlContent = GetClipboardAsHtml();
if (string.IsNullOrWhiteSpace(htmlContent))
{
string msg = "Could not get the HTML from the clipboard!";
Console.Error.WriteLine(msg);
throw new Exception(msg);
}
string formattedList = await ProcessBulletList(htmlContent);
Console.WriteLine(formattedList);
SetClipboardText(formattedList);
Console.WriteLine("The formatted list has been copied to the clipboard.");
}
static string GetClipboardAsHtml()
{
string result = string.Empty;
var thread = new System.Threading.Thread(() =>
{
result = Clipboard.GetText(TextDataFormat.Html);
});
thread.SetApartmentState(System.Threading.ApartmentState.STA);
thread.Start();
thread.Join();
return result;
}
static void SetClipboardText(string text)
{
var thread = new System.Threading.Thread(() =>
{
Clipboard.SetText(text);
});
thread.SetApartmentState(System.Threading.ApartmentState.STA);
thread.Start();
thread.Join();
}
static async Task<string> ProcessBulletList(string html)
{
var config = Configuration.Default.WithCss();
var context = BrowsingContext.New(config);
var document = await context.OpenAsync(req => req.Content(html));
var sb = new StringBuilder();
ProcessList(document.DocumentElement, sb);
return sb.ToString();
}
static void ProcessList(IElement element, StringBuilder sb)
{
foreach (var child in element.Children)
{
if (child.NodeName == "LI")
{
int indentationLevel = ComputeIndentationFromMarginLeft(child);
sb.Append(new string('\t', indentationLevel));
sb.Append("- ");
sb.AppendLine(child.TextContent.Trim());
}
else if (child.NodeName == "SPAN")
{
sb.AppendLine(child.TextContent.Trim());
}
else
{
ProcessList(child, sb);
}
}
}
private static int ComputeIndentationFromMarginLeft(IElement element)
{
var style = element.ComputeCurrentStyle();
var marginLeftStr = style.GetMarginLeft();
var marginLeft = decimal.Parse(marginLeftStr.TrimEnd("px".ToCharArray()));
//18 24 = 1
//54 72 = 2
//90 120 = 3
int result = (int)((marginLeft / 48) + 0.5m);
return result;
}
}
}