1use crate::{
2 AnalysisReport,
3 filesystem::{contained_file, replace, write_new},
4 resources::bounded_read,
5};
6use anyhow::{Result, ensure};
7use std::{
8 fs,
9 path::{Path, PathBuf},
10};
11
12pub fn refresh_report(directory: impl AsRef<Path>) -> Result<PathBuf> {
14 let directory = fs::canonicalize(directory)?;
15 let data = contained_file(&directory, Path::new("analysis.json"))?;
16 let report: AnalysisReport = serde_json::from_slice(&bounded_read(&data)?)?;
17 ensure!(
18 matches!(report.schema_version, 1 | 2),
19 "unsupported analysis schema version"
20 );
21 let html = render_html(&report)?;
22 let output = directory.join("report.html");
23 if fs::symlink_metadata(&output).is_ok() {
24 contained_file(&directory, Path::new("report.html"))?;
25 replace(&output, html.as_bytes())?;
26 } else {
27 write_new(&output, html.as_bytes())?;
28 }
29 Ok(output)
30}
31
32pub(crate) fn render_html(report: &AnalysisReport) -> Result<String> {
33 let payload = serde_json::json!({
34 "sessionToken": null,
35 "meta": meta(report),
36 "resources": report.resources,
37 });
38 Ok(page(&script_safe_json(&payload)?).into_string())
39}
40
41pub(crate) fn render_live_page(project: &Path, token: &str) -> Result<String> {
44 let payload = serde_json::json!({
45 "sessionToken": token,
46 "meta": {"root": project},
47 });
48 Ok(page(&script_safe_json(&payload)?).into_string())
49}
50
51pub(crate) fn meta(report: &AnalysisReport) -> serde_json::Value {
53 serde_json::json!({
54 "root": report.root,
55 "backend": report.backend,
56 "options": report.options,
57 "savings": report.potential_source_bytes_saved,
58 "cancelled": report.cancelled,
59 "similarGroups": report.similar_groups,
60 "performance": report.performance,
61 "projectKinds": report.inventory.project_kinds,
62 "androidMinSdk": report.inventory.android_min_sdk,
63 "diagnostics": report.inventory.diagnostics,
64 "excludedDirectories": report.inventory.excluded_directories,
65 })
66}
67
68fn script_safe_json(value: &serde_json::Value) -> Result<String> {
71 Ok(serde_json::to_string(value)?
72 .replace('<', "\\u003c")
73 .replace('>', "\\u003e")
74 .replace('&', "\\u0026")
75 .replace('\u{2028}', "\\u2028")
76 .replace('\u{2029}', "\\u2029"))
77}
78
79use maud::{DOCTYPE, Markup, PreEscaped, html};
80
81const THEME_BOOTSTRAP: &str = "try{const t=localStorage.getItem('resopt-theme')||'system';document.documentElement.dataset.theme=t==='system'?(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'):t}catch{}";
82
83fn script() -> String {
85 [
86 "'use strict';(() => {",
87 include_str!("ui/core.js"),
88 include_str!("ui/i18n.js"),
89 include_str!("ui/app.js"),
90 include_str!("ui/detail.js"),
91 include_str!("ui/batch.js"),
92 "start();})();",
93 ]
94 .join("\n")
95}
96
97fn page(data: &str) -> Markup {
98 html! {
99 (DOCTYPE)
100 html lang="en" {
101 head {
102 meta charset="utf-8";
103 meta name="viewport" content="width=device-width, initial-scale=1";
104 title { "resopt · Resource analysis" }
105 script { (PreEscaped(THEME_BOOTSTRAP)) }
106 style { (PreEscaped(include_str!("ui/style.css"))) }
107 }
108 body {
109 a.skip-link href="#results" data-i18n="colResource" { "Resource" }
110 header {
111 div.brand {
112 span.mark aria-hidden="true" { i {} i {} i {} i {} }
113 strong { "resopt" } span data-i18n="title" { "Resource analysis" }
114 }
115 div.header-meta {
116 span.read-only id="session-mode" {}
117 select id="language" aria-label="Language" data-i18n-label="language" {
118 option value="en" { "English" }
119 option value="zh-CN" { "简体中文" }
120 }
121 select id="theme" aria-label="Theme" data-i18n-label="theme" {
122 option value="system" data-i18n="themeSystem" { "System" }
123 option value="light" data-i18n="themeLight" { "Light" }
124 option value="dark" data-i18n="themeDark" { "Dark" }
125 }
126 a href="analysis.json" target="_blank" rel="noopener" data-i18n="json" { "View JSON ↗" }
127 }
128 }
129 main {
130 section.status id="status" role="status" aria-live="polite" {}
131 (overview())
132 (toolbar())
133 div.workspace {
134 section.list-pane aria-label="Resources" data-i18n-label="statResources" {
135 div.list-head aria-hidden="true" {
136 span data-i18n="colResource" {} span data-i18n="colSize" {} span data-i18n="colSavings" {}
137 }
138 div.results id="results" role="listbox" tabindex="-1" aria-label="Resources" data-i18n-label="statResources" {}
139 div.pager {
140 span id="range" role="status" aria-live="polite" {}
141 div.pager-controls {
142 button.icon-button type="button" id="previous" aria-label="Previous page" data-i18n-label="previous" { "←" }
143 span id="page-number" {}
144 button.icon-button type="button" id="next" aria-label="Next page" data-i18n-label="next" { "→" }
145 }
146 }
147 }
148 aside.inspector id="inspector" aria-label="Details" {}
149 }
150 footer.footer {
151 span data-i18n="footerUnits" {}
152 span data-i18n="footerScope" {}
153 }
154 }
155 (dialogs())
156 noscript { "Enable JavaScript to filter resources and compare images, or open analysis.json next to this file." }
157 script type="application/json" id="report-data" { (PreEscaped(data)) }
159 script { (PreEscaped(script())) }
160 }
161 }
162 }
163}
164
165fn overview() -> Markup {
166 html! {
167 section.summary aria-label="Overview" {
168 @for (id, label, accent) in [
169 ("stat-resources", "statResources", false),
170 ("stat-opportunities", "statOpportunities", false),
171 ("stat-savings", "statSavings", true),
172 ("stat-warnings", "statWarnings", false),
173 ("stat-applied", "statApplied", false),
174 ] {
175 div.stat {
176 div.stat-label data-i18n=(label) {}
177 div class={ "stat-value" @if accent { " accent" } } id=(id) { "—" }
178 }
179 }
180 p.summary-note id="scope-note" {}
181 }
182 }
183}
184
185fn toolbar() -> Markup {
186 html! {
187 section.toolbar aria-label="Filters" {
188 div.modes role="group" aria-label="View" {
189 @for mode in ["candidates", "warnings", "duplicates", "applied", "images", "unsupported", "failed", "all"] {
190 button.mode type="button" data-mode=(mode) aria-pressed="false" {
191 span data-i18n={ "mode" (mode[..1].to_uppercase()) (mode[1..]) } {}
192 " " span.mode-count id={ "mode-" (mode) } {}
193 }
194 }
195 }
196 div.search {
197 svg width="15" height="15" viewBox="0 0 20 20" fill="none" aria-hidden="true" {
198 circle cx="8.5" cy="8.5" r="5.5" stroke="currentColor" stroke-width="1.5" {}
199 path d="m13 13 4 4" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" {}
200 }
201 input type="search" id="search" autocomplete="off" aria-label="Search" data-i18n-label="search" data-i18n-placeholder="search";
202 }
203 select id="format-filter" aria-label="Format" data-i18n-label="allFormats" {}
204 select id="sort" aria-label="Sort" {
205 option value="savings" data-i18n="sortSavings" {}
206 option value="size" data-i18n="sortSize" {}
207 option value="name" data-i18n="sortName" {}
208 option value="score" data-i18n="sortScore" {}
209 }
210 button.primary type="button" id="batch-open" hidden data-i18n="batch" {}
211 button type="button" id="restore-all-open" hidden data-i18n="restoreAll" {}
212 }
213 }
214}
215
216fn dialogs() -> Markup {
217 html! {
218 dialog id="apply-dialog" aria-labelledby="apply-title" {
219 h2 id="apply-title" {}
220 p id="apply-description" {}
221 p.hint id="apply-note" {}
222 div.dialog-actions {
223 button type="button" id="apply-cancel" data-i18n="cancelButton" {}
224 button.primary type="button" id="apply-confirm" {}
225 }
226 }
227 dialog.wide id="compare-dialog" aria-labelledby="compare-title" {
228 div.dialog-head {
229 h2 id="compare-title" data-i18n="compareTitle" {}
230 button type="button" id="compare-close" data-i18n="close" {}
231 }
232 p id="compare-caption" {}
233 input type="range" id="compare-slider" min="0" max="100" value="50" aria-label="Comparison position" data-i18n-label="compare";
234 div.compare-stage id="compare-stage" data-background="checker" {}
235 p.hint id="compare-note" {}
236 }
237 dialog id="batch-dialog" aria-labelledby="batch-title" {
238 div.dialog-head {
239 h2 id="batch-title" {}
240 button type="button" id="batch-close" data-i18n="close" {}
241 }
242 div id="batch-policy-view" {
243 p data-i18n="batchIntro" {}
244 @for (id, label, checked) in [
245 ("batch-lossless", "batchLossless", true),
246 ("batch-lossy", "batchLossy", false),
247 ("batch-cross", "batchCross", false),
248 ("batch-alpha", "batchAlpha", false),
249 ("batch-quality", "batchQuality", false),
250 ] {
251 label.check { input type="checkbox" id=(id) checked[checked]; span data-i18n=(label) {} }
252 }
253 label.field { span data-i18n="batchMinScore" {} input type="number" id="batch-min-score" min="0" max="100" step="1" inputmode="decimal"; }
254 label.check { input type="checkbox" id="batch-scope"; span id="batch-scope-label" {} }
255 p.status-warn id="batch-error" role="alert" {}
256 div.dialog-actions { button.primary type="button" id="batch-preview" data-i18n="batchPreview" {} }
257 }
258 div id="batch-plan-view" hidden {
259 p.summary-text id="batch-summary" {}
260 ul.batch-list id="batch-items" {}
261 div.dialog-actions {
262 button type="button" id="batch-back" data-i18n="cancelButton" {}
263 button.primary type="button" id="batch-confirm" {}
264 }
265 }
266 div id="batch-progress-view" hidden {
267 p id="batch-progress-text" role="status" aria-live="polite" {}
268 progress id="batch-bar" max="1" value="0" {}
269 p.status-warn id="batch-stopped" hidden data-i18n="batchStopped" {}
270 h3 id="batch-failures-title" hidden data-i18n="batchFailures" {}
271 ul.batch-list id="batch-failures" {}
272 div.dialog-actions {
273 button type="button" id="batch-stop" data-i18n="batchStop" {}
274 button.primary type="button" id="batch-done" hidden data-i18n="close" {}
275 }
276 }
277 }
278 }
279}