Skip to main content

lean_ctx/core/
wrapped_svg.rs

1//! Shareable SVG "Wrapped" card.
2//!
3//! Renders [`WrappedReport`] as a self-contained 1200x630 SVG (the social/OG image
4//! size). It is pure string building — no external crates, fonts, or assets — so the
5//! output is portable, diff-friendly, and can be posted directly or rasterised to PNG
6//! by any standard SVG tool. All data-derived text is XML-escaped.
7
8use crate::core::wrapped::{WrappedReport, format_tokens};
9
10/// Social/OG card dimensions.
11const CARD_W: u32 = 1200;
12const CARD_H: u32 = 630;
13
14impl WrappedReport {
15    /// Renders a polished, dependency-free SVG share card.
16    pub fn to_svg(&self) -> String {
17        let period_label = match self.period.as_str() {
18            "week" => format!(
19                "Week of {}",
20                lean_ctx_time::UtcDateTime::now().format("%b %d, %Y")
21            ),
22            "month" => format!(
23                "Month of {}",
24                lean_ctx_time::UtcDateTime::now().format("%B %Y")
25            ),
26            _ => "All Time".to_string(),
27        };
28
29        let saved = format_tokens(self.tokens_saved);
30        let cost = format!("${:.2}", self.cost_avoided_usd);
31        let est = if self.pricing_estimated {
32            " (est.)"
33        } else {
34            ""
35        };
36        let secondary = self.svg_secondary_metrics();
37        // Model line is only meaningful when a model was shared (older cards). Minimal cards omit it.
38        let model_line = if self.model_key.is_empty() {
39            String::new()
40        } else {
41            format!(
42                r##"  <text x="70" y="606" fill="#475569" font-size="17">priced at {}{}</text>"##,
43                escape(&self.model_key),
44                est
45            )
46        };
47
48        let spark = self.svg_sparkline();
49        let top = self.svg_top_commands();
50        let bounce_note = if self.bounce_tokens > 0 {
51            format!(
52                " - {} bounce",
53                crate::core::wrapped::format_tokens(self.bounce_tokens)
54            )
55        } else {
56            String::new()
57        };
58
59        format!(
60            r##"<svg xmlns="http://www.w3.org/2000/svg" width="{CARD_W}" height="{CARD_H}" viewBox="0 0 {CARD_W} {CARD_H}" font-family="Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif">
61  <defs>
62    <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
63      <stop offset="0" stop-color="#0b1020"/>
64      <stop offset="1" stop-color="#131a2e"/>
65    </linearGradient>
66    <linearGradient id="accent" x1="0" y1="0" x2="1" y2="0">
67      <stop offset="0" stop-color="#34d399"/>
68      <stop offset="1" stop-color="#22d3ee"/>
69    </linearGradient>
70  </defs>
71  <rect width="{CARD_W}" height="{CARD_H}" fill="url(#bg)"/>
72  <rect x="0" y="0" width="{CARD_W}" height="8" fill="url(#accent)"/>
73
74  <text x="70" y="92" fill="#e5e7eb" font-size="34" font-weight="700">lean-ctx <tspan fill="#34d399">Wrapped</tspan></text>
75  <text x="70" y="130" fill="#94a3b8" font-size="24">{period}</text>
76
77  <text x="70" y="300" fill="#34d399" font-size="138" font-weight="800" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">{saved}</text>
78  <text x="76" y="346" fill="#94a3b8" font-size="26">tokens saved</text>
79
80  <text x="730" y="252" fill="#22d3ee" font-size="84" font-weight="800" font-family="ui-monospace, SFMono-Regular, Menlo, monospace">{cost}</text>
81  <text x="734" y="292" fill="#94a3b8" font-size="24">cost avoided{est}</text>
82
83{secondary}
84{spark}
85{top}
86  <text x="70" y="582" fill="#64748b" font-size="19">Savings = measured original - compressed{bounce_note} tokens · USD = upper bound</text>
87{model_line}
88  <text x="1130" y="592" text-anchor="end" fill="#34d399" font-size="26" font-weight="700">leanctx.com</text>
89</svg>"##,
90            period = escape(&period_label),
91        )
92    }
93
94    /// The secondary metric row: compression + energy always; commands/sessions only when present
95    /// (older or local cards). Energy is derived from tokens — the same J/token basis as the
96    /// community metrics page — so showing it shares no extra data. Laid out left-to-right so a
97    /// minimal card (just compression + energy) looks balanced and a rich one fills the row.
98    fn svg_secondary_metrics(&self) -> String {
99        let mut items: Vec<(String, &str)> = vec![
100            (format!("{:.1}%", self.compression_rate_pct), "compression"),
101            (
102                crate::core::energy::format_for_tokens(self.tokens_saved),
103                "energy saved",
104            ),
105        ];
106        if self.total_commands > 0 {
107            items.push((self.total_commands.to_string(), "commands"));
108        }
109        if self.sessions_count > 0 {
110            items.push((self.sessions_count.to_string(), "sessions"));
111        }
112        let xs = [70, 360, 650, 940];
113        let mut out = String::new();
114        for (i, (val, label)) in items.iter().take(xs.len()).enumerate() {
115            let x = xs[i];
116            out.push_str(&format!(
117                "  <text x=\"{x}\" y=\"412\" fill=\"#e5e7eb\" font-size=\"44\" font-weight=\"700\" font-family=\"ui-monospace, SFMono-Regular, Menlo, monospace\">{val}</text>\n  <text x=\"{lx}\" y=\"442\" fill=\"#94a3b8\" font-size=\"22\">{label}</text>",
118                lx = x + 2,
119                val = escape(val),
120            ));
121            if i + 1 < items.len() {
122                out.push('\n');
123            }
124        }
125        out
126    }
127
128    /// A subtle accent-gradient sparkline of daily savings. Empty when there is not
129    /// enough history to be meaningful (fewer than two non-zero days).
130    fn svg_sparkline(&self) -> String {
131        let vals = &self.daily_savings;
132        if vals.iter().filter(|v| **v > 0).count() < 2 {
133            return String::new();
134        }
135        let max = (*vals.iter().max().unwrap_or(&1)).max(1) as f64;
136        let (x0, x1) = (70.0_f64, 1130.0_f64);
137        let baseline = 515.0_f64;
138        let height = 55.0_f64;
139        let n = vals.len().max(2);
140        let dx = (x1 - x0) / (n as f64 - 1.0);
141        let mut points = String::new();
142        for (i, v) in vals.iter().enumerate() {
143            let x = x0 + dx * i as f64;
144            let y = baseline - (*v as f64 / max) * height;
145            points.push_str(&format!("{x:.1},{y:.1} "));
146        }
147        format!(
148            "  <polyline fill=\"none\" stroke=\"url(#accent)\" stroke-width=\"3\" stroke-linejoin=\"round\" stroke-linecap=\"round\" points=\"{}\"/>",
149            points.trim()
150        )
151    }
152
153    /// The top three commands as a single muted line. Empty when no command data.
154    fn svg_top_commands(&self) -> String {
155        if self.top_commands.is_empty() {
156            return String::new();
157        }
158        let joined = self
159            .top_commands
160            .iter()
161            .take(3)
162            .map(|(cmd, _, pct)| format!("{cmd} {pct:.0}%"))
163            .collect::<Vec<_>>()
164            .join("    ·    ");
165        format!(
166            "  <text x=\"70\" y=\"548\" fill=\"#cbd5e1\" font-size=\"22\">top  {}</text>",
167            escape(&joined)
168        )
169    }
170}
171
172/// Minimal XML text escaping for data-derived strings.
173fn escape(s: &str) -> String {
174    s.replace('&', "&amp;")
175        .replace('<', "&lt;")
176        .replace('>', "&gt;")
177        .replace('"', "&quot;")
178        .replace('\'', "&apos;")
179}
180
181#[cfg(test)]
182mod tests {
183    use crate::core::wrapped::WrappedReport;
184
185    fn sample() -> WrappedReport {
186        WrappedReport {
187            period: "all".into(),
188            tokens_saved: 348_300_000,
189            tokens_input: 580_000_000,
190            cost_avoided_usd: 870.81,
191            total_commands: 17_055,
192            sessions_count: 67,
193            top_commands: vec![
194                ("ctx_search".into(), 100, 60.0),
195                ("cli_grep <x>".into(), 80, 85.0),
196                ("cli_shell".into(), 50, 37.0),
197            ],
198            compression_rate_pct: 60.2,
199            files_touched: 1_234,
200            daily_savings: vec![10, 50, 30, 30, 80, 80, 20, 5, 5, 40, 60, 40, 5, 50, 15],
201            bounce_tokens: 0,
202            model_key: "claude-3.5-sonnet".into(),
203            pricing_estimated: false,
204            percentile: Some(99),
205            security: None,
206        }
207    }
208
209    #[test]
210    fn svg_is_well_formed_and_branded() {
211        let svg = sample().to_svg();
212        assert!(svg.starts_with("<svg"), "must be an SVG document");
213        assert!(svg.trim_end().ends_with("</svg>"), "must close the svg tag");
214        assert!(svg.contains("leanctx.com"), "must carry the brand footer");
215        assert!(svg.contains("Wrapped"));
216        assert!(svg.contains("tokens saved"));
217        // Headline metric value is rendered.
218        assert!(svg.contains("348.3M"), "must render formatted tokens saved");
219    }
220
221    #[test]
222    fn svg_states_methodology_and_model() {
223        let svg = sample().to_svg();
224        assert!(
225            svg.contains("upper bound"),
226            "must state USD is an upper bound"
227        );
228        assert!(
229            svg.contains("claude-3.5-sonnet"),
230            "must name the pricing model"
231        );
232    }
233
234    #[test]
235    fn svg_escapes_command_names() {
236        let svg = sample().to_svg();
237        // The command "cli_grep <x>" must not leak a raw '<x>' that would break XML.
238        assert!(
239            svg.contains("cli_grep &lt;x&gt;"),
240            "command names must be escaped"
241        );
242    }
243
244    #[test]
245    fn svg_minimal_card_shows_energy_and_omits_empty_fields() {
246        // A card published by a current (minimal) client carries no command/session counts or
247        // model — the card must still render cleanly: energy + compression, nothing zeroed.
248        let mut r = sample();
249        r.total_commands = 0;
250        r.sessions_count = 0;
251        r.model_key = String::new();
252        r.top_commands = vec![];
253        let svg = r.to_svg();
254        assert!(
255            svg.contains(">energy saved<"),
256            "energy is always shown:\n{svg}"
257        );
258        assert!(svg.contains(">compression<"), "compression is always shown");
259        assert!(!svg.contains(">commands<"), "no commands label when zero");
260        assert!(!svg.contains(">sessions<"), "no sessions label when zero");
261        assert!(!svg.contains("priced at"), "no model line when model empty");
262    }
263
264    #[test]
265    fn svg_omits_sparkline_without_history() {
266        let mut r = sample();
267        r.daily_savings = vec![0];
268        let svg = r.to_svg();
269        assert!(
270            !svg.contains("<polyline"),
271            "no sparkline without enough history"
272        );
273        // Card still renders the rest.
274        assert!(svg.contains("</svg>"));
275    }
276}