Skip to content
Merged
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
13 changes: 13 additions & 0 deletions checks/pagecheck.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,19 @@ string[] Export(string name, string to, PageExportKind kind)
var pagePng = Export("page-clean.html", "clean.png", PageExportKind.Png);
Check("a page as PNG: one file", pagePng.Length == 1 && new FileInfo(pagePng[0]).Length > 1000, true);

// Save a copy (P7): the dashboard template as one file still draws its charts with nothing
// linked, so it loads nothing and says nothing in the console.
var assets = Path.Combine(AppContext.BaseDirectory, "Assets", "pages");
foreach (var template in new[] { "dashboard", "report", "slides" })
{
var copy = Path.Combine(dir, $"copy-{template}.html");
File.WriteAllText(copy, PageBundle.Make(File.ReadAllText(Path.Combine(assets, "templates", template + ".html")),
PageTheme.Css("swiss"), assets, _ => Task.FromResult<string?>(null)).Result);
var (copied, why) = PageCheck.Check(copy, dir);
Check($"a saved copy of {template}: checked", why, null);
Check($" no errors, nothing blocked", copied is { Errors.Count: 0, Blocked.Count: 0 }, true);
}

// The Pages view's picture (P5): the first screen, 400 px wide, 16:9.
var thumb = Export("page-deck.html", "thumb.png", PageExportKind.Thumb);
var png = File.ReadAllBytes(thumb[0]);
Expand Down
30 changes: 30 additions & 0 deletions checks/pages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,36 @@ PageEntry E(string name, string project, string agent, string? session, int crea
PageThumbs.Prune([mine], thumbs);
Check(" a removed page's picture is pruned, the others kept",
(File.Exists(PageThumbs.PathFor(outside, thumbs)), File.Exists(PageThumbs.PathFor(mine, thumbs))), (false, true));

// Save a copy (P7): one file with everything inside, libraries only when used.
var lib = Path.Combine(dir, "lib");
Directory.CreateDirectory(lib);
File.WriteAllText(Path.Combine(lib, "clayo-page.css"), ".a { color: red } /* $1 </style> */");
File.WriteAllText(Path.Combine(lib, "clayo-page.js"), "var page = '$0 </script>';");
File.WriteAllText(Path.Combine(lib, "chart.umd.min.js"), "var CHART;");
File.WriteAllText(Path.Combine(lib, "mermaid.min.js"), "var MERMAID;");
const string Cdn = "https://cdn.jsdelivr.net/npm/d3@7.9.0/dist/d3.min.js";
var fetched = new List<string>();
Task<string?> Fetch(string url) { fetched.Add(url); return Task.FromResult<string?>(url == Cdn ? "var D3;" : null); }
string Bundle(string body) => PageBundle.Make(
$"<!doctype html><head><link rel=\"stylesheet\" href=\"clayo-page.css\"></head><body>{body}<script src=\"clayo-page.js\"></script></body>",
":root { --accent: blue; }", lib, Fetch).Result;

var plainCopy = Bundle("<p>hi</p>");
Check("copy: sealed", plainCopy.Contains("Content-Security-Policy"), true);
Check(" the stylesheet inside, then the theme", plainCopy.IndexOf(".a { color: red }") is > 0 and var at && at < plainCopy.IndexOf("--accent: blue"), true);
Check(" the script inside", plainCopy.Contains("var page = '$0 <\\/script>';"), true);
Check(" nothing linked from Clayo", plainCopy.Contains("ccx.assets/pages/clayo-page"), false);
Check(" a closing tag in a file can't end its tag early", plainCopy.Contains("/* $1 <\\/style> */"), true);
Check(" no charts: no Chart.js, no Mermaid", (plainCopy.Contains("CHART"), plainCopy.Contains("MERMAID")), (false, false));
var chartCopy = Bundle("<script type=\"application/json\" class=\"chart\">{}</script>");
Check("a chart: Chart.js, before Clayo's script", chartCopy.IndexOf("var CHART;") is > 0 and var c && c < chartCopy.IndexOf("var page"), true);
Check(" and still no Mermaid", chartCopy.Contains("MERMAID"), false);
Check("a diagram: Mermaid", Bundle("<pre class=\"mermaid\">graph TD</pre>").Contains("var MERMAID;"), true);
var cdnCopy = Bundle($"<script src=\"{Cdn}\"></script><script src=\"https://unpkg.com/x@1.0.0/x.js\"></script><script src=\"https://example.com/y.js\"></script>");
Check("a CDN script it can get: inside", cdnCopy.Contains("<script>var D3;</script>") && !cdnCopy.Contains(Cdn), true);
Check(" one it can't: its link kept", cdnCopy.Contains("src=\"https://unpkg.com/x@1.0.0/x.js\""), true);
Check(" another host: never fetched", fetched.Any(u => u.Contains("example.com")), false);
}
finally { Directory.Delete(dir, recursive: true); }

