Gift packages: buy a main package for someone, with a printable gift card
- /ajandek: the package, whom it is for and from whom, the recipient's address typed twice (or "I hand it over"), a message; paid on Stripe like any package, the invoice is the buyer's - On payment the gift gets its own code (not a promo code: it cannot be withdrawn, and it adds the whole package); redeemed on /bevaltas - The recipient's e-mail carries the message and the code, with the gift card attached as a PDF; the buyer's confirmation says it was a gift - /ajandekaim: codes, state, the card to download, sending it by e-mail (again, or to another address) up to three times - crates/gift-card draws the A4 card (example chart, questions avatar, QR code) as SVG and makes a PDF with krilla, fonts compiled in; the backend draws downloads on a blocking thread, the worker the e-mails - Telegram notices say "(ajándék)"; unpaid gifts go after a week Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
@@ -0,0 +1,638 @@
|
||||
//! The printable gift card of a gifted package: one A4 page (PDF) with whom
|
||||
//! it is for, the package, the giver's message, the code to redeem (with a QR
|
||||
//! code), the example chart of the home page and the avatar of the questions.
|
||||
//!
|
||||
//! The page is drawn as an SVG and turned into a PDF with its text embedded
|
||||
//! (selectable and searchable). Fonts and pictures are compiled in: the
|
||||
//! services run in empty containers. Light and printer-friendly on purpose.
|
||||
|
||||
use std::fmt::Write as _;
|
||||
use std::sync::{Arc, OnceLock};
|
||||
|
||||
use base64::Engine as _;
|
||||
use krilla::action::{Action, LinkAction};
|
||||
use krilla::annotation::{Annotation, LinkAnnotation, Target};
|
||||
use krilla::geom::{Rect, Size};
|
||||
use krilla::metadata::Metadata;
|
||||
use krilla::page::PageSettings;
|
||||
use krilla_svg::{SurfaceExt as _, SvgSettings};
|
||||
use usvg::fontdb;
|
||||
|
||||
/// A4 in points.
|
||||
const W: f32 = 595.28;
|
||||
const H: f32 = 841.89;
|
||||
|
||||
const SERIF: &[u8] = include_bytes!("../fonts/CormorantGaramond-SemiBold.ttf");
|
||||
const SERIF_ITALIC: &[u8] = include_bytes!("../fonts/CormorantGaramond-MediumItalic.ttf");
|
||||
/// The family name inside that file (an instance cut from the variable font).
|
||||
const SERIF_ITALIC_FAMILY: &str = "Cormorant Garamond Light";
|
||||
const SANS: &[u8] = include_bytes!("../fonts/Inter-Regular.ttf");
|
||||
const SANS_BOLD: &[u8] = include_bytes!("../fonts/Inter-SemiBold.ttf");
|
||||
/// The zodiac and planet glyphs of the wheel.
|
||||
const SYMBOLS: &[u8] = include_bytes!("../fonts/DejaVuSans.ttf");
|
||||
const WHEEL: &str = include_str!("../assets/wheel.svg");
|
||||
const AVATAR: &[u8] = include_bytes!("../assets/avatar.webp");
|
||||
|
||||
const INK: &str = "#1b2238";
|
||||
const GOLD: &str = "#a07a2c";
|
||||
const MUTED: &str = "#5f6578";
|
||||
const LINE: &str = "#d9c9a3";
|
||||
const PAPER: &str = "#fdfaf3";
|
||||
|
||||
/// Where the code box starts; the message fills the space above it.
|
||||
const CODE_TOP: f32 = 636.0;
|
||||
const CODE_HEIGHT: f32 = 114.0;
|
||||
const CODE_LEFT: f32 = 56.0;
|
||||
const QR_SIZE: f32 = 86.0;
|
||||
const MESSAGE_LEFT: f32 = 164.0;
|
||||
const MESSAGE_RIGHT: f32 = W - 70.0;
|
||||
const AVATAR_SIZE: f32 = 70.0;
|
||||
|
||||
/// What goes on the card (the user's text is cleaned and escaped here).
|
||||
pub struct Card<'a> {
|
||||
/// The package's name ("Páros").
|
||||
pub package: &'a str,
|
||||
/// What the package gives, item by item ("2 részletes képletelemzés").
|
||||
pub contents: &'a [String],
|
||||
/// The code as shown (`ABCD-EFGH-JKLM`).
|
||||
pub code: &'a str,
|
||||
/// The link that opens the redeem page with the code filled in.
|
||||
pub redeem_url: &'a str,
|
||||
/// Whom it is for ("Bea részére").
|
||||
pub recipient_name: Option<&'a str>,
|
||||
/// Who gives it, as the buyer typed it.
|
||||
pub from_name: Option<&'a str>,
|
||||
/// The buyer's message (line breaks kept).
|
||||
pub message: Option<&'a str>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct Error(String);
|
||||
|
||||
impl std::fmt::Display for Error {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
write!(f, "gift card: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for Error {}
|
||||
|
||||
/// The card as a PDF document.
|
||||
pub fn pdf(card: &Card) -> Result<Vec<u8>, Error> {
|
||||
let tree = tree(card)?;
|
||||
let size = Size::from_wh(W, H).expect("A4 is a size");
|
||||
let mut document = krilla::Document::new();
|
||||
document.set_metadata(
|
||||
Metadata::new()
|
||||
.title(format!("Sorsfonalak ajándékutalvány – {}", card.package))
|
||||
.language("hu".into())
|
||||
.creator("Sorsfonalak".into()),
|
||||
);
|
||||
let mut page = document.start_page_with(PageSettings::new(size));
|
||||
let mut surface = page.surface();
|
||||
surface.draw_svg(&tree, size, SvgSettings::default()).ok_or_else(|| Error("the page could not be drawn".into()))?;
|
||||
surface.finish();
|
||||
// The QR code and the address can be clicked in a PDF reader.
|
||||
let (qr, link) = link_areas(card);
|
||||
for rect in [qr, link] {
|
||||
let action = Action::Link(LinkAction::new(card.redeem_url.to_string()));
|
||||
page.add_annotation(Annotation::new_link(LinkAnnotation::new(rect, Target::Action(action)), None));
|
||||
}
|
||||
page.finish();
|
||||
document.finish().map_err(|e| Error(format!("{e:?}")))
|
||||
}
|
||||
|
||||
/// The page as an SVG tree (the PDF is made from it; tests render it to a picture).
|
||||
pub fn tree(card: &Card) -> Result<usvg::Tree, Error> {
|
||||
let options = usvg::Options { fontdb: fonts(), font_family: "Inter".into(), ..Default::default() };
|
||||
usvg::Tree::from_str(&svg(card), &options).map_err(|e| Error(e.to_string()))
|
||||
}
|
||||
|
||||
fn fonts() -> Arc<fontdb::Database> {
|
||||
static FONTS: OnceLock<Arc<fontdb::Database>> = OnceLock::new();
|
||||
FONTS
|
||||
.get_or_init(|| {
|
||||
let mut db = fontdb::Database::new();
|
||||
for data in [SERIF, SERIF_ITALIC, SANS, SANS_BOLD, SYMBOLS] {
|
||||
db.load_font_data(data.to_vec());
|
||||
}
|
||||
Arc::new(db)
|
||||
})
|
||||
.clone()
|
||||
}
|
||||
|
||||
// --- measuring and wrapping text ---------------------------------------------------------
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Face {
|
||||
Serif,
|
||||
SerifItalic,
|
||||
Sans,
|
||||
SansBold,
|
||||
}
|
||||
|
||||
impl Face {
|
||||
fn data(self) -> &'static [u8] {
|
||||
match self {
|
||||
Face::Serif => SERIF,
|
||||
Face::SerifItalic => SERIF_ITALIC,
|
||||
Face::Sans => SANS,
|
||||
Face::SansBold => SANS_BOLD,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The width of a line of text (without kerning: a little wider than drawn).
|
||||
fn width(face: Face, text: &str, size: f32, spacing: f32) -> f32 {
|
||||
let face = ttf_parser::Face::parse(face.data(), 0).expect("the fonts are compiled in");
|
||||
let em = f32::from(face.units_per_em());
|
||||
text.chars()
|
||||
.map(|c| {
|
||||
let advance =
|
||||
face.glyph_index(c).and_then(|g| face.glyph_hor_advance(g)).unwrap_or(face.units_per_em() / 2);
|
||||
f32::from(advance) * size / em + spacing
|
||||
})
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Breaks text into lines of at most `max` points (a word longer than a line is cut).
|
||||
fn wrap(text: &str, max: f32, measure: &dyn Fn(&str) -> f32) -> Vec<String> {
|
||||
let mut lines = Vec::new();
|
||||
for paragraph in text.split('\n') {
|
||||
let mut line = String::new();
|
||||
for word in paragraph.split_whitespace() {
|
||||
let joined = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
|
||||
if measure(&joined) <= max {
|
||||
line = joined;
|
||||
continue;
|
||||
}
|
||||
if !line.is_empty() {
|
||||
lines.push(std::mem::take(&mut line));
|
||||
}
|
||||
// The word alone, cut where it does not fit.
|
||||
for c in word.chars() {
|
||||
let longer = format!("{line}{c}");
|
||||
if !line.is_empty() && measure(&longer) > max {
|
||||
lines.push(std::mem::replace(&mut line, c.to_string()));
|
||||
} else {
|
||||
line = longer;
|
||||
}
|
||||
}
|
||||
}
|
||||
lines.push(line);
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Groups items into lines joined by `sep`, an item never split.
|
||||
fn wrap_items(items: &[String], sep: &str, max: f32, measure: &dyn Fn(&str) -> f32) -> Vec<String> {
|
||||
let mut lines: Vec<String> = Vec::new();
|
||||
for item in items {
|
||||
match lines.last_mut() {
|
||||
Some(line) if measure(&format!("{line}{sep}{item}")) <= max => {
|
||||
line.push_str(sep);
|
||||
line.push_str(item);
|
||||
}
|
||||
_ => lines.push(item.clone()),
|
||||
}
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// User text made safe for the card: control characters out, at most one
|
||||
/// empty line in a row, spaces trimmed.
|
||||
fn clean(text: &str) -> String {
|
||||
let text: String = text.replace("\r\n", "\n").chars().filter(|&c| c == '\n' || !c.is_control()).collect();
|
||||
let mut out = String::new();
|
||||
let mut empty = 0;
|
||||
for line in text.trim().split('\n') {
|
||||
let line = line.trim();
|
||||
empty = if line.is_empty() { empty + 1 } else { 0 };
|
||||
if empty <= 1 {
|
||||
if !out.is_empty() {
|
||||
out.push('\n');
|
||||
}
|
||||
out.push_str(line);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn escape(text: &str) -> String {
|
||||
let mut out = String::with_capacity(text.len());
|
||||
for c in text.chars() {
|
||||
match c {
|
||||
'&' => out.push_str("&"),
|
||||
'<' => out.push_str("<"),
|
||||
'>' => out.push_str(">"),
|
||||
'"' => out.push_str("""),
|
||||
'\'' => out.push_str("'"),
|
||||
c => out.push(c),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// --- the page ----------------------------------------------------------------------------
|
||||
|
||||
/// The message part: lines of italic text, their size and line height, and the signature.
|
||||
struct Message {
|
||||
lines: Vec<String>,
|
||||
size: f32,
|
||||
leading: f32,
|
||||
signature: Option<String>,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
const SIGNATURE_GAP: f32 = 24.0;
|
||||
|
||||
fn of(card: &Card, room: f32) -> Message {
|
||||
let from = card.from_name.map(clean).map(|f| f.replace('\n', " ")).filter(|f| !f.is_empty());
|
||||
let message = card.message.map(clean).filter(|m| !m.is_empty());
|
||||
let (text, signature) = match (message, from) {
|
||||
(Some(m), from) => (format!("„{m}”"), from.map(|f| format!("– {f}"))),
|
||||
(None, Some(f)) => (format!("Szeretettel küldi: {f}"), None),
|
||||
(None, None) => (
|
||||
"Fedezd fel, mit mesélnek rólad a csillagok: a születési képleted, személyre szóló elemzések, \
|
||||
és válaszok a kérdéseidre."
|
||||
.to_string(),
|
||||
None,
|
||||
),
|
||||
};
|
||||
let room = room - if signature.is_some() { Self::SIGNATURE_GAP } else { 0.0 };
|
||||
let max = MESSAGE_RIGHT - MESSAGE_LEFT;
|
||||
let sizes = [(16.5, 22.0), (15.0, 20.0), (13.5, 18.0), (12.0, 16.0)];
|
||||
for (size, leading) in sizes {
|
||||
let lines = wrap(&text, max, &|s| width(Face::SerifItalic, s, size, 0.0));
|
||||
if lines.len() as f32 * leading <= room {
|
||||
return Message { lines, size, leading, signature };
|
||||
}
|
||||
}
|
||||
// Still too long (many line breaks): the lines that fit, the last one cut.
|
||||
let (size, leading) = sizes[sizes.len() - 1];
|
||||
let mut lines = wrap(&text, max, &|s| width(Face::SerifItalic, s, size, 0.0));
|
||||
let keep = ((room / leading).floor() as usize).max(1);
|
||||
if lines.len() > keep {
|
||||
lines.truncate(keep);
|
||||
if let Some(last) = lines.last_mut() {
|
||||
while !last.is_empty() && width(Face::SerifItalic, &format!("{last} …"), size, 0.0) > max {
|
||||
last.pop();
|
||||
}
|
||||
last.push_str(" …");
|
||||
}
|
||||
}
|
||||
Message { lines, size, leading, signature }
|
||||
}
|
||||
|
||||
fn height(&self) -> f32 {
|
||||
self.lines.len() as f32 * self.leading + if self.signature.is_some() { Self::SIGNATURE_GAP } else { 0.0 }
|
||||
}
|
||||
}
|
||||
|
||||
/// "sorsfonalak.hu/bevaltas" from the redeem link.
|
||||
fn short_address(url: &str) -> &str {
|
||||
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
||||
rest.split(['?', '#']).next().unwrap_or(rest)
|
||||
}
|
||||
|
||||
/// Where the QR code and the address are, for the link areas of the PDF.
|
||||
fn link_areas(card: &Card) -> (Rect, Rect) {
|
||||
let qr = Rect::from_xywh(qr_left(), CODE_TOP + (CODE_HEIGHT - QR_SIZE) / 2.0, QR_SIZE, QR_SIZE).expect("a rect");
|
||||
let text_width = width(Face::Sans, &format!("Beváltás: {}", short_address(card.redeem_url)), 10.0, 0.0);
|
||||
let link = Rect::from_xywh(CODE_LEFT + 26.0, CODE_TOP + 84.0, text_width, 15.0).expect("a rect");
|
||||
(qr, link)
|
||||
}
|
||||
|
||||
fn qr_left() -> f32 {
|
||||
W - CODE_LEFT - 22.0 - QR_SIZE
|
||||
}
|
||||
|
||||
/// A four-pointed star (the logo's), centred on (x, y).
|
||||
fn star(x: f32, y: f32, r: f32, fill: &str) -> String {
|
||||
let i = r * 0.28;
|
||||
format!(
|
||||
r#"<path fill="{fill}" d="M{x} {t}L{a} {b}L{rr} {y}L{a} {c}L{x} {bt}L{d} {c}L{l} {y}L{d} {b}Z"/>"#,
|
||||
t = y - r,
|
||||
a = x + i,
|
||||
b = y - i,
|
||||
rr = x + r,
|
||||
c = y + i,
|
||||
bt = y + r,
|
||||
d = x - i,
|
||||
l = x - r,
|
||||
)
|
||||
}
|
||||
|
||||
/// The QR code of the redeem link as a path of `size` points at (x, y).
|
||||
fn qr(url: &str, x: f32, y: f32, size: f32) -> String {
|
||||
let Ok(code) = qrcode::QrCode::with_error_correction_level(url, qrcode::EcLevel::M) else {
|
||||
return String::new();
|
||||
};
|
||||
let n = code.width();
|
||||
let colors = code.to_colors();
|
||||
let mut d = String::new();
|
||||
for row in 0..n {
|
||||
let mut col = 0;
|
||||
while col < n {
|
||||
if colors[row * n + col] == qrcode::Color::Dark {
|
||||
let start = col;
|
||||
while col < n && colors[row * n + col] == qrcode::Color::Dark {
|
||||
col += 1;
|
||||
}
|
||||
let _ = write!(d, "M{start} {row}h{}v1h-{}z", col - start, col - start);
|
||||
} else {
|
||||
col += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let scale = size / n as f32;
|
||||
format!(r#"<path fill="{INK}" transform="translate({x} {y}) scale({scale})" d="{d}"/>"#)
|
||||
}
|
||||
|
||||
/// The page as an SVG document (points as units).
|
||||
pub fn svg(card: &Card) -> String {
|
||||
let cx = W / 2.0;
|
||||
let mut s = String::new();
|
||||
let _ = write!(s, r#"<svg xmlns="http://www.w3.org/2000/svg" width="{W}" height="{H}" viewBox="0 0 {W} {H}">"#);
|
||||
|
||||
// Paper and a double frame with stars in the corners.
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<rect width="{W}" height="{H}" fill="white"/><rect x="18" y="18" width="{}" height="{}" fill="{PAPER}" stroke="{GOLD}" stroke-width="0.9"/><rect x="24" y="24" width="{}" height="{}" fill="none" stroke="{LINE}" stroke-width="0.5"/>"#,
|
||||
W - 36.0,
|
||||
H - 36.0,
|
||||
W - 48.0,
|
||||
H - 48.0
|
||||
);
|
||||
for (x, y) in [(24.0, 24.0), (W - 24.0, 24.0), (24.0, H - 24.0), (W - 24.0, H - 24.0)] {
|
||||
s.push_str(&star(x, y, 6.0, GOLD));
|
||||
}
|
||||
|
||||
// The logo: the mark and "sorsfonalak", centred.
|
||||
let word_size = 30.0;
|
||||
let mark = 34.0;
|
||||
let gap = 10.0;
|
||||
let total = mark + gap + width(Face::Serif, "sorsfonalak", word_size, 0.3);
|
||||
let x0 = cx - total / 2.0;
|
||||
let baseline = 80.0;
|
||||
let mark_top = baseline - 9.5 - mark / 2.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<g transform="translate({x0} {mark_top}) scale({k})"><g fill="none" stroke="{GOLD}" stroke-width="4.5" stroke-linecap="round"><circle cx="32" cy="32" r="23"/><path d="M10 46 C 24 45, 29 23, 44 18"/><path d="M18 33.5 L36 33.5" stroke-width="4.2"/></g><path d="M49 6 L51.8 13.2 L59 16 L51.8 18.8 L49 26 L46.2 18.8 L39 16 L46.2 13.2 Z" fill="{INK}"/></g>"#,
|
||||
k = mark / 64.0
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{}" y="{baseline}" font-family="Cormorant Garamond" font-weight="600" font-size="{word_size}" letter-spacing="0.3" fill="{INK}">sors<tspan fill="{GOLD}">fonalak</tspan></text>"#,
|
||||
x0 + mark + gap
|
||||
);
|
||||
|
||||
// "AJÁNDÉKUTALVÁNY" between two short lines.
|
||||
let eyebrow = "AJÁNDÉKUTALVÁNY";
|
||||
let spacing = 3.2;
|
||||
let ew = width(Face::SansBold, eyebrow, 9.0, spacing) - spacing;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{}" y="108" font-family="Inter" font-weight="600" font-size="9" letter-spacing="{spacing}" fill="{GOLD}">{eyebrow}</text>"#,
|
||||
cx - ew / 2.0
|
||||
);
|
||||
for (a, b) in [(cx - ew / 2.0 - 56.0, cx - ew / 2.0 - 14.0), (cx + ew / 2.0 + 14.0, cx + ew / 2.0 + 56.0)] {
|
||||
let _ = write!(s, r#"<line x1="{a}" y1="104.8" x2="{b}" y2="104.8" stroke="{LINE}" stroke-width="0.8"/>"#);
|
||||
}
|
||||
|
||||
// The example chart with an orbit around it and a few stars.
|
||||
let wheel = 216.0;
|
||||
let wheel_top = 124.0;
|
||||
let wy = wheel_top + wheel / 2.0;
|
||||
let orbit = wheel / 2.0 + 13.0;
|
||||
let _ = write!(s, r#"<circle cx="{cx}" cy="{wy}" r="{orbit}" fill="none" stroke="{LINE}" stroke-width="0.6"/>"#);
|
||||
for (deg, r) in [(90.0_f32, 2.4), (-8.0, 1.8), (218.0, 2.0)] {
|
||||
let (sin, cos) = deg.to_radians().sin_cos();
|
||||
let _ = write!(s, r#"<circle cx="{}" cy="{}" r="{r}" fill="{GOLD}"/>"#, cx + orbit * cos, wy - orbit * sin);
|
||||
}
|
||||
for (x, y, r) in
|
||||
[(124.0, 164.0, 5.0), (462.0, 148.0, 6.5), (470.0, 304.0, 4.0), (134.0, 322.0, 6.0), (420.0, 350.0, 3.0)]
|
||||
{
|
||||
s.push_str(&star(x, y, r, LINE));
|
||||
}
|
||||
let inner = WHEEL.split_once("viewBox=\"0 0 680 680\">").map_or("", |(_, rest)| rest);
|
||||
let inner = inner.trim_end().trim_end_matches("</svg>");
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<svg x="{}" y="{wheel_top}" width="{wheel}" height="{wheel}" viewBox="0 0 680 680">{inner}</svg>"#,
|
||||
cx - wheel / 2.0
|
||||
);
|
||||
|
||||
// Whom it is for, the package and what it gives.
|
||||
if let Some(name) = card.recipient_name.map(clean).map(|n| n.replace('\n', " ")).filter(|n| !n.is_empty()) {
|
||||
let line = format!("{name} részére");
|
||||
let size = (440.0 / width(Face::SerifItalic, &line, 1.0, 0.0)).min(21.0);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{}" text-anchor="middle" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="{size}" fill="{GOLD}">{}</text>"#,
|
||||
wheel_top + wheel + 38.0,
|
||||
escape(&line)
|
||||
);
|
||||
}
|
||||
let title_y = wheel_top + wheel + 76.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{title_y}" text-anchor="middle" font-family="Cormorant Garamond" font-weight="600" font-size="36" fill="{INK}">„{}” csomag</text>"#,
|
||||
escape(card.package)
|
||||
);
|
||||
let contents = wrap_items(card.contents, " · ", 440.0, &|t| width(Face::Sans, t, 10.0, 0.0));
|
||||
let mut y = title_y + 26.0;
|
||||
for line in &contents {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{y}" text-anchor="middle" font-family="Inter" font-size="10" fill="{MUTED}" xml:space="preserve">{}</text>"#,
|
||||
escape(line)
|
||||
);
|
||||
y += 15.0;
|
||||
}
|
||||
|
||||
// A divider with a small diamond.
|
||||
let divider = y + 10.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><line x1="{}" y1="{divider}" x2="{}" y2="{divider}" stroke="{LINE}" stroke-width="0.7"/><path d="M{cx} {} l3.5 3.5 l-3.5 3.5 l-3.5 -3.5 z" fill="{GOLD}"/>"#,
|
||||
cx - 150.0,
|
||||
cx - 10.0,
|
||||
cx + 10.0,
|
||||
cx + 150.0,
|
||||
divider - 3.5
|
||||
);
|
||||
|
||||
// The message next to the avatar, centred in the room above the code box.
|
||||
let room_top = divider + 22.0;
|
||||
let room_bottom = CODE_TOP - 22.0;
|
||||
let message = Message::of(card, room_bottom - room_top);
|
||||
let block = message.height().max(AVATAR_SIZE);
|
||||
let top = room_top + ((room_bottom - room_top - block) / 2.0).max(0.0);
|
||||
let avatar_y = top + (block - AVATAR_SIZE) / 2.0;
|
||||
let r = AVATAR_SIZE / 2.0;
|
||||
let (ax, ay) = (70.0 + r, avatar_y + r);
|
||||
let avatar = base64::engine::general_purpose::STANDARD.encode(AVATAR);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<clipPath id="avatar"><circle cx="{ax}" cy="{ay}" r="{r}"/></clipPath><image x="70" y="{avatar_y}" width="{AVATAR_SIZE}" height="{AVATAR_SIZE}" clip-path="url(#avatar)" href="data:image/webp;base64,{avatar}"/><circle cx="{ax}" cy="{ay}" r="{}" fill="none" stroke="{GOLD}" stroke-width="1.2"/><circle cx="{ax}" cy="{ay}" r="{}" fill="none" stroke="{LINE}" stroke-width="0.5"/>"#,
|
||||
r + 2.5,
|
||||
r + 6.0
|
||||
);
|
||||
let text_top = top + (block - message.height()) / 2.0;
|
||||
let mut y = text_top + message.size * 0.95;
|
||||
for line in &message.lines {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{MESSAGE_LEFT}" y="{y}" font-family="{SERIF_ITALIC_FAMILY}" font-style="italic" font-weight="500" font-size="{}" fill="{INK}" xml:space="preserve">{}</text>"#,
|
||||
message.size,
|
||||
escape(line)
|
||||
);
|
||||
y += message.leading;
|
||||
}
|
||||
if let Some(signature) = &message.signature {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{MESSAGE_RIGHT}" y="{}" text-anchor="end" font-family="Cormorant Garamond" font-weight="600" font-size="15" fill="{GOLD}">{}</text>"#,
|
||||
y - message.leading + Message::SIGNATURE_GAP,
|
||||
escape(signature)
|
||||
);
|
||||
}
|
||||
|
||||
// The code, the address and the QR code in a box.
|
||||
let box_width = W - 2.0 * CODE_LEFT;
|
||||
let tx = CODE_LEFT + 26.0;
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<rect x="{CODE_LEFT}" y="{CODE_TOP}" width="{box_width}" height="{CODE_HEIGHT}" rx="10" fill="white" stroke="{GOLD}" stroke-width="1"/>"#
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{tx}" y="{}" font-family="Inter" font-weight="600" font-size="8.5" letter-spacing="2.5" fill="{GOLD}">AJÁNDÉKKÓD</text>"#,
|
||||
CODE_TOP + 30.0
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{tx}" y="{}" font-family="Inter" font-weight="600" font-size="27" letter-spacing="1.5" fill="{INK}">{}</text>"#,
|
||||
CODE_TOP + 66.0,
|
||||
escape(card.code)
|
||||
);
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{tx}" y="{}" font-family="Inter" font-size="10" fill="{MUTED}">Beváltás: <tspan fill="{INK}" font-weight="600">{}</tspan></text>"#,
|
||||
CODE_TOP + 95.0,
|
||||
escape(short_address(card.redeem_url))
|
||||
);
|
||||
s.push_str(&qr(card.redeem_url, qr_left(), CODE_TOP + (CODE_HEIGHT - QR_SIZE) / 2.0, QR_SIZE));
|
||||
|
||||
// How to redeem it.
|
||||
let how = "Lépj be vagy regisztrálj a sorsfonalak.hu oldalon, és írd be a kódot a „Kód beváltása” oldalon, \
|
||||
vagy olvasd be a QR-kódot a telefonoddal. A kód egyszer váltható be, és nem jár le.";
|
||||
let mut y = CODE_TOP + CODE_HEIGHT + 26.0;
|
||||
for line in wrap(how, 430.0, &|t| width(Face::Sans, t, 9.0, 0.0)) {
|
||||
let _ = write!(
|
||||
s,
|
||||
r#"<text x="{cx}" y="{y}" text-anchor="middle" font-family="Inter" font-size="9" fill="{MUTED}">{}</text>"#,
|
||||
escape(&line)
|
||||
);
|
||||
y += 13.0;
|
||||
}
|
||||
|
||||
s.push_str("</svg>");
|
||||
s
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn contents() -> Vec<String> {
|
||||
[
|
||||
"2 részletes képletelemzés",
|
||||
"1 kapcsolati elemzés",
|
||||
"2 éves előrejelzés",
|
||||
"1 személyhely",
|
||||
"3 kérdés",
|
||||
"5 kártyajóslás",
|
||||
]
|
||||
.map(String::from)
|
||||
.to_vec()
|
||||
}
|
||||
|
||||
fn card<'a>(contents: &'a [String], message: Option<&'a str>, from: Option<&'a str>) -> Card<'a> {
|
||||
Card {
|
||||
package: "Páros",
|
||||
contents,
|
||||
code: "ABCD-EFGH-JKMN",
|
||||
redeem_url: "https://sorsfonalak.hu/bevaltas?kod=ABCD-EFGH-JKMN",
|
||||
recipient_name: Some("Bea"),
|
||||
from_name: from,
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fonts_are_found_by_their_names() {
|
||||
let db = fonts();
|
||||
let families: Vec<String> = db.faces().flat_map(|f| f.families.iter().map(|(n, _)| n.clone())).collect();
|
||||
for family in ["Cormorant Garamond", "Inter", "DejaVu Sans"] {
|
||||
assert!(families.iter().any(|f| f == family), "{family} not in {families:?}");
|
||||
}
|
||||
let italic = db.query(&fontdb::Query {
|
||||
families: &[fontdb::Family::Name(SERIF_ITALIC_FAMILY)],
|
||||
weight: fontdb::Weight(500),
|
||||
style: fontdb::Style::Italic,
|
||||
..Default::default()
|
||||
});
|
||||
assert!(italic.is_some_and(|id| db.face(id).is_some_and(|f| f.style == fontdb::Style::Italic)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_card_is_a_pdf_with_its_text() {
|
||||
let contents = contents();
|
||||
let pdf = pdf(&card(&contents, Some("Boldog születésnapot! Ölelés: Ági"), Some("Ági & <Péter>"))).unwrap();
|
||||
assert!(pdf.starts_with(b"%PDF-"));
|
||||
assert!(pdf.len() < 400_000, "{} bytes", pdf.len());
|
||||
// The redeem link is clickable.
|
||||
assert!(pdf.windows(26).any(|w| w == b"sorsfonalak.hu/bevaltas?ko"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_messages_get_smaller_and_still_fit() {
|
||||
let contents = contents();
|
||||
let short = Message::of(&card(&contents, Some("Boldog születésnapot!"), Some("Ági")), 150.0);
|
||||
assert_eq!((short.lines.len(), short.size), (1, 16.5));
|
||||
let long = "Nagyon sok boldog születésnapot kívánok! ".repeat(7);
|
||||
let m = Message::of(&card(&contents, Some(&long), Some("Ági")), 150.0);
|
||||
assert!(m.size < 16.5 && m.height() <= 150.0, "{} lines of {}", m.lines.len(), m.size);
|
||||
// Line after line: what does not fit is cut, with an ellipsis.
|
||||
let lines = "a\n".repeat(40);
|
||||
let m = Message::of(&card(&contents, Some(&lines), None), 150.0);
|
||||
assert!(m.height() <= 150.0 && m.lines.last().unwrap().ends_with('…'));
|
||||
// One endless word is broken.
|
||||
let word = "a".repeat(300);
|
||||
let m = Message::of(&card(&contents, Some(&word), None), 150.0);
|
||||
assert!(m.lines.iter().all(|l| width(Face::SerifItalic, l, m.size, 0.0) <= MESSAGE_RIGHT - MESSAGE_LEFT));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn user_text_is_escaped_and_cleaned() {
|
||||
let contents = contents();
|
||||
let svg = svg(&card(&contents, Some("<b>szia</b>\u{7}\n\n\n\nvége"), Some("Ági & \"Péter\"")));
|
||||
assert!(svg.contains("<b>szia</b>") && !svg.contains('\u{7}'));
|
||||
assert!(svg.contains("– Ági & "Péter""));
|
||||
assert_eq!(clean(" a\n\n\n\nb "), "a\n\nb");
|
||||
usvg::Tree::from_str(&svg, &usvg::Options::default()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn without_a_message_the_card_still_says_something() {
|
||||
let contents = contents();
|
||||
assert!(svg(&card(&contents, None, Some("Ági"))).contains("Szeretettel küldi: Ági"));
|
||||
assert!(svg(&card(&contents, None, None)).contains(">Bea részére</text>"));
|
||||
let nameless = Card { recipient_name: None, ..card(&contents, None, None) };
|
||||
assert!(!svg(&nameless).contains("részére"));
|
||||
assert!(svg(&card(&contents, None, None)).contains("Fedezd fel"));
|
||||
assert_eq!(short_address("https://sorsfonalak.hu/bevaltas?kod=X"), "sorsfonalak.hu/bevaltas");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user