From 20f39f352605dabbf0c27f8e4967669304423e9a Mon Sep 17 00:00:00 2001 From: Yogeswaran Amsavalli Date: Wed, 18 Nov 2026 13:51:01 +0100 Subject: [PATCH] Pages: save a copy of a page as one file that opens anywhere offline (P7a) --- checks/pagecheck.cs | 13 ++++ checks/pages.cs | 30 +++++++++ src/Clayo/Assets/terminal.html | 4 +- src/Clayo/Pages/PageBundle.cs | 81 +++++++++++++++++++++++++ src/Clayo/Pages/PagesView.xaml.cs | 1 + src/Clayo/Terminal/TerminalPane.xaml.cs | 41 +++++++++++++ 6 files changed, 169 insertions(+), 1 deletion(-) create mode 100644 src/Clayo/Pages/PageBundle.cs diff --git a/checks/pagecheck.cs b/checks/pagecheck.cs index 5812471..aa116d1 100644 --- a/checks/pagecheck.cs +++ b/checks/pagecheck.cs @@ -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(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]); diff --git a/checks/pages.cs b/checks/pages.cs index 7696e09..37737f1 100644 --- a/checks/pages.cs +++ b/checks/pages.cs @@ -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 */"); + File.WriteAllText(Path.Combine(lib, "clayo-page.js"), "var page = '$0 ';"); + 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(); + Task Fetch(string url) { fetched.Add(url); return Task.FromResult(url == Cdn ? "var D3;" : null); } + string Bundle(string body) => PageBundle.Make( + $"{body}", + ":root { --accent: blue; }", lib, Fetch).Result; + + var plainCopy = Bundle("

hi

"); + 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(""); + 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("
graph TD
").Contains("var MERMAID;"), true); + var cdnCopy = Bundle($""); + Check("a CDN script it can get: inside", cdnCopy.Contains("") && !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); } diff --git a/src/Clayo/Assets/terminal.html b/src/Clayo/Assets/terminal.html index f777a32..0863790 100644 --- a/src/Clayo/Assets/terminal.html +++ b/src/Clayo/Assets/terminal.html @@ -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; } @@ -57,6 +57,7 @@ + @@ -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); }); diff --git a/src/Clayo/Pages/PageBundle.cs b/src/Clayo/Pages/PageBundle.cs new file mode 100644 index 0000000..3daaf2a --- /dev/null +++ b/src/Clayo/Pages/PageBundle.cs @@ -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; + +/// +/// 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. +/// +public static partial class PageBundle +{ + public static string CdnCache => Path.Combine( + Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Clayo", "cdn"); + + [GeneratedRegex(@"]*\bhref\s*=\s*([""'])https://ccx\.assets/pages/clayo-page\.css\1[^>]*>", RegexOptions.IgnoreCase)] + private static partial Regex StyleLink(); + + [GeneratedRegex(@"]*\bsrc\s*=\s*([""'])https://ccx\.assets/pages/clayo-page\.js\1[^>]*>\s*", RegexOptions.IgnoreCase)] + private static partial Regex ScriptTag(); + + [GeneratedRegex(@"]*\bsrc\s*=\s*([""'])(https://(?:cdnjs\.cloudflare\.com|cdn\.jsdelivr\.net|unpkg\.com)/[^""']+)\1[^>]*>\s*", RegexOptions.IgnoreCase)] + private static partial Regex CdnScript(); + + [GeneratedRegex(@"]*\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(@"]*\bclass\s*=\s*[""'][^""']*\bchart\b", RegexOptions.IgnoreCase)] + private static partial Regex UsesChart(); + + [GeneratedRegex(@"]*\bclass\s*=\s*[""'][^""']*\bmermaid\b", RegexOptions.IgnoreCase)] + private static partial Regex UsesMermaid(); + + /// + /// 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. + /// + public static async Task Make(string html, string themeCss, string assets, Func> 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)[] { (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, " $""; + private static string Style(string css) => $""; + + private static readonly HttpClient Http = new() { Timeout = TimeSpan.FromSeconds(20) }; + + /// A CDN file from the cache, else fetched and kept there; null when it can't be had. + public static async Task 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; } + } +} diff --git a/src/Clayo/Pages/PagesView.xaml.cs b/src/Clayo/Pages/PagesView.xaml.cs index 4c2dab1..17ac70f 100644 --- a/src/Clayo/Pages/PagesView.xaml.cs +++ b/src/Clayo/Pages/PagesView.xaml.cs @@ -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"; diff --git a/src/Clayo/Terminal/TerminalPane.xaml.cs b/src/Clayo/Terminal/TerminalPane.xaml.cs index c7a5d87..1e4fd2f 100644 --- a/src/Clayo/Terminal/TerminalPane.xaml.cs +++ b/src/Clayo/Terminal/TerminalPane.xaml.cs @@ -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); } @@ -760,6 +764,43 @@ private void ShowExportMenu(string page) menu.IsOpen = true; } + /// Share's choices, where the mouse is. A public link comes with P7b. + 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; + } + + /// + /// Asks where to save the page as one file that opens anywhere offline (PageBundle), writes + /// it, and shows it in Explorer. + /// + 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); + } + } + /// Asks where to save the page as a PDF or PNG, writes it, and shows it in Explorer. public static async Task Export(Window? owner, string page, PageExportKind kind) {