Expand Down
4 changes: 3 additions & 1 deletion src/Clayo/Assets/terminal.html
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@
/* One frame at a time: the doc's, or the page's. */
#md[data-kind="page"] #mdframe, #md:not([data-kind="page"]) #pageframe { display: none; }
/* Export is a page's, Present a deck's. */
#md:not([data-kind="page"]) #pageexport, #md:not([data-deck="1"]) #pagepresent { display: none; }
#md:not([data-kind="page"]) #pageexport, #md:not([data-kind="page"]) #pageshare, #md:not([data-deck="1"]) #pagepresent { display: none; }
</style>
</head>
<body>
Expand All @@ -57,6 +57,7 @@
<span id="mdname"></span>
<button id="pagepresent" title="Full screen. Arrow keys move between slides, Esc leaves.">▶ Present</button>
<button id="pageexport" title="Save it as a PDF or a PNG">Export</button>
<button id="pageshare" title="Save a copy that opens anywhere, offline">Share</button>
<button id="mdsplit" title="Half and half">◧ Split</button>
<button id="mdfull" title="Fill the pane">⛶ Full</button>
<button id="mdclose" title="Back to the terminal">✕</button>
Expand Down Expand Up @@ -348,6 +349,7 @@
// Both are the host's to do: a save dialog, a window over the screen.
document.getElementById("pageexport").addEventListener("click", function () { send({ t: "export" }); });
document.getElementById("pagepresent").addEventListener("click", function () { send({ t: "present" }); });
document.getElementById("pageshare").addEventListener("click", function () { send({ t: "share" }); });
mdSplit.addEventListener("click", function () { setMode("split"); });
mdFull.addEventListener("click", function () { setMode("full"); });
document.getElementById("mdclose").addEventListener("click", function () { closeDoc(true); });
Expand Down
81 changes: 81 additions & 0 deletions src/Clayo/Pages/PageBundle.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
using System.IO;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;

namespace CcxShell.Core;

/// <summary>
/// A page as one file that opens anywhere with no network (D14): sealed as the viewer shows it,
/// in the theme picked, with Clayo's stylesheet and script inside it, Chart.js and Mermaid only
/// when the page uses them, and the CDN scripts and stylesheets it links (D4) fetched once into
/// %LOCALAPPDATA%\Clayo\cdn. No WPF.
/// </summary>
public static partial class PageBundle
{
public static string CdnCache => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Clayo", "cdn");

[GeneratedRegex(@"<link\b[^>]*\bhref\s*=\s*([""'])https://ccx\.assets/pages/clayo-page\.css\1[^>]*>", RegexOptions.IgnoreCase)]
private static partial Regex StyleLink();

[GeneratedRegex(@"<script\b[^>]*\bsrc\s*=\s*([""'])https://ccx\.assets/pages/clayo-page\.js\1[^>]*>\s*</script\s*>", RegexOptions.IgnoreCase)]
private static partial Regex ScriptTag();

[GeneratedRegex(@"<script\b[^>]*\bsrc\s*=\s*([""'])(https://(?:cdnjs\.cloudflare\.com|cdn\.jsdelivr\.net|unpkg\.com)/[^""']+)\1[^>]*>\s*</script\s*>", RegexOptions.IgnoreCase)]
private static partial Regex CdnScript();

[GeneratedRegex(@"<link\b(?=[^>]*\brel\s*=\s*[""']?stylesheet)[^>]*\bhref\s*=\s*([""'])(https://(?:cdnjs\.cloudflare\.com|cdn\.jsdelivr\.net|unpkg\.com)/[^""']+)\1[^>]*>", RegexOptions.IgnoreCase)]
private static partial Regex CdnStyle();

[GeneratedRegex(@"<script\b[^>]*\bclass\s*=\s*[""'][^""']*\bchart\b", RegexOptions.IgnoreCase)]
private static partial Regex UsesChart();

[GeneratedRegex(@"<pre\b[^>]*\bclass\s*=\s*[""'][^""']*\bmermaid\b", RegexOptions.IgnoreCase)]
private static partial Regex UsesMermaid();

/// <summary>
/// The one file. fetch gets a CDN file's text, or null when it can't; a file it can't get
/// keeps its link, so the copy still works online.
/// </summary>
public static async Task<string> Make(string html, string themeCss, string assets, Func<string, Task<string?>> fetch)
{
html = PageHtml.Seal(html, themeCss);
string Read(string name) => File.ReadAllText(Path.Combine(assets, name));

// Lambdas, not "$" strings: the files are full of "$" that Regex.Replace would read.
html = StyleLink().Replace(html, _ => Style(Read("clayo-page.css")), 1);
var libs = new StringBuilder();
if (UsesChart().IsMatch(html)) libs.Append(Script(Read("chart.umd.min.js")));
if (UsesMermaid().IsMatch(html)) libs.Append(Script(Read("mermaid.min.js")));
html = ScriptTag().Replace(html, _ => libs + Script(Read("clayo-page.js")), 1);

foreach (var (pattern, wrap) in new (Regex, Func<string, string>)[] { (CdnScript(), Script), (CdnStyle(), Style) })
foreach (var m in pattern.Matches(html).Reverse())
if (await fetch(m.Groups[2].Value) is { } text)
html = html[..m.Index] + wrap(text) + html[(m.Index + m.Length)..];
return html;
}

// Inside the tag, "</script" or "</style" would end it early.
private static string Script(string js) => $"<script>{js.Replace("</script", "<\\/script", StringComparison.OrdinalIgnoreCase)}</script>";
private static string Style(string css) => $"<style>{css.Replace("</style", "<\\/style", StringComparison.OrdinalIgnoreCase)}</style>";

private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(20) };

/// <summary>A CDN file from the cache, else fetched and kept there; null when it can't be had.</summary>
public static async Task<string?> FetchCached(string url)
{
var file = Path.Combine(CdnCache, Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(url))));
try
{
if (File.Exists(file)) return await File.ReadAllTextAsync(file);
var text = await Http.GetStringAsync(url);
Directory.CreateDirectory(CdnCache);
await File.WriteAllTextAsync(file, text);
return text;
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException or HttpRequestException or TaskCanceledException) { return null; }
}
}
1 change: 1 addition & 0 deletions src/Clayo/Pages/PagesView.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,7 @@ MenuItem Item(string header, Action act, bool enabled = true)
sub.Click += async (_, _) => await TerminalPane.Export(Window.GetWindow(this), pages[0].Path, kind);
export.Items.Add(sub);
}
Item("Save a copy…", async () => await TerminalPane.SaveCopy(Window.GetWindow(this), pages[0].Path), one);
Item("Show in Explorer", () => System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{pages[0].Path}\"")?.Dispose(), one);
CardMenu.Items.Add(new Separator());
Item(one ? "Delete" : $"Delete {pages.Count} pages", () => Delete(pages)).InputGestureText = "Del";
Expand Down
41 changes: 41 additions & 0 deletions src/Clayo/Terminal/TerminalPane.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,10 @@ private void OnWebMessage(object? sender, CoreWebView2WebMessageReceivedEventArg
if (PageOpen is { } toExport) ShowExportMenu(toExport);
break;

case "share":
if (PageOpen is { } toShare) ShowShareMenu(toShare);
break;

case "present":
if (PageOpen is { } toPresent && Window.GetWindow(this) is { } owner)
try { new PresentWindow(PageHtml.Seal(File.ReadAllText(toPresent), PageTheme.CurrentCss())).ShowOver(owner); }
Expand Down Expand Up @@ -760,6 +764,43 @@ private void ShowExportMenu(string page)
menu.IsOpen = true;
}

/// <summary>Share's choices, where the mouse is. A public link comes with P7b.</summary>
private void ShowShareMenu(string page)
{
var menu = new ContextMenu { Placement = System.Windows.Controls.Primitives.PlacementMode.MousePoint };
var copy = new MenuItem { Header = "Save a copy…" };
copy.Click += async (_, _) => await SaveCopy(Window.GetWindow(this), page);
menu.Items.Add(copy);
menu.IsOpen = true;
}

/// <summary>
/// Asks where to save the page as one file that opens anywhere offline (PageBundle), writes
/// it, and shows it in Explorer.
/// </summary>
public static async Task SaveCopy(Window? owner, string page)
{
var dialog = new Microsoft.Win32.SaveFileDialog
{
Title = "Save a copy of the page",
FileName = string.Concat(PageIndex.TitleOf(page).Split(Path.GetInvalidFileNameChars())),
DefaultExt = "html",
Filter = "Web page|*.html"
};
if (dialog.ShowDialog(owner) != true) return;
try
{
var html = await PageBundle.Make(await File.ReadAllTextAsync(page), PageTheme.CurrentCss(),
Path.Combine(AppContext.BaseDirectory, "Assets", "pages"), PageBundle.FetchCached);
await File.WriteAllTextAsync(dialog.FileName, html);
System.Diagnostics.Process.Start("explorer.exe", $"/select,\"{dialog.FileName}\"")?.Dispose();
}
catch (Exception e) when (e is IOException or UnauthorizedAccessException)
{
MessageBox.Show(owner!, $"Couldn't save the copy: {e.Message}", "Clayo", MessageBoxButton.OK, MessageBoxImage.Warning);
}
}

/// <summary>Asks where to save the page as a PDF or PNG, writes it, and shows it in Explorer.</summary>
public static async Task Export(Window? owner, string page, PageExportKind kind)
{
Expand Down