use std::collections::BTreeMap;
use std::sync::LazyLock;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::core::custom_fields::{
CheckoutCustomField, CustomFieldTranslations, decode_custom_fields, encode_custom_fields,
parse_custom_fields_loose,
};
trait WireEnum: Sized + Copy {
fn parse_wire(value: &str) -> Option<Self>;
}
macro_rules! wire_enum {
(
$(#[$meta:meta])*
$name:ident {
$( $(#[$vmeta:meta])* $variant:ident => $wire:literal ),+ $(,)?
}
) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum $name {
$( $(#[$vmeta])* $variant, )+
}
impl $name {
pub const fn as_str(self) -> &'static str {
match self { $( Self::$variant => $wire, )+ }
}
pub fn from_wire(value: &str) -> Option<Self> {
match value {
$( $wire => Some(Self::$variant), )+
_ => None,
}
}
}
impl WireEnum for $name {
fn parse_wire(value: &str) -> Option<Self> { Self::from_wire(value) }
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl Serialize for $name {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
Self::from_wire(&raw).ok_or_else(|| {
serde::de::Error::custom(format!(
concat!("unknown ", stringify!($name), " value: {}"),
raw
))
})
}
}
};
}
wire_enum! {
CornerRadius {
Square => "square",
Small => "small",
Medium => "medium",
Large => "large",
Pill => "pill",
}
}
wire_enum! {
NonPillRadius {
Square => "square",
Small => "small",
Medium => "medium",
Large => "large",
}
}
impl From<NonPillRadius> for CornerRadius {
fn from(value: NonPillRadius) -> Self {
match value {
NonPillRadius::Square => CornerRadius::Square,
NonPillRadius::Small => CornerRadius::Small,
NonPillRadius::Medium => CornerRadius::Medium,
NonPillRadius::Large => CornerRadius::Large,
}
}
}
wire_enum! {
SpacingScale {
Compact => "compact",
Comfortable => "comfortable",
Spacious => "spacious",
}
}
wire_enum! {
SizeScale {
Sm => "sm",
Md => "md",
Lg => "lg",
}
}
wire_enum! {
SurfaceStyle {
Flat => "flat",
Outlined => "outlined",
Elevated => "elevated",
}
}
wire_enum! {
FontFamily {
Inter => "inter",
System => "system",
Serif => "serif",
Mono => "mono",
Roboto => "roboto",
Poppins => "poppins",
Manrope => "manrope",
DmSans => "dm-sans",
SpaceGrotesk => "space-grotesk",
PlexSans => "plex-sans",
WorkSans => "work-sans",
OpenSans => "open-sans",
Lora => "lora",
Playfair => "playfair",
PlexMono => "plex-mono",
JetbrainsMono => "jetbrains-mono",
}
}
wire_enum! {
FontWeight {
Regular => "regular",
Medium => "medium",
Semibold => "semibold",
Bold => "bold",
}
}
wire_enum! {
LayoutStyle {
Compact => "compact",
Split => "split",
}
}
wire_enum! {
SummaryPosition {
Left => "left",
Right => "right",
}
}
wire_enum! {
LabelStyle {
Above => "above",
Hidden => "hidden",
}
}
wire_enum! {
LegacyLabelType {
Above => "above",
Never => "never",
}
}
wire_enum! {
PaymentLayout {
Tabs => "tabs",
Accordion => "accordion",
SpacedAccordion => "spaced_accordion",
}
}
wire_enum! {
LogoShape {
Square => "square",
Rounded => "rounded",
Circle => "circle",
}
}
wire_enum! {
LogoSize {
Sm => "sm",
Md => "md",
Lg => "lg",
}
}
wire_enum! {
SurchargePosition {
Inline => "inline",
Trailing => "trailing",
Below => "below",
Above => "above",
CornerStart => "cornerStart",
CornerEnd => "cornerEnd",
}
}
wire_enum! {
NativeElementPosition {
Top => "top",
BelowFields => "belowFields",
BelowCard => "belowCard",
Bottom => "bottom",
}
}
wire_enum! {
SurchargeStyle {
Plain => "plain",
Badge => "badge",
Outline => "outline",
Solid => "solid",
Underline => "underline",
Ribbon => "ribbon",
}
}
wire_enum! {
SurchargeBorderWidth {
None => "none",
Thin => "thin",
Medium => "medium",
Thick => "thick",
}
}
wire_enum! {
SurchargeBorderStyle {
Solid => "solid",
Dashed => "dashed",
Dotted => "dotted",
}
}
wire_enum! {
SurchargeSize {
Sm => "sm",
Md => "md",
Lg => "lg",
}
}
wire_enum! {
SurchargeShape {
Pill => "pill",
Rounded => "rounded",
Square => "square",
}
}
wire_enum! {
SurchargeWeight {
Regular => "regular",
Medium => "medium",
Bold => "bold",
}
}
wire_enum! {
SurchargeSign {
Always => "always",
MinusOnly => "minusOnly",
None => "none",
}
}
wire_enum! {
SurchargeLabelMode {
Amount => "amount",
Labelled => "labelled",
}
}
wire_enum! {
SurchargeFigureMode {
Amount => "amount",
Percent => "percent",
AmountThenPercent => "amountThenPercent",
PercentThenAmount => "percentThenAmount",
}
}
wire_enum! {
AirwallexCardPreset {
SingleRow => "single_row",
SplitFields => "split_fields",
SplitFieldsLabelled => "split_fields_labelled",
Stacked => "stacked",
NumberExpiryRow => "number_expiry_row",
Compact => "compact",
}
}
wire_enum! {
AirwallexFieldChrome {
Outlined => "outlined",
Filled => "filled",
Underline => "underline",
}
}
wire_enum! {
AirwallexLabelStyle {
Above => "above",
Inline => "inline",
Floating => "floating",
None => "none",
}
}
wire_enum! {
AirwallexFieldFontSize {
Sm => "sm",
Md => "md",
Lg => "lg",
}
}
wire_enum! {
AirwallexFieldWeight {
Regular => "regular",
Medium => "medium",
Semibold => "semibold",
}
}
wire_enum! {
AirwallexFocusRing {
None => "none",
Subtle => "subtle",
Strong => "strong",
}
}
wire_enum! {
AirwallexAutofillTreatment {
System => "system",
Brand => "brand",
Neutral => "neutral",
}
}
pub type CardFieldChrome = AirwallexFieldChrome;
pub type CardFieldFontSize = AirwallexFieldFontSize;
pub type CardFieldWeight = AirwallexFieldWeight;
pub type CardFocusRing = AirwallexFocusRing;
wire_enum! {
CancelLinkPosition {
Top => "top",
Bottom => "bottom",
}
}
wire_enum! {
CancelLinkStyle {
Link => "link",
Button => "button",
}
}
wire_enum! {
StripeTheme {
Auto => "auto",
Stripe => "stripe",
Flat => "flat",
Night => "night",
}
}
wire_enum! {
StripeInputStyle {
Spaced => "spaced",
Condensed => "condensed",
}
}
wire_enum! {
StripeLabelPlacement {
Above => "above",
Floating => "floating",
}
}
wire_enum! {
StripeSpacing {
Compact => "compact",
Comfortable => "comfortable",
Spacious => "spacious",
}
}
wire_enum! {
PaypalCardLayout {
Split => "split",
Stacked => "stacked",
}
}
wire_enum! {
PaypalLabelStyle {
Above => "above",
None => "none",
}
}
wire_enum! {
NomupayFormStyle {
Plain => "plain",
Card => "card",
}
}
wire_enum! {
ApplePayButtonStyle {
Auto => "auto",
Black => "black",
White => "white",
WhiteOutline => "white-outline",
}
}
wire_enum! {
ApplePayButtonType {
Pay => "pay",
Plain => "plain",
Buy => "buy",
CheckOut => "check-out",
Continue => "continue",
Book => "book",
Order => "order",
Subscribe => "subscribe",
Donate => "donate",
Contribute => "contribute",
Support => "support",
Tip => "tip",
AddMoney => "add-money",
TopUp => "top-up",
Reload => "reload",
Rent => "rent",
}
}
wire_enum! {
GooglePayButtonColor {
Auto => "auto",
Default => "default",
Black => "black",
White => "white",
}
}
wire_enum! {
GooglePayButtonType {
Pay => "pay",
Plain => "plain",
Buy => "buy",
Checkout => "checkout",
Book => "book",
Order => "order",
Subscribe => "subscribe",
Donate => "donate",
}
}
wire_enum! {
WhopCardPreset {
Accordion => "accordion",
Tiles => "tiles",
CardStacked => "card_stacked",
CardCompact => "card_compact",
}
}
wire_enum! {
WhopAccentColor {
Auto => "auto",
Gray => "gray",
Blue => "blue",
Indigo => "indigo",
Iris => "iris",
Violet => "violet",
Purple => "purple",
Plum => "plum",
Pink => "pink",
Crimson => "crimson",
Ruby => "ruby",
Red => "red",
Tomato => "tomato",
Orange => "orange",
Amber => "amber",
Yellow => "yellow",
Lime => "lime",
Grass => "grass",
Green => "green",
Jade => "jade",
Teal => "teal",
Cyan => "cyan",
Sky => "sky",
Mint => "mint",
Brown => "brown",
Bronze => "bronze",
Gold => "gold",
}
}
wire_enum! {
WhopGrayColor {
Auto => "auto",
Gray => "gray",
Mauve => "mauve",
Slate => "slate",
Sage => "sage",
Olive => "olive",
Sand => "sand",
}
}
wire_enum! {
WhopBillingDetails {
Minimal => "minimal",
Full => "full",
}
}
wire_enum! {
WhopEmailLabel {
Above => "above",
Floating => "floating",
}
}
wire_enum! {
WhopRadius {
Checkout => "checkout",
Square => "square",
Small => "small",
Medium => "medium",
Large => "large",
}
}
wire_enum! {
WhopShadow {
None => "none",
Soft => "soft",
}
}
wire_enum! {
WhopSelection {
RadioTint => "radio_tint",
Radio => "radio",
Tint => "tint",
}
}
wire_enum! {
NoticeSection {
Summary => "summary",
Payment => "payment",
}
}
wire_enum! {
NoticeIcon {
Lock => "lock",
Shield => "shield",
Check => "check",
Truck => "truck",
Package => "package",
Refresh => "refresh",
Star => "star",
Support => "support",
Globe => "globe",
Tag => "tag",
Heart => "heart",
Leaf => "leaf",
Clock => "clock",
Bank => "bank",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustBadge {
pub id: String,
pub label: String,
pub text_color: String,
pub background_color: String,
#[serde(default)]
pub border_color: Option<String>,
}
impl TrustBadge {
pub fn new(
id: impl Into<String>,
label: impl Into<String>,
text_color: impl Into<String>,
background_color: impl Into<String>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
text_color: text_color.into(),
background_color: background_color.into(),
border_color: None,
}
}
#[must_use]
pub fn border_color(mut self, colour: impl Into<String>) -> Self {
self.border_color = Some(colour.into());
self
}
}
pub const NOTICES_PER_SECTION: usize = 3;
pub const NOTICE_LABEL_MAX_LENGTH: usize = 80;
const NOTICE_ID_MAX_LENGTH: usize = 40;
pub const NOTICE_ICON_FALLBACK: NoticeIcon = NoticeIcon::Check;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckoutNotice {
pub id: String,
pub section: NoticeSection,
pub icon: NoticeIcon,
pub label: String,
#[serde(default)]
pub label_translations: CustomFieldTranslations,
}
impl CheckoutNotice {
pub fn new(
id: impl Into<String>,
section: NoticeSection,
icon: NoticeIcon,
label: impl Into<String>,
) -> Self {
Self {
id: id.into(),
section,
icon,
label: label.into(),
label_translations: CustomFieldTranslations::new(),
}
}
#[must_use]
pub fn translation(mut self, locale: impl Into<String>, label: impl Into<String>) -> Self {
self.label_translations.insert(locale.into(), label.into());
self
}
}
pub static DEFAULT_NOTICES: LazyLock<Vec<CheckoutNotice>> = LazyLock::new(|| {
vec![
CheckoutNotice::new(
"secure",
NoticeSection::Summary,
NoticeIcon::Shield,
"Secure payment",
)
.translation("de", "Sichere Zahlung")
.translation("fr", "Paiement sécurisé")
.translation("es", "Pago seguro")
.translation("it", "Pagamento sicuro")
.translation("nl", "Veilig betalen")
.translation("zh", "安全支付")
.translation("zh-Hant", "安全付款")
.translation("hi", "सुरक्षित भुगतान")
.translation("ar", "دفع آمن"),
CheckoutNotice::new(
"ssl",
NoticeSection::Summary,
NoticeIcon::Lock,
"Encrypted · 256-bit SSL",
)
.translation("de", "Verschlüsselt · 256-Bit-SSL")
.translation("fr", "Chiffré · SSL 256 bits")
.translation("es", "Cifrado · SSL de 256 bits")
.translation("it", "Crittografato · SSL a 256 bit")
.translation("nl", "Versleuteld · 256-bit SSL")
.translation("zh", "加密 · 256 位 SSL")
.translation("zh-Hant", "加密 · 256 位元 SSL")
.translation("hi", "एन्क्रिप्टेड · 256-बिट SSL")
.translation("ar", "مشفّر · SSL بطول 256 بت"),
]
});
pub fn default_notices() -> Vec<CheckoutNotice> {
DEFAULT_NOTICES.clone()
}
fn js_trim(value: &str) -> &str {
fn is_js_space(c: char) -> bool {
matches!(
c,
'\t' | '\n'
| '\u{000B}'
| '\u{000C}'
| '\r'
| ' '
| '\u{00A0}'
| '\u{1680}'
| '\u{2000}'
..='\u{200A}'
| '\u{2028}'
| '\u{2029}'
| '\u{202F}'
| '\u{205F}'
| '\u{3000}'
| '\u{FEFF}'
)
}
value.trim_matches(is_js_space)
}
fn cap_notice_text(value: &str) -> String {
value.chars().take(NOTICE_LABEL_MAX_LENGTH).collect()
}
fn parse_notice_translations(raw: Option<&Value>) -> CustomFieldTranslations {
let parsed;
let value = match raw {
Some(Value::String(s)) => match serde_json::from_str::<Value>(s) {
Ok(v) => {
parsed = v;
&parsed
}
Err(_) => return CustomFieldTranslations::new(),
},
Some(v) => v,
None => return CustomFieldTranslations::new(),
};
let mut out = CustomFieldTranslations::new();
if let Some(obj) = value.as_object() {
for (k, v) in obj {
if let Some(text) = v.as_str()
&& !js_trim(text).is_empty()
{
out.insert(k.clone(), text.to_string());
}
}
}
out
}
fn normalize_notices(list: &[Value]) -> Vec<CheckoutNotice> {
let mut seen = std::collections::BTreeSet::new();
let mut per_section: BTreeMap<&'static str, usize> = BTreeMap::new();
let mut out = Vec::new();
for (index, raw) in list.iter().enumerate() {
let Some(src) = raw.as_object() else {
continue;
};
let label = src
.get("label")
.and_then(Value::as_str)
.map(cap_notice_text)
.unwrap_or_default();
let label_translations: CustomFieldTranslations =
parse_notice_translations(src.get("labelTranslations"))
.into_iter()
.map(|(locale, text)| (locale, cap_notice_text(&text)))
.collect();
if js_trim(&label).is_empty() && label_translations.is_empty() {
continue;
}
let section = pick_enum(src.get("section"), NoticeSection::Summary);
let used = per_section.entry(section.as_str()).or_insert(0);
if *used >= NOTICES_PER_SECTION {
continue;
}
*used += 1;
let mut id: String = src
.get("id")
.and_then(Value::as_str)
.map(|raw| {
raw.chars()
.filter(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '-')
.take(NOTICE_ID_MAX_LENGTH)
.collect()
})
.unwrap_or_default();
if id.is_empty() || seen.contains(&id) {
id = format!("notice-{}", index + 1);
}
while seen.contains(&id) {
id.push('x');
}
seen.insert(id.clone());
out.push(CheckoutNotice {
id,
section,
icon: pick_enum(src.get("icon"), NOTICE_ICON_FALLBACK),
label,
label_translations,
});
}
out
}
pub fn decode_notices(raw: Option<&str>) -> Option<Vec<CheckoutNotice>> {
let parsed: Value = serde_json::from_str(raw?).ok()?;
parsed.as_array().map(Vec::as_slice).map(normalize_notices)
}
pub fn parse_notices_loose(raw: Option<&Value>) -> Option<Vec<CheckoutNotice>> {
match raw? {
Value::String(s) => decode_notices(Some(s)),
Value::Array(items) => Some(normalize_notices(items)),
_ => None,
}
}
#[derive(Serialize)]
struct NoticeWire<'a> {
id: &'a str,
section: &'static str,
icon: &'static str,
label: &'a str,
#[serde(rename = "labelTranslations", skip_serializing_if = "Option::is_none")]
label_translations: Option<BTreeMap<&'a str, &'a str>>,
}
pub fn encode_notices(notices: &[CheckoutNotice]) -> String {
let wire: Vec<NoticeWire<'_>> = notices
.iter()
.map(|n| {
let translations: BTreeMap<&str, &str> = n
.label_translations
.iter()
.filter(|(_, text)| !js_trim(text).is_empty())
.map(|(locale, text)| (locale.as_str(), text.as_str()))
.collect();
NoticeWire {
id: &n.id,
section: n.section.as_str(),
icon: n.icon.as_str(),
label: &n.label,
label_translations: (!translations.is_empty()).then_some(translations),
}
})
.collect();
serde_json::to_string(&wire).unwrap_or_else(|_| "[]".to_string())
}
fn notice_translation_for(map: &CustomFieldTranslations, locale: Option<&str>) -> Option<String> {
let locale = locale.filter(|l| !l.is_empty())?;
let mut folded: BTreeMap<String, &str> = BTreeMap::new();
for (k, v) in map {
if !v.is_empty() {
folded.entry(k.to_lowercase()).or_insert(v.as_str());
}
}
let parts: Vec<String> = locale
.to_lowercase()
.split('-')
.map(str::to_string)
.collect();
(1..=parts.len())
.rev()
.find_map(|i| folded.get(&parts[..i].join("-")).map(|v| (*v).to_string()))
}
pub fn notice_text(notice: &CheckoutNotice, locale: Option<&str>) -> String {
notice_translation_for(¬ice.label_translations, locale)
.unwrap_or_else(|| notice.label.clone())
}
pub fn notices_in(notices: &[CheckoutNotice], section: NoticeSection) -> Vec<&CheckoutNotice> {
notices
.iter()
.filter(|n| n.section == section)
.take(NOTICES_PER_SECTION)
.collect()
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ShownNotice<'a> {
pub notice: &'a CheckoutNotice,
pub text: String,
}
pub fn shown_notices<'a>(
notices: &'a [CheckoutNotice],
section: NoticeSection,
locale: Option<&str>,
) -> Vec<ShownNotice<'a>> {
notices_in(notices, section)
.into_iter()
.map(|notice| ShownNotice {
notice,
text: js_trim(¬ice_text(notice, locale)).to_string(),
})
.filter(|shown| !shown.text.is_empty())
.collect()
}
fn hex6_channels(hex: &str) -> Option<[u8; 3]> {
let rest = hex.trim().strip_prefix('#')?;
if rest.len() != 6 || !rest.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let ch = |i: usize| u8::from_str_radix(&rest[i..i + 2], 16).ok();
Some([ch(0)?, ch(2)?, ch(4)?])
}
fn is_theme_tinted_badge_colouring(text_color: &str, fill: &str, border: &str) -> bool {
let (Some(primary), Some(bg), Some(line)) = (
hex6_channels(text_color),
hex6_channels(fill),
hex6_channels(border),
) else {
return false;
};
let mixed =
|surface: f64, to: f64, share: f64| (surface + (to - surface) * share + 0.5).floor();
(0..3).all(|i| {
let p = f64::from(primary[i]);
(0..=255).any(|surface| {
let surface = f64::from(surface);
mixed(surface, p, 0.08) == f64::from(bg[i])
&& mixed(surface, p, 0.3) == f64::from(line[i])
})
})
}
pub fn is_default_badge_set(badges: &[TrustBadge]) -> bool {
if badges.len() != DEFAULT_BADGES.len() {
return false;
}
let same_content = badges
.iter()
.zip(DEFAULT_BADGES.iter())
.all(|(b, d)| b.id == d.id && b.label == d.label);
if !same_content {
return false;
}
let colouring = |set: &[TrustBadge]| -> Vec<String> {
set.iter()
.map(|b| {
format!(
"{}|{}|{}",
b.text_color,
b.background_color,
b.border_color.as_deref().unwrap_or("")
)
.to_lowercase()
})
.collect()
};
let mine = colouring(badges);
if mine == colouring(DEFAULT_BADGES.as_slice())
|| mine == colouring(DEFAULT_BADGES_DARK.as_slice())
{
return true;
}
let first = &badges[0];
let Some(border) = first.border_color.as_deref().filter(|b| !b.is_empty()) else {
return false;
};
let same = |a: &str, b: &str| a.eq_ignore_ascii_case(b);
badges.iter().all(|b| {
same(&b.text_color, &first.text_color)
&& same(&b.background_color, &first.background_color)
&& same(b.border_color.as_deref().unwrap_or(""), border)
}) && is_theme_tinted_badge_colouring(&first.text_color, &first.background_color, border)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NoticesAndBadges {
pub trust_badges: Vec<TrustBadge>,
pub notices: Vec<CheckoutNotice>,
}
pub fn resolve_notices_and_badges(
saved_badges: Option<Vec<TrustBadge>>,
saved_notices: Option<Vec<CheckoutNotice>>,
) -> NoticesAndBadges {
if let Some(notices) = saved_notices {
return NoticesAndBadges {
trust_badges: saved_badges.unwrap_or_default(),
notices,
};
}
match saved_badges {
Some(badges) if !is_default_badge_set(&badges) => NoticesAndBadges {
trust_badges: badges,
notices: Vec::new(),
},
_ => NoticesAndBadges {
trust_badges: Vec::new(),
notices: default_notices(),
},
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CheckoutBranding {
pub display_name: String,
pub logo_url: String,
pub tagline: String,
pub show_logo: bool,
pub logo_shape: LogoShape,
pub logo_size: LogoSize,
pub primary: String,
pub background: String,
pub surface: String,
pub text: String,
pub heading: String,
pub muted: String,
pub border: String,
pub accent_text: String,
pub button_background: String,
pub button_text: String,
pub font_family: FontFamily,
pub heading_weight: FontWeight,
pub radius_surface: NonPillRadius,
pub radius_input: NonPillRadius,
pub radius_button: CornerRadius,
pub radius_badge: CornerRadius,
pub surface_style: SurfaceStyle,
pub surface_padding: SpacingScale,
pub vertical_gap: SpacingScale,
pub input_size: SizeScale,
pub button_size: SizeScale,
pub layout: LayoutStyle,
pub summary_position: SummaryPosition,
pub show_order_summary: bool,
pub summary_gradient: bool,
pub show_total: bool,
pub total_label: String,
pub show_currency_code: bool,
pub show_order_items: bool,
pub cancel_link_enabled: bool,
pub cancel_link_position: CancelLinkPosition,
pub cancel_link_style: CancelLinkStyle,
pub show_surcharge: bool,
pub surcharge_position: SurchargePosition,
pub native_element_position: NativeElementPosition,
pub native_element_stacked: bool,
pub surcharge_style: SurchargeStyle,
pub surcharge_size: SurchargeSize,
pub surcharge_shape: SurchargeShape,
pub surcharge_border_width: SurchargeBorderWidth,
pub surcharge_border_style: SurchargeBorderStyle,
pub surcharge_weight: SurchargeWeight,
pub surcharge_sign: SurchargeSign,
pub surcharge_uppercase: bool,
pub surcharge_label: SurchargeLabelMode,
pub surcharge_figure: SurchargeFigureMode,
pub discount_figure: SurchargeFigureMode,
pub surcharge_color: String,
pub discount_color: String,
pub method_section_order: MethodSectionOrder,
pub method_section_labels: MethodSectionLabels,
pub trust_badges: Vec<TrustBadge>,
pub notices: Vec<CheckoutNotice>,
pub custom_fields: Vec<CheckoutCustomField>,
pub header_text: String,
pub pay_button_label: String,
pub card_terms_message: String,
pub footer_text: String,
pub support_email: String,
pub payment_layout: PaymentLayout,
pub label_style: LabelStyle,
pub airwallex_card_preset: Option<AirwallexCardPreset>,
pub airwallex_hide_card: bool,
pub airwallex_hide_card_title: bool,
pub airwallex_field_chrome: AirwallexFieldChrome,
pub airwallex_label_style: Option<AirwallexLabelStyle>,
pub airwallex_field_font_size: AirwallexFieldFontSize,
pub airwallex_field_weight: AirwallexFieldWeight,
pub airwallex_focus_ring: AirwallexFocusRing,
pub airwallex_autofill: AirwallexAutofillTreatment,
pub airwallex_valid_tint: bool,
pub airwallex_network_marks: bool,
pub stripe_theme: StripeTheme,
pub stripe_inputs: StripeInputStyle,
pub stripe_labels: StripeLabelPlacement,
pub stripe_spacing: StripeSpacing,
pub stripe_field_font_size: CardFieldFontSize,
pub stripe_field_weight: CardFieldWeight,
pub stripe_focus_ring: CardFocusRing,
pub stripe_disable_animations: bool,
pub paypal_card_layout: PaypalCardLayout,
pub paypal_label_style: PaypalLabelStyle,
pub paypal_field_chrome: CardFieldChrome,
pub mollie_field_chrome: CardFieldChrome,
pub paypal_field_font_size: CardFieldFontSize,
pub mollie_field_font_size: CardFieldFontSize,
pub paypal_field_weight: CardFieldWeight,
pub mollie_field_weight: CardFieldWeight,
pub paypal_focus_ring: CardFocusRing,
pub mollie_focus_ring: CardFocusRing,
pub paypal_valid_tint: bool,
pub epayouts_card_layout: PaypalCardLayout,
pub epayouts_label_style: PaypalLabelStyle,
pub epayouts_field_chrome: CardFieldChrome,
pub epayouts_field_font_size: CardFieldFontSize,
pub epayouts_field_weight: CardFieldWeight,
pub epayouts_focus_ring: CardFocusRing,
pub epayouts_valid_tint: bool,
pub nomupay_form_style: NomupayFormStyle,
pub nomupay_show_labels: bool,
pub nomupay_show_placeholders: bool,
pub nomupay_show_cvv_hint: bool,
pub nomupay_field_chrome: CardFieldChrome,
pub nomupay_field_font_size: CardFieldFontSize,
pub nomupay_focus_ring: CardFocusRing,
pub nomupay_apple_pay_button_style: ApplePayButtonStyle,
pub nomupay_apple_pay_button_type: ApplePayButtonType,
pub nomupay_google_pay_button_color: GooglePayButtonColor,
pub nomupay_google_pay_button_type: GooglePayButtonType,
pub micropayment_field_chrome: CardFieldChrome,
pub micropayment_field_font_size: CardFieldFontSize,
pub micropayment_field_weight: CardFieldWeight,
pub micropayment_focus_ring: CardFocusRing,
pub whop_card_preset: WhopCardPreset,
pub whop_accent_color: WhopAccentColor,
pub whop_gray_color: WhopGrayColor,
pub whop_billing_details: WhopBillingDetails,
pub whop_separated: bool,
pub whop_email_label: WhopEmailLabel,
pub whop_field_chrome: CardFieldChrome,
pub whop_field_font_size: CardFieldFontSize,
pub whop_field_weight: CardFieldWeight,
pub whop_focus_ring: CardFocusRing,
pub whop_radius: WhopRadius,
pub whop_shadow: WhopShadow,
pub whop_method_icons: bool,
pub whop_selection: WhopSelection,
pub show_powered_by: bool,
pub custom_css: String,
}
impl Default for CheckoutBranding {
fn default() -> Self {
DEFAULT_BRANDING.clone()
}
}
pub const fn font_stack(family: FontFamily) -> &'static str {
match family {
FontFamily::Inter => "'Inter Variable', 'Inter', system-ui, -apple-system, sans-serif",
FontFamily::System => {
"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif"
}
FontFamily::Serif => "Georgia, 'Times New Roman', serif",
FontFamily::Mono => "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
FontFamily::Roboto => "'Roboto', system-ui, sans-serif",
FontFamily::Poppins => "'Poppins', system-ui, sans-serif",
FontFamily::Manrope => "'Manrope Variable', 'Manrope', system-ui, sans-serif",
FontFamily::DmSans => "'DM Sans Variable', 'DM Sans', system-ui, sans-serif",
FontFamily::SpaceGrotesk => {
"'Space Grotesk Variable', 'Space Grotesk', system-ui, sans-serif"
}
FontFamily::PlexSans => "'IBM Plex Sans', system-ui, sans-serif",
FontFamily::WorkSans => "'Work Sans Variable', 'Work Sans', system-ui, sans-serif",
FontFamily::OpenSans => "'Open Sans Variable', 'Open Sans', system-ui, sans-serif",
FontFamily::Lora => "'Lora Variable', 'Lora', Georgia, serif",
FontFamily::Playfair => "'Playfair Display Variable', 'Playfair Display', Georgia, serif",
FontFamily::PlexMono => "'IBM Plex Mono', ui-monospace, monospace",
FontFamily::JetbrainsMono => {
"'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, monospace"
}
}
}
pub const fn radius_value(radius: CornerRadius) -> &'static str {
match radius {
CornerRadius::Square => "0px",
CornerRadius::Small => "6px",
CornerRadius::Medium => "12px",
CornerRadius::Large => "20px",
CornerRadius::Pill => "999px",
}
}
pub const fn font_weight_value(weight: FontWeight) -> &'static str {
match weight {
FontWeight::Regular => "400",
FontWeight::Medium => "500",
FontWeight::Semibold => "600",
FontWeight::Bold => "700",
}
}
pub const fn surface_pad_value(scale: SpacingScale) -> &'static str {
match scale {
SpacingScale::Compact => "1rem",
SpacingScale::Comfortable => "1.5rem",
SpacingScale::Spacious => "2rem",
}
}
pub const fn vertical_gap_value(scale: SpacingScale) -> &'static str {
match scale {
SpacingScale::Compact => "0.75rem",
SpacingScale::Comfortable => "1rem",
SpacingScale::Spacious => "1.5rem",
}
}
pub const fn input_pad_value(size: SizeScale) -> &'static str {
match size {
SizeScale::Sm => "0.5rem 0.75rem",
SizeScale::Md => "0.625rem 0.75rem",
SizeScale::Lg => "0.875rem 0.875rem",
}
}
pub const fn button_pad_value(size: SizeScale) -> &'static str {
match size {
SizeScale::Sm => "0.625rem 1rem",
SizeScale::Md => "0.875rem 1.25rem",
SizeScale::Lg => "1.125rem 1.5rem",
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogoDimensions {
pub px: u32,
pub radius: u32,
}
pub const fn logo_dimensions(size: LogoSize) -> LogoDimensions {
match size {
LogoSize::Sm => LogoDimensions { px: 36, radius: 8 },
LogoSize::Lg => LogoDimensions { px: 64, radius: 16 },
LogoSize::Md => LogoDimensions { px: 48, radius: 12 },
}
}
pub const fn shadow_for(style: SurfaceStyle) -> &'static str {
match style {
SurfaceStyle::Elevated => {
"0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 32px -12px rgba(15, 23, 42, 0.08)"
}
SurfaceStyle::Outlined | SurfaceStyle::Flat => "none",
}
}
pub fn is_hex_color(value: &str) -> bool {
let t = value.trim();
let Some(rest) = t.strip_prefix('#') else {
return false;
};
if rest.len() != 3 && rest.len() != 6 {
return false;
}
rest.bytes().all(|b| b.is_ascii_hexdigit())
}
pub const WCAG_AA_TEXT: f64 = 4.5;
pub const WCAG_AA_UI: f64 = 3.0;
fn css_hex_channels(value: &str) -> Option<(f64, f64, f64)> {
let t = value.trim();
let rest = t.strip_prefix('#')?;
if rest.len() != 3 && rest.len() != 6 {
return None;
}
if !rest.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let full: String = if rest.len() == 3 {
rest.chars().flat_map(|c| [c, c]).collect()
} else {
rest.to_owned()
};
let channel = |i: usize| -> Option<f64> {
u8::from_str_radix(full.get(i..i + 2)?, 16)
.ok()
.map(f64::from)
};
Some((channel(0)?, channel(2)?, channel(4)?))
}
fn relative_luminance((r, g, b): (f64, f64, f64)) -> f64 {
let linear = |channel: f64| {
let c = channel / 255.0;
if c <= 0.03928 {
c / 12.92
} else {
((c + 0.055) / 1.055).powf(2.4)
}
};
0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b)
}
pub fn contrast_ratio(a: &str, b: &str) -> Option<f64> {
let first = relative_luminance(css_hex_channels(a)?);
let second = relative_luminance(css_hex_channels(b)?);
let (lighter, darker) = if first >= second {
(first, second)
} else {
(second, first)
};
Some((lighter + 0.05) / (darker + 0.05))
}
pub fn is_dark_surface(color: &str) -> bool {
let stripped = color.replacen('#', "", 1);
let m = stripped.trim();
if m.len() != 3 && m.len() != 6 {
return false;
}
let full: String = if m.len() == 3 {
m.chars().flat_map(|c| [c, c]).collect()
} else {
m.to_string()
};
let bytes = full.as_bytes();
if !bytes.iter().all(u8::is_ascii_hexdigit) {
return false;
}
let pair = |i: usize| -> u32 { u32::from_str_radix(&full[i..i + 2], 16).unwrap_or(0) };
let (r, g, b) = (pair(0), pair(2), pair(4));
let luma = (r * 299 + g * 587 + b * 114) / 1000;
luma < 128
}
pub static DEFAULT_BADGES: LazyLock<Vec<TrustBadge>> = LazyLock::new(|| {
vec![
TrustBadge::new("secure", "Secure", "#047857", "#ecfdf5").border_color("#a7f3d0"),
TrustBadge::new("ssl", "256-bit SSL", "#1E4FEB", "#eff6ff").border_color("#bfdbfe"),
]
});
pub static DEFAULT_BADGES_DARK: LazyLock<Vec<TrustBadge>> = LazyLock::new(|| {
vec![
TrustBadge::new("secure", "Secure", "#34d399", "#064e3b").border_color("#065f46"),
TrustBadge::new("ssl", "256-bit SSL", "#60a5fa", "#172554").border_color("#1e40af"),
]
});
fn default_branding_base() -> CheckoutBranding {
CheckoutBranding {
display_name: String::new(),
logo_url: String::new(),
tagline: String::new(),
show_logo: false,
logo_shape: LogoShape::Rounded,
logo_size: LogoSize::Md,
primary: String::new(),
background: String::new(),
surface: String::new(),
text: String::new(),
heading: String::new(),
muted: String::new(),
border: String::new(),
accent_text: String::new(),
button_background: String::new(),
button_text: String::new(),
font_family: FontFamily::Inter,
heading_weight: FontWeight::Semibold,
radius_surface: NonPillRadius::Medium,
radius_input: NonPillRadius::Medium,
radius_button: CornerRadius::Medium,
radius_badge: CornerRadius::Pill,
surface_style: SurfaceStyle::Elevated,
surface_padding: SpacingScale::Comfortable,
vertical_gap: SpacingScale::Comfortable,
input_size: SizeScale::Md,
button_size: SizeScale::Md,
layout: LayoutStyle::Split,
summary_position: SummaryPosition::Left,
show_order_summary: true,
summary_gradient: false,
show_total: true,
total_label: "Total".to_string(),
show_currency_code: false,
show_order_items: true,
cancel_link_enabled: true,
cancel_link_position: CancelLinkPosition::Top,
cancel_link_style: CancelLinkStyle::Link,
show_surcharge: true,
surcharge_position: SurchargePosition::Trailing,
native_element_position: NativeElementPosition::Top,
native_element_stacked: false,
surcharge_style: SurchargeStyle::Badge,
surcharge_size: SurchargeSize::Sm,
surcharge_shape: SurchargeShape::Pill,
surcharge_border_width: SurchargeBorderWidth::Thin,
surcharge_border_style: SurchargeBorderStyle::Solid,
surcharge_weight: SurchargeWeight::Medium,
surcharge_sign: SurchargeSign::Always,
surcharge_uppercase: false,
surcharge_label: SurchargeLabelMode::Labelled,
surcharge_figure: SurchargeFigureMode::Amount,
discount_figure: SurchargeFigureMode::PercentThenAmount,
surcharge_color: String::new(),
discount_color: String::new(),
method_section_order: default_method_section_order(),
method_section_labels: MethodSectionLabels::new(),
airwallex_card_preset: None,
airwallex_hide_card: false,
airwallex_hide_card_title: false,
airwallex_field_chrome: AirwallexFieldChrome::Outlined,
airwallex_label_style: None,
airwallex_field_font_size: AirwallexFieldFontSize::Md,
airwallex_field_weight: AirwallexFieldWeight::Medium,
airwallex_focus_ring: AirwallexFocusRing::None,
airwallex_autofill: AirwallexAutofillTreatment::System,
airwallex_valid_tint: false,
airwallex_network_marks: false,
stripe_theme: StripeTheme::Auto,
stripe_inputs: StripeInputStyle::Spaced,
stripe_labels: StripeLabelPlacement::Above,
stripe_spacing: StripeSpacing::Comfortable,
stripe_field_font_size: CardFieldFontSize::Md,
stripe_field_weight: CardFieldWeight::Medium,
stripe_focus_ring: CardFocusRing::Strong,
stripe_disable_animations: false,
paypal_card_layout: PaypalCardLayout::Split,
paypal_label_style: PaypalLabelStyle::Above,
paypal_field_chrome: CardFieldChrome::Outlined,
mollie_field_chrome: CardFieldChrome::Outlined,
paypal_field_font_size: CardFieldFontSize::Md,
mollie_field_font_size: CardFieldFontSize::Md,
paypal_field_weight: CardFieldWeight::Regular,
mollie_field_weight: CardFieldWeight::Regular,
paypal_focus_ring: CardFocusRing::Strong,
mollie_focus_ring: CardFocusRing::Strong,
paypal_valid_tint: false,
epayouts_card_layout: PaypalCardLayout::Split,
epayouts_label_style: PaypalLabelStyle::Above,
epayouts_field_chrome: CardFieldChrome::Outlined,
epayouts_field_font_size: CardFieldFontSize::Md,
epayouts_field_weight: CardFieldWeight::Regular,
epayouts_focus_ring: CardFocusRing::Strong,
epayouts_valid_tint: false,
nomupay_form_style: NomupayFormStyle::Plain,
nomupay_show_labels: true,
nomupay_show_placeholders: true,
nomupay_show_cvv_hint: false,
nomupay_field_chrome: CardFieldChrome::Outlined,
nomupay_field_font_size: CardFieldFontSize::Md,
nomupay_focus_ring: CardFocusRing::None,
nomupay_apple_pay_button_style: ApplePayButtonStyle::Auto,
nomupay_apple_pay_button_type: ApplePayButtonType::Pay,
nomupay_google_pay_button_color: GooglePayButtonColor::Auto,
nomupay_google_pay_button_type: GooglePayButtonType::Pay,
micropayment_field_chrome: CardFieldChrome::Outlined,
micropayment_field_font_size: CardFieldFontSize::Md,
micropayment_field_weight: CardFieldWeight::Regular,
micropayment_focus_ring: CardFocusRing::Strong,
whop_card_preset: WhopCardPreset::CardStacked,
whop_accent_color: WhopAccentColor::Auto,
whop_gray_color: WhopGrayColor::Auto,
whop_billing_details: WhopBillingDetails::Minimal,
whop_separated: false,
whop_email_label: WhopEmailLabel::Above,
whop_field_chrome: CardFieldChrome::Outlined,
whop_field_font_size: CardFieldFontSize::Md,
whop_field_weight: CardFieldWeight::Regular,
whop_focus_ring: CardFocusRing::Strong,
whop_radius: WhopRadius::Checkout,
whop_shadow: WhopShadow::Soft,
whop_method_icons: true,
whop_selection: WhopSelection::RadioTint,
trust_badges: Vec::new(),
notices: Vec::new(),
custom_fields: Vec::new(),
header_text: String::new(),
pay_button_label: String::new(),
card_terms_message: String::new(),
footer_text: String::new(),
support_email: String::new(),
payment_layout: PaymentLayout::Tabs,
label_style: LabelStyle::Above,
show_powered_by: true,
custom_css: String::new(),
}
}
pub static DEFAULT_BRANDING: LazyLock<CheckoutBranding> = LazyLock::new(|| CheckoutBranding {
primary: "#1E4FEB".to_string(),
background: "#f8fafc".to_string(),
surface: "#ffffff".to_string(),
text: "#1e293b".to_string(),
heading: "#0A1130".to_string(),
muted: "#64748b".to_string(),
border: "#e2e8f0".to_string(),
accent_text: "#1E4FEB".to_string(),
button_background: "#0A1130".to_string(),
button_text: "#ffffff".to_string(),
surcharge_color: "#b45309".to_string(),
discount_color: "#047857".to_string(),
trust_badges: Vec::new(),
notices: default_notices(),
..default_branding_base()
});
pub static DEFAULT_BRANDING_DARK: LazyLock<CheckoutBranding> = LazyLock::new(|| CheckoutBranding {
primary: "#1E4FEB".to_string(),
background: "#020617".to_string(),
surface: "#0f172a".to_string(),
text: "#e2e8f0".to_string(),
heading: "#f8fafc".to_string(),
muted: "#94a3b8".to_string(),
border: "#1e293b".to_string(),
accent_text: "#60a5fa".to_string(),
button_background: "#1E4FEB".to_string(),
button_text: "#ffffff".to_string(),
surface_style: SurfaceStyle::Flat,
surcharge_color: "#fbbf24".to_string(),
discount_color: "#34d399".to_string(),
trust_badges: Vec::new(),
notices: default_notices(),
..default_branding_base()
});
pub fn default_branding() -> CheckoutBranding {
clone_branding(&DEFAULT_BRANDING)
}
pub fn clone_branding(b: &CheckoutBranding) -> CheckoutBranding {
b.clone()
}
pub type MethodSectionOrder = BTreeMap<String, i64>;
pub type MethodSectionLabels = BTreeMap<String, BTreeMap<String, String>>;
pub const MIN_SECTION_ORDER: i64 = 1;
pub const MAX_SECTION_ORDER: i64 = 100;
pub const MAX_SECTION_LABEL_LENGTH: usize = 120;
pub const UNKNOWN_SECTION_ORDER: i64 = MAX_SECTION_ORDER;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MethodSectionSpec {
pub id: &'static str,
pub label_key: &'static str,
pub order: i64,
}
pub const METHOD_SECTIONS: &[MethodSectionSpec] = &[
MethodSectionSpec {
id: "card",
label_key: "sections.card",
order: 10,
},
MethodSectionSpec {
id: "wallet",
label_key: "sections.wallets",
order: 20,
},
MethodSectionSpec {
id: "bnpl",
label_key: "sections.bnpl",
order: 30,
},
MethodSectionSpec {
id: "bank_redirect",
label_key: "sections.onlineBanking",
order: 40,
},
MethodSectionSpec {
id: "bank_transfer",
label_key: "sections.bankTransfer",
order: 45,
},
MethodSectionSpec {
id: "crypto",
label_key: "sections.cryptocurrency",
order: 50,
},
MethodSectionSpec {
id: "game_items",
label_key: "sections.gameItems",
order: 60,
},
MethodSectionSpec {
id: "voucher",
label_key: "sections.vouchers",
order: 70,
},
MethodSectionSpec {
id: "gift_card",
label_key: "sections.giftCards",
order: 75,
},
MethodSectionSpec {
id: "reward",
label_key: "sections.rewards",
order: 80,
},
MethodSectionSpec {
id: "cash",
label_key: "sections.cash",
order: 90,
},
];
pub const SECTION_ALIASES: &[(&str, &str)] = &[("card_redirect", "card")];
pub fn canonical_section_id(id: &str) -> String {
for (alias, canonical) in SECTION_ALIASES {
if *alias == id {
return (*canonical).to_string();
}
}
id.to_string()
}
pub fn default_method_section_order() -> MethodSectionOrder {
METHOD_SECTIONS
.iter()
.map(|spec| (spec.id.to_string(), spec.order))
.collect()
}
fn section_position(id: &str) -> usize {
METHOD_SECTIONS
.iter()
.position(|spec| spec.id == id)
.unwrap_or(METHOD_SECTIONS.len())
}
pub fn compare_sections(a: &str, b: &str, order: &MethodSectionOrder) -> std::cmp::Ordering {
let a_id = canonical_section_id(a);
let b_id = canonical_section_id(b);
let a_order = order.get(&a_id).copied().unwrap_or(UNKNOWN_SECTION_ORDER);
let b_order = order.get(&b_id).copied().unwrap_or(UNKNOWN_SECTION_ORDER);
a_order
.cmp(&b_order)
.then_with(|| section_position(&a_id).cmp(§ion_position(&b_id)))
.then_with(|| a_id.cmp(&b_id))
}
pub fn section_label(
id: &str,
locale: &str,
labels: &MethodSectionLabels,
fallback: Option<&str>,
) -> String {
let section = canonical_section_id(id);
if let Some(by_locale) = labels.get(§ion) {
let wanted = locale.to_ascii_lowercase();
let mut candidate: &str = &wanted;
loop {
for (key, value) in by_locale {
if key.to_ascii_lowercase() == candidate && !value.trim().is_empty() {
return value.clone();
}
}
match candidate.rfind('-') {
Some(cut) => candidate = &candidate[..cut],
None => break,
}
}
if let Some(value) = by_locale.values().find(|v| !v.trim().is_empty()) {
return value.clone();
}
}
match fallback {
Some(name) if !name.trim().is_empty() => name.to_string(),
_ => section,
}
}
pub fn decode_method_section_order(raw: Option<&str>) -> MethodSectionOrder {
let mut order = default_method_section_order();
let Some(raw) = raw else { return order };
let Ok(Value::Object(parsed)) = serde_json::from_str::<Value>(raw) else {
return order;
};
for (key, value) in parsed {
let Some(number) = value.as_i64() else {
continue;
};
if !(MIN_SECTION_ORDER..=MAX_SECTION_ORDER).contains(&number) {
continue;
}
order.insert(canonical_section_id(&key), number);
}
order
}
pub fn encode_method_section_order(order: &MethodSectionOrder) -> String {
serde_json::to_string(order).unwrap_or_else(|_| "{}".to_string())
}
pub fn decode_method_section_labels(raw: Option<&str>) -> MethodSectionLabels {
let mut labels = MethodSectionLabels::new();
let Some(raw) = raw else { return labels };
let Ok(Value::Object(parsed)) = serde_json::from_str::<Value>(raw) else {
return labels;
};
for (section, by_locale) in parsed {
let Some(by_locale) = by_locale.as_object() else {
continue;
};
if section.trim().is_empty() {
continue;
}
let mut entries: BTreeMap<String, String> = BTreeMap::new();
for (locale, caption) in by_locale {
let Some(caption) = caption.as_str() else {
continue;
};
let caption = caption.trim();
if locale.trim().is_empty() || caption.is_empty() {
continue;
}
entries.insert(locale.clone(), truncate_section_label(caption));
}
if !entries.is_empty() {
labels.insert(canonical_section_id(§ion), entries);
}
}
labels
}
pub fn encode_method_section_labels(labels: &MethodSectionLabels) -> String {
let mut cleaned = MethodSectionLabels::new();
for (section, by_locale) in labels {
let mut kept: BTreeMap<String, String> = BTreeMap::new();
for (locale, caption) in by_locale {
let caption = caption.trim();
if locale.trim().is_empty() || caption.is_empty() {
continue;
}
kept.insert(locale.clone(), truncate_section_label(caption));
}
if !kept.is_empty() {
cleaned.insert(canonical_section_id(section), kept);
}
}
serde_json::to_string(&cleaned).unwrap_or_else(|_| "{}".to_string())
}
fn truncate_section_label(caption: &str) -> String {
if utf16_len(caption) <= MAX_SECTION_LABEL_LENGTH {
return caption.to_string();
}
let mut out = String::new();
let mut units = 0;
for c in caption.chars() {
let w = c.len_utf16();
if units + w > MAX_SECTION_LABEL_LENGTH {
break;
}
out.push(c);
units += w;
}
out
}
pub const fn surcharge_font_size(size: SurchargeSize) -> &'static str {
match size {
SurchargeSize::Sm => "0.6875rem",
SurchargeSize::Md => "0.8125rem",
SurchargeSize::Lg => "0.9375rem",
}
}
pub const fn surcharge_pad(size: SurchargeSize) -> &'static str {
match size {
SurchargeSize::Sm => "1px 6px",
SurchargeSize::Md => "2px 8px",
SurchargeSize::Lg => "3px 10px",
}
}
pub const fn surcharge_radius(shape: SurchargeShape) -> &'static str {
match shape {
SurchargeShape::Pill => "999px",
SurchargeShape::Rounded => "6px",
SurchargeShape::Square => "0px",
}
}
pub const fn surcharge_border_width_value(width: SurchargeBorderWidth) -> &'static str {
match width {
SurchargeBorderWidth::None => "0px",
SurchargeBorderWidth::Thin => "1px",
SurchargeBorderWidth::Medium => "2px",
SurchargeBorderWidth::Thick => "3px",
}
}
pub const fn surcharge_font_weight(weight: SurchargeWeight) -> &'static str {
match weight {
SurchargeWeight::Regular => "400",
SurchargeWeight::Medium => "600",
SurchargeWeight::Bold => "700",
}
}
pub const fn surcharge_style_draws_a_shape(style: SurchargeStyle) -> bool {
matches!(
style,
SurchargeStyle::Badge
| SurchargeStyle::Outline
| SurchargeStyle::Solid
| SurchargeStyle::Ribbon
)
}
pub fn readable_ink_on(color: &str) -> &'static str {
let on_black = contrast_ratio(color, "#000000");
let on_white = contrast_ratio(color, "#ffffff");
match (on_black, on_white) {
(Some(black), Some(white)) if black >= white => "#000000",
(Some(_), Some(_)) => "#ffffff",
_ => "#ffffff",
}
}
pub fn resolve_airwallex_card_preset(
from_branding: Option<&str>,
from_connector: Option<&str>,
) -> AirwallexCardPreset {
let parse = |value: Option<&str>| -> Option<AirwallexCardPreset> {
let raw = value?.trim().to_ascii_lowercase();
AirwallexCardPreset::from_wire(&raw)
};
parse(from_branding)
.or_else(|| parse(from_connector))
.unwrap_or(AIRWALLEX_CARD_PRESET_FALLBACK)
}
pub const AIRWALLEX_CARD_PRESET_FALLBACK: AirwallexCardPreset =
AirwallexCardPreset::SplitFieldsLabelled;
pub const CUSTOM_CSS_MAX_LENGTH: usize = 50_000;
pub fn sanitize_custom_css(raw: Option<&str>) -> Option<String> {
let raw = raw?;
let trimmed = raw.trim();
if trimmed.is_empty() {
return None;
}
if utf16_len(trimmed) > CUSTOM_CSS_MAX_LENGTH {
return None;
}
let mut out = trimmed.to_string();
out = escape_style_close(&out);
out = strip_imports(&out);
out = comment_out(&out, "expression", Some('('), "/* expression( */", false);
out = comment_out(&out, "behavior", Some(':'), "/* behavior: */", true);
out = comment_out(
&out,
"-moz-binding",
Some(':'),
"/* -moz-binding: */",
false,
);
out = neutralize_javascript_urls(&out);
Some(out)
}
fn utf16_len(s: &str) -> usize {
s.encode_utf16().count()
}
fn find_ci(hay: &str, needle: &str, from: usize) -> Option<usize> {
let hb = hay.as_bytes();
let nb = needle.as_bytes();
if nb.is_empty() || hb.len() < nb.len() {
return None;
}
(from..=hb.len() - nb.len()).find(|&i| {
hb[i..i + nb.len()]
.iter()
.zip(nb)
.all(|(a, b)| a.to_ascii_lowercase() == *b)
})
}
fn skip_ws(s: &str, mut i: usize) -> usize {
while let Some(c) = s[i..].chars().next() {
if c.is_whitespace() || c == '\u{feff}' {
i += c.len_utf8();
} else {
break;
}
}
i
}
fn escape_style_close(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, "</style", i) {
out.push_str(&s[i..idx]);
out.push_str("<\\/style");
i = idx + "</style".len();
}
out.push_str(&s[i..]);
out
}
fn is_word_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn strip_imports(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, "@import", i) {
let after = idx + "@import".len();
if s.as_bytes().get(after).copied().is_some_and(is_word_byte) {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
out.push_str(&s[i..idx]);
i = match s[after..].find(';') {
Some(rel) => after + rel + 1,
None => s.len(),
};
}
out.push_str(&s[i..]);
out
}
fn comment_out(
s: &str,
token: &str,
terminator: Option<char>,
replacement: &str,
guard_prefix: bool,
) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, token, i) {
if guard_prefix
&& idx > 0
&& s[..idx]
.chars()
.next_back()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '-')
{
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
let after = skip_ws(s, idx + token.len());
let end = match terminator {
Some(t) if s[after..].starts_with(t) => after + t.len_utf8(),
Some(_) => {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
None => after,
};
out.push_str(&s[i..idx]);
out.push_str(replacement);
i = end;
}
out.push_str(&s[i..]);
out
}
fn neutralize_javascript_urls(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, "url", i) {
let mut p = skip_ws(s, idx + 3);
if !s[p..].starts_with('(') {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
p = skip_ws(s, p + 1);
if s[p..].starts_with('"') || s[p..].starts_with('\'') {
p += 1;
}
p = skip_ws(s, p);
if find_ci(s, "javascript:", p) != Some(p) {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
out.push_str(&s[i..idx]);
out.push_str("url(invalid:");
i = p + "javascript:".len();
}
out.push_str(&s[i..]);
out
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrandingSource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub merchant_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seller_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub merchant_logo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub logo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub merchant_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub theme: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub background_colour: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_button_colour: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_button_text_colour: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_form_header_text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_button_text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub custom_message_for_card_terms: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branding_visibility: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sdk_layout: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_form_label_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sdk_ui_rules: Option<Map<String, Value>>,
}
const BRANDING_GROUP_KEY: &str = "branding";
fn s(v: &Option<String>) -> &str {
v.as_deref().unwrap_or("")
}
fn or_else(value: &str, fallback: &str) -> String {
if value.is_empty() {
fallback.to_string()
} else {
value.to_string()
}
}
fn pick_enum<T: WireEnum>(value: Option<&Value>, fallback: T) -> T {
match value.and_then(Value::as_str) {
Some(raw) => T::parse_wire(raw).unwrap_or(fallback),
None => fallback,
}
}
fn pick_optional_enum<T: WireEnum>(value: Option<&Value>) -> Option<T> {
let raw = value?.as_str()?.trim();
if raw.is_empty() {
return None;
}
T::parse_wire(raw)
}
fn parse_bool(value: Option<&Value>, fallback: bool) -> bool {
match value {
Some(Value::Bool(b)) => *b,
Some(Value::String(raw)) if raw == "true" => true,
Some(Value::String(raw)) if raw == "false" => false,
_ => fallback,
}
}
fn bag_str<'a>(bag: &'a Map<String, Value>, key: &str) -> &'a str {
bag.get(key).and_then(Value::as_str).unwrap_or("")
}
pub fn decode_badges(raw: Option<&str>) -> Option<Vec<TrustBadge>> {
let raw = raw?;
let parsed: Value = serde_json::from_str(raw).ok()?;
let items = parsed.as_array()?;
Some(
items
.iter()
.enumerate()
.filter_map(|(i, item)| {
let obj = item.as_object()?;
let str_field = |k: &str| obj.get(k).and_then(Value::as_str);
Some(TrustBadge {
id: match str_field("id") {
Some(id) if !id.is_empty() => id.to_string(),
_ => format!("badge-{i}"),
},
label: str_field("label").unwrap_or("").to_string(),
text_color: str_field("textColor").unwrap_or("#0f172a").to_string(),
background_color: str_field("backgroundColor")
.unwrap_or("#f1f5f9")
.to_string(),
border_color: str_field("borderColor")
.filter(|v| !v.is_empty())
.map(str::to_string),
})
})
.filter(|b| !b.label.is_empty())
.collect(),
)
}
#[derive(Serialize)]
struct BadgeWire<'a> {
id: &'a str,
label: &'a str,
#[serde(rename = "textColor")]
text_color: &'a str,
#[serde(rename = "backgroundColor")]
background_color: &'a str,
#[serde(rename = "borderColor", skip_serializing_if = "Option::is_none")]
border_color: Option<&'a str>,
}
pub fn encode_badges(badges: &[TrustBadge]) -> String {
let wire: Vec<BadgeWire<'_>> = badges
.iter()
.map(|b| BadgeWire {
id: &b.id,
label: &b.label,
text_color: &b.text_color,
background_color: &b.background_color,
border_color: b.border_color.as_deref().filter(|v| !v.is_empty()),
})
.collect();
serde_json::to_string(&wire).unwrap_or_else(|_| "[]".to_string())
}
pub fn decode_branding(source: Option<&BrandingSource>) -> CheckoutBranding {
let Some(source) = source else {
return clone_branding(&DEFAULT_BRANDING);
};
let dflt = &*DEFAULT_BRANDING;
let empty = Map::new();
let extras: &Map<String, Value> = source
.sdk_ui_rules
.as_ref()
.and_then(|rules| rules.get(BRANDING_GROUP_KEY))
.and_then(Value::as_object)
.unwrap_or(&empty);
let trust_row = resolve_notices_and_badges(
decode_badges(extras.get("trustBadges").and_then(Value::as_str)),
decode_notices(extras.get("notices").and_then(Value::as_str)),
);
let decoded_custom_fields =
decode_custom_fields(extras.get("customFields").and_then(Value::as_str));
let display_name = or_else(s(&source.merchant_name), s(&source.seller_name));
let logo_url = or_else(s(&source.merchant_logo), s(&source.logo));
let tagline = or_else(bag_str(extras, "tagline"), s(&source.merchant_description));
let label_style = {
let from_bag = bag_str(extras, "labelStyle");
match from_bag {
"above" | "floating" => LabelStyle::Above,
"hidden" => LabelStyle::Hidden,
_ => match s(&source.payment_form_label_type) {
"above" | "floating" => LabelStyle::Above,
"hidden" | "never" => LabelStyle::Hidden,
_ => dflt.label_style,
},
}
};
CheckoutBranding {
display_name,
logo_url,
tagline,
show_logo: parse_bool(extras.get("showLogo"), dflt.show_logo),
logo_shape: pick_enum(extras.get("logoShape"), dflt.logo_shape),
logo_size: pick_enum(extras.get("logoSize"), dflt.logo_size),
primary: or_else(s(&source.theme), &dflt.primary),
background: or_else(s(&source.background_colour), &dflt.background),
surface: or_else(bag_str(extras, "surface"), &dflt.surface),
text: or_else(bag_str(extras, "text"), &dflt.text),
heading: or_else(
bag_str(extras, "heading"),
&or_else(bag_str(extras, "text"), &dflt.heading),
),
muted: or_else(bag_str(extras, "muted"), &dflt.muted),
border: or_else(bag_str(extras, "border"), &dflt.border),
accent_text: or_else(
bag_str(extras, "accentText"),
&or_else(s(&source.theme), &dflt.accent_text),
),
button_background: or_else(
s(&source.payment_button_colour),
&or_else(s(&source.theme), &dflt.button_background),
),
button_text: or_else(s(&source.payment_button_text_colour), &dflt.button_text),
font_family: pick_enum(extras.get("fontFamily"), dflt.font_family),
heading_weight: pick_enum(extras.get("headingWeight"), dflt.heading_weight),
radius_surface: pick_enum(extras.get("radiusSurface"), dflt.radius_surface),
radius_input: pick_enum(extras.get("radiusInput"), dflt.radius_input),
radius_button: pick_enum(extras.get("radiusButton"), dflt.radius_button),
radius_badge: pick_enum(extras.get("radiusBadge"), dflt.radius_badge),
surface_style: pick_enum(extras.get("surfaceStyle"), dflt.surface_style),
surface_padding: pick_enum(extras.get("surfacePadding"), dflt.surface_padding),
vertical_gap: pick_enum(extras.get("verticalGap"), dflt.vertical_gap),
input_size: pick_enum(extras.get("inputSize"), dflt.input_size),
button_size: pick_enum(extras.get("buttonSize"), dflt.button_size),
layout: pick_enum(extras.get("layout"), dflt.layout),
summary_position: pick_enum(extras.get("summaryPosition"), dflt.summary_position),
show_order_summary: parse_bool(extras.get("showOrderSummary"), dflt.show_order_summary),
summary_gradient: parse_bool(extras.get("summaryGradient"), dflt.summary_gradient),
show_total: parse_bool(extras.get("showTotal"), dflt.show_total),
total_label: or_else(bag_str(extras, "totalLabel"), &dflt.total_label),
show_currency_code: parse_bool(extras.get("showCurrencyCode"), dflt.show_currency_code),
show_order_items: parse_bool(extras.get("showOrderItems"), dflt.show_order_items),
cancel_link_enabled: parse_bool(extras.get("cancelLinkEnabled"), dflt.cancel_link_enabled),
cancel_link_position: pick_enum(
extras.get("cancelLinkPosition"),
dflt.cancel_link_position,
),
cancel_link_style: pick_enum(extras.get("cancelLinkStyle"), dflt.cancel_link_style),
show_surcharge: parse_bool(extras.get("showSurcharge"), dflt.show_surcharge),
surcharge_position: pick_enum(extras.get("surchargePosition"), dflt.surcharge_position),
native_element_position: pick_enum(
extras.get("nativeElementPosition"),
dflt.native_element_position,
),
native_element_stacked: parse_bool(
extras.get("nativeElementStacked"),
dflt.native_element_stacked,
),
surcharge_style: pick_enum(extras.get("surchargeStyle"), dflt.surcharge_style),
surcharge_size: pick_enum(extras.get("surchargeSize"), dflt.surcharge_size),
surcharge_shape: pick_enum(extras.get("surchargeShape"), dflt.surcharge_shape),
surcharge_border_width: pick_enum(
extras.get("surchargeBorderWidth"),
dflt.surcharge_border_width,
),
surcharge_border_style: pick_enum(
extras.get("surchargeBorderStyle"),
dflt.surcharge_border_style,
),
surcharge_weight: pick_enum(extras.get("surchargeWeight"), dflt.surcharge_weight),
surcharge_sign: pick_enum(extras.get("surchargeSign"), dflt.surcharge_sign),
surcharge_uppercase: parse_bool(extras.get("surchargeUppercase"), dflt.surcharge_uppercase),
surcharge_label: pick_enum(extras.get("surchargeLabel"), dflt.surcharge_label),
surcharge_figure: pick_enum(extras.get("surchargeFigure"), dflt.surcharge_figure),
discount_figure: pick_enum(extras.get("discountFigure"), dflt.discount_figure),
surcharge_color: or_else(bag_str(extras, "surchargeColor"), &dflt.surcharge_color),
discount_color: or_else(bag_str(extras, "discountColor"), &dflt.discount_color),
method_section_order: decode_method_section_order(
extras.get("methodSectionOrder").and_then(Value::as_str),
),
method_section_labels: decode_method_section_labels(
extras.get("methodSectionLabels").and_then(Value::as_str),
),
trust_badges: trust_row.trust_badges,
notices: trust_row.notices,
custom_fields: decoded_custom_fields.unwrap_or_default(),
header_text: s(&source.payment_form_header_text).to_string(),
pay_button_label: s(&source.payment_button_text).to_string(),
card_terms_message: s(&source.custom_message_for_card_terms).to_string(),
footer_text: bag_str(extras, "footerText").to_string(),
support_email: bag_str(extras, "supportEmail").to_string(),
payment_layout: PaymentLayout::from_wire(s(&source.sdk_layout))
.unwrap_or(dflt.payment_layout),
label_style,
airwallex_card_preset: pick_optional_enum(extras.get("airwallexCardPreset")),
airwallex_hide_card: parse_bool(extras.get("airwallexHideCard"), dflt.airwallex_hide_card),
airwallex_hide_card_title: parse_bool(
extras.get("airwallexHideCardTitle"),
dflt.airwallex_hide_card_title,
),
airwallex_field_chrome: pick_enum(
extras.get("airwallexFieldChrome"),
dflt.airwallex_field_chrome,
),
airwallex_label_style: pick_optional_enum(extras.get("airwallexLabelStyle")),
airwallex_field_font_size: pick_enum(
extras.get("airwallexFieldFontSize"),
dflt.airwallex_field_font_size,
),
airwallex_field_weight: pick_enum(
extras.get("airwallexFieldWeight"),
dflt.airwallex_field_weight,
),
airwallex_focus_ring: pick_enum(
extras.get("airwallexFocusRing"),
dflt.airwallex_focus_ring,
),
airwallex_autofill: pick_enum(extras.get("airwallexAutofill"), dflt.airwallex_autofill),
airwallex_valid_tint: parse_bool(
extras.get("airwallexValidTint"),
dflt.airwallex_valid_tint,
),
airwallex_network_marks: parse_bool(
extras.get("airwallexNetworkMarks"),
dflt.airwallex_network_marks,
),
stripe_theme: pick_enum(extras.get("stripeTheme"), dflt.stripe_theme),
stripe_inputs: pick_enum(extras.get("stripeInputs"), dflt.stripe_inputs),
stripe_labels: pick_enum(extras.get("stripeLabels"), dflt.stripe_labels),
stripe_spacing: pick_enum(extras.get("stripeSpacing"), dflt.stripe_spacing),
stripe_field_font_size: pick_enum(
extras.get("stripeFieldFontSize"),
dflt.stripe_field_font_size,
),
stripe_field_weight: pick_enum(extras.get("stripeFieldWeight"), dflt.stripe_field_weight),
stripe_focus_ring: pick_enum(extras.get("stripeFocusRing"), dflt.stripe_focus_ring),
stripe_disable_animations: parse_bool(
extras.get("stripeDisableAnimations"),
dflt.stripe_disable_animations,
),
paypal_card_layout: pick_enum(extras.get("paypalCardLayout"), dflt.paypal_card_layout),
paypal_label_style: pick_enum(extras.get("paypalLabelStyle"), dflt.paypal_label_style),
paypal_field_chrome: pick_enum(extras.get("paypalFieldChrome"), dflt.paypal_field_chrome),
mollie_field_chrome: pick_enum(extras.get("mollieFieldChrome"), dflt.mollie_field_chrome),
paypal_field_font_size: pick_enum(
extras.get("paypalFieldFontSize"),
dflt.paypal_field_font_size,
),
mollie_field_font_size: pick_enum(
extras.get("mollieFieldFontSize"),
dflt.mollie_field_font_size,
),
paypal_field_weight: pick_enum(extras.get("paypalFieldWeight"), dflt.paypal_field_weight),
mollie_field_weight: pick_enum(extras.get("mollieFieldWeight"), dflt.mollie_field_weight),
paypal_focus_ring: pick_enum(extras.get("paypalFocusRing"), dflt.paypal_focus_ring),
mollie_focus_ring: pick_enum(extras.get("mollieFocusRing"), dflt.mollie_focus_ring),
paypal_valid_tint: parse_bool(extras.get("paypalValidTint"), dflt.paypal_valid_tint),
epayouts_card_layout: pick_enum(
extras.get("epayoutsCardLayout"),
pick_enum(extras.get("paypalCardLayout"), dflt.epayouts_card_layout),
),
epayouts_label_style: pick_enum(
extras.get("epayoutsLabelStyle"),
pick_enum(extras.get("paypalLabelStyle"), dflt.epayouts_label_style),
),
epayouts_field_chrome: pick_enum(
extras.get("epayoutsFieldChrome"),
pick_enum(extras.get("paypalFieldChrome"), dflt.epayouts_field_chrome),
),
epayouts_field_font_size: pick_enum(
extras.get("epayoutsFieldFontSize"),
pick_enum(
extras.get("paypalFieldFontSize"),
dflt.epayouts_field_font_size,
),
),
epayouts_field_weight: pick_enum(
extras.get("epayoutsFieldWeight"),
pick_enum(extras.get("paypalFieldWeight"), dflt.epayouts_field_weight),
),
epayouts_focus_ring: pick_enum(
extras.get("epayoutsFocusRing"),
pick_enum(extras.get("paypalFocusRing"), dflt.epayouts_focus_ring),
),
epayouts_valid_tint: parse_bool(
extras.get("epayoutsValidTint"),
parse_bool(extras.get("paypalValidTint"), dflt.epayouts_valid_tint),
),
nomupay_form_style: pick_enum(extras.get("nomupayFormStyle"), dflt.nomupay_form_style),
nomupay_show_labels: parse_bool(extras.get("nomupayShowLabels"), dflt.nomupay_show_labels),
nomupay_show_placeholders: parse_bool(
extras.get("nomupayShowPlaceholders"),
dflt.nomupay_show_placeholders,
),
nomupay_show_cvv_hint: parse_bool(
extras.get("nomupayShowCvvHint"),
dflt.nomupay_show_cvv_hint,
),
nomupay_field_chrome: pick_enum(
extras.get("nomupayFieldChrome"),
dflt.nomupay_field_chrome,
),
nomupay_field_font_size: pick_enum(
extras.get("nomupayFieldFontSize"),
dflt.nomupay_field_font_size,
),
nomupay_focus_ring: pick_enum(extras.get("nomupayFocusRing"), dflt.nomupay_focus_ring),
nomupay_apple_pay_button_style: pick_enum(
extras.get("nomupayApplePayButtonStyle"),
dflt.nomupay_apple_pay_button_style,
),
nomupay_apple_pay_button_type: pick_enum(
extras.get("nomupayApplePayButtonType"),
dflt.nomupay_apple_pay_button_type,
),
nomupay_google_pay_button_color: pick_enum(
extras.get("nomupayGooglePayButtonColor"),
dflt.nomupay_google_pay_button_color,
),
nomupay_google_pay_button_type: pick_enum(
extras.get("nomupayGooglePayButtonType"),
dflt.nomupay_google_pay_button_type,
),
micropayment_field_chrome: pick_enum(
extras.get("micropaymentFieldChrome"),
dflt.micropayment_field_chrome,
),
micropayment_field_font_size: pick_enum(
extras.get("micropaymentFieldFontSize"),
dflt.micropayment_field_font_size,
),
micropayment_field_weight: pick_enum(
extras.get("micropaymentFieldWeight"),
dflt.micropayment_field_weight,
),
micropayment_focus_ring: pick_enum(
extras.get("micropaymentFocusRing"),
dflt.micropayment_focus_ring,
),
whop_card_preset: pick_enum(extras.get("whopCardPreset"), dflt.whop_card_preset),
whop_accent_color: pick_enum(extras.get("whopAccentColor"), dflt.whop_accent_color),
whop_gray_color: pick_enum(extras.get("whopGrayColor"), dflt.whop_gray_color),
whop_billing_details: pick_enum(
extras.get("whopBillingDetails"),
dflt.whop_billing_details,
),
whop_separated: parse_bool(extras.get("whopSeparated"), dflt.whop_separated),
whop_email_label: pick_enum(extras.get("whopEmailLabel"), dflt.whop_email_label),
whop_field_chrome: pick_enum(extras.get("whopFieldChrome"), dflt.whop_field_chrome),
whop_field_font_size: pick_enum(extras.get("whopFieldFontSize"), dflt.whop_field_font_size),
whop_field_weight: pick_enum(extras.get("whopFieldWeight"), dflt.whop_field_weight),
whop_focus_ring: pick_enum(extras.get("whopFocusRing"), dflt.whop_focus_ring),
whop_radius: pick_enum(extras.get("whopRadius"), dflt.whop_radius),
whop_shadow: pick_enum(extras.get("whopShadow"), dflt.whop_shadow),
whop_method_icons: parse_bool(extras.get("whopMethodIcons"), dflt.whop_method_icons),
whop_selection: pick_enum(extras.get("whopSelection"), dflt.whop_selection),
show_powered_by: source.branding_visibility != Some(false),
custom_css: bag_str(extras, "customCss").to_string(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EncodedBranding {
pub theme: String,
pub logo: Option<String>,
pub seller_name: Option<String>,
pub sdk_layout: PaymentLayout,
pub payment_button_text: Option<String>,
pub payment_button_colour: String,
pub payment_button_text_colour: String,
pub background_colour: String,
pub payment_form_header_text: Option<String>,
pub payment_form_label_type: LegacyLabelType,
pub custom_message_for_card_terms: Option<String>,
pub sdk_ui_rules: BTreeMap<String, BTreeMap<String, String>>,
pub branding_visibility: bool,
}
fn trim_opt(v: &str) -> Option<String> {
let t = v.trim();
if t.is_empty() {
None
} else {
Some(t.to_string())
}
}
fn branding_extras(branding: &CheckoutBranding) -> BTreeMap<String, String> {
let mut extras = BTreeMap::new();
let mut put = |k: &str, v: String| {
extras.insert(k.to_string(), v);
};
put("surface", branding.surface.clone());
put("text", branding.text.clone());
put("heading", branding.heading.clone());
put("muted", branding.muted.clone());
put("border", branding.border.clone());
put("accentText", branding.accent_text.clone());
put("fontFamily", branding.font_family.as_str().to_string());
put(
"headingWeight",
branding.heading_weight.as_str().to_string(),
);
put(
"radiusSurface",
branding.radius_surface.as_str().to_string(),
);
put("radiusInput", branding.radius_input.as_str().to_string());
put("radiusButton", branding.radius_button.as_str().to_string());
put("radiusBadge", branding.radius_badge.as_str().to_string());
put("surfaceStyle", branding.surface_style.as_str().to_string());
put(
"surfacePadding",
branding.surface_padding.as_str().to_string(),
);
put("verticalGap", branding.vertical_gap.as_str().to_string());
put("inputSize", branding.input_size.as_str().to_string());
put("buttonSize", branding.button_size.as_str().to_string());
put("layout", branding.layout.as_str().to_string());
put(
"summaryPosition",
branding.summary_position.as_str().to_string(),
);
put("showOrderSummary", branding.show_order_summary.to_string());
put("summaryGradient", branding.summary_gradient.to_string());
put("showTotal", branding.show_total.to_string());
put("totalLabel", branding.total_label.clone());
put("showCurrencyCode", branding.show_currency_code.to_string());
put("showOrderItems", branding.show_order_items.to_string());
put(
"cancelLinkEnabled",
branding.cancel_link_enabled.to_string(),
);
put(
"cancelLinkPosition",
branding.cancel_link_position.as_str().to_string(),
);
put(
"cancelLinkStyle",
branding.cancel_link_style.as_str().to_string(),
);
put("showLogo", branding.show_logo.to_string());
put("logoShape", branding.logo_shape.as_str().to_string());
put("logoSize", branding.logo_size.as_str().to_string());
put("labelStyle", branding.label_style.as_str().to_string());
put("showSurcharge", branding.show_surcharge.to_string());
put(
"surchargePosition",
branding.surcharge_position.as_str().to_string(),
);
put(
"nativeElementPosition",
branding.native_element_position.as_str().to_string(),
);
put(
"nativeElementStacked",
branding.native_element_stacked.to_string(),
);
put(
"surchargeStyle",
branding.surcharge_style.as_str().to_string(),
);
put(
"surchargeSize",
branding.surcharge_size.as_str().to_string(),
);
put(
"surchargeShape",
branding.surcharge_shape.as_str().to_string(),
);
put(
"surchargeBorderWidth",
branding.surcharge_border_width.as_str().to_string(),
);
put(
"surchargeBorderStyle",
branding.surcharge_border_style.as_str().to_string(),
);
put(
"surchargeWeight",
branding.surcharge_weight.as_str().to_string(),
);
put(
"surchargeSign",
branding.surcharge_sign.as_str().to_string(),
);
put(
"surchargeUppercase",
branding.surcharge_uppercase.to_string(),
);
put(
"surchargeLabel",
branding.surcharge_label.as_str().to_string(),
);
put(
"surchargeFigure",
branding.surcharge_figure.as_str().to_string(),
);
put(
"discountFigure",
branding.discount_figure.as_str().to_string(),
);
put("surchargeColor", branding.surcharge_color.clone());
put("discountColor", branding.discount_color.clone());
put(
"methodSectionOrder",
encode_method_section_order(&branding.method_section_order),
);
let section_labels = encode_method_section_labels(&branding.method_section_labels);
if section_labels != "{}" {
put("methodSectionLabels", section_labels);
}
put(
"airwallexCardPreset",
branding
.airwallex_card_preset
.map(|p| p.as_str().to_string())
.unwrap_or_default(),
);
put(
"airwallexHideCard",
branding.airwallex_hide_card.to_string(),
);
put(
"airwallexHideCardTitle",
branding.airwallex_hide_card_title.to_string(),
);
put(
"airwallexFieldChrome",
branding.airwallex_field_chrome.as_str().to_string(),
);
put(
"airwallexLabelStyle",
branding
.airwallex_label_style
.map(|v| v.as_str().to_string())
.unwrap_or_default(),
);
put(
"airwallexFieldFontSize",
branding.airwallex_field_font_size.as_str().to_string(),
);
put(
"airwallexFieldWeight",
branding.airwallex_field_weight.as_str().to_string(),
);
put(
"airwallexFocusRing",
branding.airwallex_focus_ring.as_str().to_string(),
);
put(
"airwallexAutofill",
branding.airwallex_autofill.as_str().to_string(),
);
put(
"airwallexValidTint",
branding.airwallex_valid_tint.to_string(),
);
put(
"airwallexNetworkMarks",
branding.airwallex_network_marks.to_string(),
);
put("stripeTheme", branding.stripe_theme.as_str().to_string());
put("stripeInputs", branding.stripe_inputs.as_str().to_string());
put("stripeLabels", branding.stripe_labels.as_str().to_string());
put(
"stripeSpacing",
branding.stripe_spacing.as_str().to_string(),
);
put(
"stripeFieldFontSize",
branding.stripe_field_font_size.as_str().to_string(),
);
put(
"stripeFieldWeight",
branding.stripe_field_weight.as_str().to_string(),
);
put(
"stripeFocusRing",
branding.stripe_focus_ring.as_str().to_string(),
);
put(
"stripeDisableAnimations",
branding.stripe_disable_animations.to_string(),
);
put(
"paypalCardLayout",
branding.paypal_card_layout.as_str().to_string(),
);
put(
"paypalLabelStyle",
branding.paypal_label_style.as_str().to_string(),
);
put(
"paypalFieldChrome",
branding.paypal_field_chrome.as_str().to_string(),
);
put(
"mollieFieldChrome",
branding.mollie_field_chrome.as_str().to_string(),
);
put(
"paypalFieldFontSize",
branding.paypal_field_font_size.as_str().to_string(),
);
put(
"mollieFieldFontSize",
branding.mollie_field_font_size.as_str().to_string(),
);
put(
"paypalFieldWeight",
branding.paypal_field_weight.as_str().to_string(),
);
put(
"mollieFieldWeight",
branding.mollie_field_weight.as_str().to_string(),
);
put(
"paypalFocusRing",
branding.paypal_focus_ring.as_str().to_string(),
);
put(
"mollieFocusRing",
branding.mollie_focus_ring.as_str().to_string(),
);
put("paypalValidTint", branding.paypal_valid_tint.to_string());
put(
"epayoutsCardLayout",
branding.epayouts_card_layout.as_str().to_string(),
);
put(
"epayoutsLabelStyle",
branding.epayouts_label_style.as_str().to_string(),
);
put(
"epayoutsFieldChrome",
branding.epayouts_field_chrome.as_str().to_string(),
);
put(
"epayoutsFieldFontSize",
branding.epayouts_field_font_size.as_str().to_string(),
);
put(
"epayoutsFieldWeight",
branding.epayouts_field_weight.as_str().to_string(),
);
put(
"epayoutsFocusRing",
branding.epayouts_focus_ring.as_str().to_string(),
);
put(
"epayoutsValidTint",
branding.epayouts_valid_tint.to_string(),
);
put(
"nomupayFormStyle",
branding.nomupay_form_style.as_str().to_string(),
);
put(
"nomupayShowLabels",
branding.nomupay_show_labels.to_string(),
);
put(
"nomupayShowPlaceholders",
branding.nomupay_show_placeholders.to_string(),
);
put(
"nomupayShowCvvHint",
branding.nomupay_show_cvv_hint.to_string(),
);
put(
"nomupayFieldChrome",
branding.nomupay_field_chrome.as_str().to_string(),
);
put(
"nomupayFieldFontSize",
branding.nomupay_field_font_size.as_str().to_string(),
);
put(
"nomupayFocusRing",
branding.nomupay_focus_ring.as_str().to_string(),
);
put(
"nomupayApplePayButtonStyle",
branding.nomupay_apple_pay_button_style.as_str().to_string(),
);
put(
"nomupayApplePayButtonType",
branding.nomupay_apple_pay_button_type.as_str().to_string(),
);
put(
"nomupayGooglePayButtonColor",
branding
.nomupay_google_pay_button_color
.as_str()
.to_string(),
);
put(
"nomupayGooglePayButtonType",
branding.nomupay_google_pay_button_type.as_str().to_string(),
);
put(
"micropaymentFieldChrome",
branding.micropayment_field_chrome.as_str().to_string(),
);
put(
"micropaymentFieldFontSize",
branding.micropayment_field_font_size.as_str().to_string(),
);
put(
"micropaymentFieldWeight",
branding.micropayment_field_weight.as_str().to_string(),
);
put(
"micropaymentFocusRing",
branding.micropayment_focus_ring.as_str().to_string(),
);
put(
"whopCardPreset",
branding.whop_card_preset.as_str().to_string(),
);
put(
"whopAccentColor",
branding.whop_accent_color.as_str().to_string(),
);
put(
"whopGrayColor",
branding.whop_gray_color.as_str().to_string(),
);
put(
"whopBillingDetails",
branding.whop_billing_details.as_str().to_string(),
);
put("whopSeparated", branding.whop_separated.to_string());
put(
"whopEmailLabel",
branding.whop_email_label.as_str().to_string(),
);
put(
"whopFieldChrome",
branding.whop_field_chrome.as_str().to_string(),
);
put(
"whopFieldFontSize",
branding.whop_field_font_size.as_str().to_string(),
);
put(
"whopFieldWeight",
branding.whop_field_weight.as_str().to_string(),
);
put(
"whopFocusRing",
branding.whop_focus_ring.as_str().to_string(),
);
put("whopRadius", branding.whop_radius.as_str().to_string());
put("whopShadow", branding.whop_shadow.as_str().to_string());
put("whopMethodIcons", branding.whop_method_icons.to_string());
put(
"whopSelection",
branding.whop_selection.as_str().to_string(),
);
put("notices", encode_notices(&branding.notices));
if !branding.trust_badges.is_empty() {
put("trustBadges", encode_badges(&branding.trust_badges));
}
if !branding.custom_fields.is_empty() {
put(
"customFields",
encode_custom_fields(&branding.custom_fields),
);
}
if let Some(v) = trim_opt(&branding.tagline) {
put("tagline", v);
}
if let Some(v) = trim_opt(&branding.footer_text) {
put("footerText", v);
}
if let Some(v) = trim_opt(&branding.support_email) {
put("supportEmail", v);
}
if let Some(v) = trim_opt(&branding.custom_css) {
put("customCss", v);
}
extras
}
pub fn encode_branding(branding: &CheckoutBranding) -> EncodedBranding {
let mut rules = BTreeMap::new();
rules.insert(BRANDING_GROUP_KEY.to_string(), branding_extras(branding));
encoded_with_rules(branding, rules)
}
fn encoded_with_rules(
branding: &CheckoutBranding,
sdk_ui_rules: BTreeMap<String, BTreeMap<String, String>>,
) -> EncodedBranding {
EncodedBranding {
theme: branding.primary.clone(),
logo: trim_opt(&branding.logo_url),
seller_name: trim_opt(&branding.display_name),
sdk_layout: branding.payment_layout,
payment_button_text: trim_opt(&branding.pay_button_label),
payment_button_colour: branding.button_background.clone(),
payment_button_text_colour: branding.button_text.clone(),
background_colour: branding.background.clone(),
payment_form_header_text: trim_opt(&branding.header_text),
payment_form_label_type: match branding.label_style {
LabelStyle::Hidden => LegacyLabelType::Never,
LabelStyle::Above => LegacyLabelType::Above,
},
custom_message_for_card_terms: trim_opt(&branding.card_terms_message),
sdk_ui_rules,
branding_visibility: branding.show_powered_by,
}
}
pub fn encode_branding_with_base(branding: &CheckoutBranding, base: Option<&Value>) -> Value {
let base_obj = base.and_then(Value::as_object);
let mut rules: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
if let Some(existing) = base_obj
.and_then(|o| o.get("sdk_ui_rules"))
.and_then(Value::as_object)
{
for (group, value) in existing {
let Some(entries) = value.as_object() else {
continue;
};
let mut group_map = BTreeMap::new();
for (k, v) in entries {
if let Some(sv) = v.as_str() {
group_map.insert(k.clone(), sv.to_string());
}
}
rules.insert(group.clone(), group_map);
}
}
rules.insert(BRANDING_GROUP_KEY.to_string(), branding_extras(branding));
let flat = encoded_with_rules(branding, rules);
let mut out: Map<String, Value> = base_obj.cloned().unwrap_or_default();
if let Value::Object(flat_map) = serde_json::to_value(&flat).unwrap_or(Value::Null) {
for (k, v) in flat_map {
out.insert(k, v);
}
}
Value::Object(out)
}
pub const BRANDING_EXPORT_FORMAT: &str = "delopay-checkout-branding";
pub const BRANDING_EXPORT_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrandingExport {
pub format: String,
pub version: u32,
pub exported_at: String,
pub branding: CheckoutBranding,
}
pub fn build_branding_export(branding: &CheckoutBranding) -> BrandingExport {
let now = std::time::SystemTime::now();
let millis = match now.duration_since(std::time::UNIX_EPOCH) {
Ok(d) => d.as_millis() as i64,
Err(e) => -(e.duration().as_millis() as i64),
};
build_branding_export_at(branding, millis)
}
pub fn build_branding_export_at(branding: &CheckoutBranding, unix_millis: i64) -> BrandingExport {
BrandingExport {
format: BRANDING_EXPORT_FORMAT.to_string(),
version: BRANDING_EXPORT_VERSION,
exported_at: iso8601_millis(unix_millis),
branding: clone_branding(branding),
}
}
fn iso8601_millis(unix_millis: i64) -> String {
const MS_PER_DAY: i64 = 86_400_000;
let days = unix_millis.div_euclid(MS_PER_DAY);
let ms_of_day = unix_millis.rem_euclid(MS_PER_DAY);
let (hour, minute, second, milli) = (
ms_of_day / 3_600_000,
(ms_of_day / 60_000) % 60,
(ms_of_day / 1_000) % 60,
ms_of_day % 1_000,
);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = y + i64::from(m <= 2);
format!("{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{milli:03}Z")
}
fn value_str(v: Option<&Value>, fallback: &str) -> String {
match v.and_then(Value::as_str) {
Some(raw) => raw.to_string(),
None => fallback.to_string(),
}
}
fn value_hex(v: Option<&Value>, fallback: &str) -> String {
match v.and_then(Value::as_str) {
Some(raw) if is_hex_color(raw) => raw.to_string(),
_ => fallback.to_string(),
}
}
fn parse_trust_badges_loose(raw: Option<&Value>) -> Option<Vec<TrustBadge>> {
let items = raw?.as_array()?;
Some(
items
.iter()
.enumerate()
.filter_map(|(i, item)| {
let obj = item.as_object()?;
let hex = |k: &str| {
obj.get(k)
.and_then(Value::as_str)
.filter(|v| is_hex_color(v))
};
Some(TrustBadge {
id: match obj.get("id").and_then(Value::as_str) {
Some(id) if !id.is_empty() => id.to_string(),
_ => format!("badge-{i}"),
},
label: obj
.get("label")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
text_color: hex("textColor").unwrap_or("#0f172a").to_string(),
background_color: hex("backgroundColor").unwrap_or("#f1f5f9").to_string(),
border_color: hex("borderColor").map(str::to_string),
})
})
.filter(|b| !b.label.is_empty())
.collect(),
)
}
pub fn parse_imported_branding(raw: &Value) -> CheckoutBranding {
let root: Option<&Map<String, Value>> = match raw.as_object() {
Some(obj) => match obj.get("branding").and_then(Value::as_object) {
Some(inner) => Some(inner),
None => Some(obj),
},
None => None,
};
let Some(root) = root else {
return clone_branding(&DEFAULT_BRANDING);
};
let dflt = &*DEFAULT_BRANDING;
let g = |k: &str| root.get(k);
let trust_row = resolve_notices_and_badges(
parse_trust_badges_loose(g("trustBadges")),
parse_notices_loose(g("notices")),
);
let custom_fields = g("customFields")
.and_then(parse_custom_fields_loose)
.unwrap_or_default();
let label_style = pick_enum(g("labelStyle"), dflt.label_style);
CheckoutBranding {
display_name: value_str(g("displayName"), &dflt.display_name),
logo_url: value_str(g("logoUrl"), &dflt.logo_url),
tagline: value_str(g("tagline"), &dflt.tagline),
show_logo: parse_bool(g("showLogo"), dflt.show_logo),
logo_shape: pick_enum(g("logoShape"), dflt.logo_shape),
logo_size: pick_enum(g("logoSize"), dflt.logo_size),
primary: value_hex(g("primary"), &dflt.primary),
background: value_hex(g("background"), &dflt.background),
surface: value_hex(g("surface"), &dflt.surface),
text: value_hex(g("text"), &dflt.text),
heading: value_hex(g("heading"), &dflt.heading),
muted: value_hex(g("muted"), &dflt.muted),
border: value_hex(g("border"), &dflt.border),
accent_text: value_hex(g("accentText"), &dflt.accent_text),
button_background: value_hex(g("buttonBackground"), &dflt.button_background),
button_text: value_hex(g("buttonText"), &dflt.button_text),
font_family: pick_enum(g("fontFamily"), dflt.font_family),
heading_weight: pick_enum(g("headingWeight"), dflt.heading_weight),
radius_surface: pick_enum(g("radiusSurface"), dflt.radius_surface),
radius_input: pick_enum(g("radiusInput"), dflt.radius_input),
radius_button: pick_enum(g("radiusButton"), dflt.radius_button),
radius_badge: pick_enum(g("radiusBadge"), dflt.radius_badge),
surface_style: pick_enum(g("surfaceStyle"), dflt.surface_style),
surface_padding: pick_enum(g("surfacePadding"), dflt.surface_padding),
vertical_gap: pick_enum(g("verticalGap"), dflt.vertical_gap),
input_size: pick_enum(g("inputSize"), dflt.input_size),
button_size: pick_enum(g("buttonSize"), dflt.button_size),
layout: pick_enum(g("layout"), dflt.layout),
summary_position: pick_enum(g("summaryPosition"), dflt.summary_position),
show_order_summary: parse_bool(g("showOrderSummary"), dflt.show_order_summary),
summary_gradient: parse_bool(g("summaryGradient"), dflt.summary_gradient),
show_total: parse_bool(g("showTotal"), dflt.show_total),
total_label: value_str(g("totalLabel"), &dflt.total_label),
show_currency_code: parse_bool(g("showCurrencyCode"), dflt.show_currency_code),
show_order_items: parse_bool(g("showOrderItems"), dflt.show_order_items),
cancel_link_enabled: parse_bool(g("cancelLinkEnabled"), dflt.cancel_link_enabled),
cancel_link_position: pick_enum(g("cancelLinkPosition"), dflt.cancel_link_position),
cancel_link_style: pick_enum(g("cancelLinkStyle"), dflt.cancel_link_style),
trust_badges: trust_row.trust_badges,
notices: trust_row.notices,
custom_fields,
header_text: value_str(g("headerText"), &dflt.header_text),
pay_button_label: value_str(g("payButtonLabel"), &dflt.pay_button_label),
card_terms_message: value_str(g("cardTermsMessage"), &dflt.card_terms_message),
footer_text: value_str(g("footerText"), &dflt.footer_text),
support_email: value_str(g("supportEmail"), &dflt.support_email),
payment_layout: pick_enum(g("paymentLayout"), dflt.payment_layout),
label_style,
show_surcharge: parse_bool(g("showSurcharge"), dflt.show_surcharge),
surcharge_position: pick_enum(g("surchargePosition"), dflt.surcharge_position),
native_element_position: pick_enum(
g("nativeElementPosition"),
dflt.native_element_position,
),
native_element_stacked: parse_bool(g("nativeElementStacked"), dflt.native_element_stacked),
surcharge_style: pick_enum(g("surchargeStyle"), dflt.surcharge_style),
surcharge_size: pick_enum(g("surchargeSize"), dflt.surcharge_size),
surcharge_shape: pick_enum(g("surchargeShape"), dflt.surcharge_shape),
surcharge_border_width: pick_enum(g("surchargeBorderWidth"), dflt.surcharge_border_width),
surcharge_border_style: pick_enum(g("surchargeBorderStyle"), dflt.surcharge_border_style),
surcharge_weight: pick_enum(g("surchargeWeight"), dflt.surcharge_weight),
surcharge_sign: pick_enum(g("surchargeSign"), dflt.surcharge_sign),
surcharge_uppercase: parse_bool(g("surchargeUppercase"), dflt.surcharge_uppercase),
surcharge_label: pick_enum(g("surchargeLabel"), dflt.surcharge_label),
surcharge_figure: pick_enum(g("surchargeFigure"), dflt.surcharge_figure),
discount_figure: pick_enum(g("discountFigure"), dflt.discount_figure),
surcharge_color: value_hex(g("surchargeColor"), &dflt.surcharge_color),
discount_color: value_hex(g("discountColor"), &dflt.discount_color),
method_section_order: decode_method_section_order(
g("methodSectionOrder").map(|v| v.to_string()).as_deref(),
),
method_section_labels: decode_method_section_labels(
g("methodSectionLabels").map(|v| v.to_string()).as_deref(),
),
airwallex_card_preset: pick_optional_enum(g("airwallexCardPreset")),
airwallex_hide_card: parse_bool(g("airwallexHideCard"), dflt.airwallex_hide_card),
airwallex_hide_card_title: parse_bool(
g("airwallexHideCardTitle"),
dflt.airwallex_hide_card_title,
),
airwallex_field_chrome: pick_enum(g("airwallexFieldChrome"), dflt.airwallex_field_chrome),
airwallex_label_style: pick_optional_enum(g("airwallexLabelStyle")),
airwallex_field_font_size: pick_enum(
g("airwallexFieldFontSize"),
dflt.airwallex_field_font_size,
),
airwallex_field_weight: pick_enum(g("airwallexFieldWeight"), dflt.airwallex_field_weight),
airwallex_focus_ring: pick_enum(g("airwallexFocusRing"), dflt.airwallex_focus_ring),
airwallex_autofill: pick_enum(g("airwallexAutofill"), dflt.airwallex_autofill),
airwallex_valid_tint: parse_bool(g("airwallexValidTint"), dflt.airwallex_valid_tint),
airwallex_network_marks: parse_bool(
g("airwallexNetworkMarks"),
dflt.airwallex_network_marks,
),
stripe_theme: pick_enum(g("stripeTheme"), dflt.stripe_theme),
stripe_inputs: pick_enum(g("stripeInputs"), dflt.stripe_inputs),
stripe_labels: pick_enum(g("stripeLabels"), dflt.stripe_labels),
stripe_spacing: pick_enum(g("stripeSpacing"), dflt.stripe_spacing),
stripe_field_font_size: pick_enum(g("stripeFieldFontSize"), dflt.stripe_field_font_size),
stripe_field_weight: pick_enum(g("stripeFieldWeight"), dflt.stripe_field_weight),
stripe_focus_ring: pick_enum(g("stripeFocusRing"), dflt.stripe_focus_ring),
stripe_disable_animations: parse_bool(
g("stripeDisableAnimations"),
dflt.stripe_disable_animations,
),
paypal_card_layout: pick_enum(g("paypalCardLayout"), dflt.paypal_card_layout),
paypal_label_style: pick_enum(g("paypalLabelStyle"), dflt.paypal_label_style),
paypal_field_chrome: pick_enum(g("paypalFieldChrome"), dflt.paypal_field_chrome),
mollie_field_chrome: pick_enum(g("mollieFieldChrome"), dflt.mollie_field_chrome),
paypal_field_font_size: pick_enum(g("paypalFieldFontSize"), dflt.paypal_field_font_size),
mollie_field_font_size: pick_enum(g("mollieFieldFontSize"), dflt.mollie_field_font_size),
paypal_field_weight: pick_enum(g("paypalFieldWeight"), dflt.paypal_field_weight),
mollie_field_weight: pick_enum(g("mollieFieldWeight"), dflt.mollie_field_weight),
paypal_focus_ring: pick_enum(g("paypalFocusRing"), dflt.paypal_focus_ring),
mollie_focus_ring: pick_enum(g("mollieFocusRing"), dflt.mollie_focus_ring),
paypal_valid_tint: parse_bool(g("paypalValidTint"), dflt.paypal_valid_tint),
epayouts_card_layout: pick_enum(
g("epayoutsCardLayout"),
pick_enum(g("paypalCardLayout"), dflt.epayouts_card_layout),
),
epayouts_label_style: pick_enum(
g("epayoutsLabelStyle"),
pick_enum(g("paypalLabelStyle"), dflt.epayouts_label_style),
),
epayouts_field_chrome: pick_enum(
g("epayoutsFieldChrome"),
pick_enum(g("paypalFieldChrome"), dflt.epayouts_field_chrome),
),
epayouts_field_font_size: pick_enum(
g("epayoutsFieldFontSize"),
pick_enum(g("paypalFieldFontSize"), dflt.epayouts_field_font_size),
),
epayouts_field_weight: pick_enum(
g("epayoutsFieldWeight"),
pick_enum(g("paypalFieldWeight"), dflt.epayouts_field_weight),
),
epayouts_focus_ring: pick_enum(
g("epayoutsFocusRing"),
pick_enum(g("paypalFocusRing"), dflt.epayouts_focus_ring),
),
epayouts_valid_tint: parse_bool(
g("epayoutsValidTint"),
parse_bool(g("paypalValidTint"), dflt.epayouts_valid_tint),
),
nomupay_form_style: pick_enum(g("nomupayFormStyle"), dflt.nomupay_form_style),
nomupay_show_labels: parse_bool(g("nomupayShowLabels"), dflt.nomupay_show_labels),
nomupay_show_placeholders: parse_bool(
g("nomupayShowPlaceholders"),
dflt.nomupay_show_placeholders,
),
nomupay_show_cvv_hint: parse_bool(g("nomupayShowCvvHint"), dflt.nomupay_show_cvv_hint),
nomupay_field_chrome: pick_enum(g("nomupayFieldChrome"), dflt.nomupay_field_chrome),
nomupay_field_font_size: pick_enum(g("nomupayFieldFontSize"), dflt.nomupay_field_font_size),
nomupay_focus_ring: pick_enum(g("nomupayFocusRing"), dflt.nomupay_focus_ring),
nomupay_apple_pay_button_style: pick_enum(
g("nomupayApplePayButtonStyle"),
dflt.nomupay_apple_pay_button_style,
),
nomupay_apple_pay_button_type: pick_enum(
g("nomupayApplePayButtonType"),
dflt.nomupay_apple_pay_button_type,
),
nomupay_google_pay_button_color: pick_enum(
g("nomupayGooglePayButtonColor"),
dflt.nomupay_google_pay_button_color,
),
nomupay_google_pay_button_type: pick_enum(
g("nomupayGooglePayButtonType"),
dflt.nomupay_google_pay_button_type,
),
micropayment_field_chrome: pick_enum(
g("micropaymentFieldChrome"),
dflt.micropayment_field_chrome,
),
micropayment_field_font_size: pick_enum(
g("micropaymentFieldFontSize"),
dflt.micropayment_field_font_size,
),
micropayment_field_weight: pick_enum(
g("micropaymentFieldWeight"),
dflt.micropayment_field_weight,
),
micropayment_focus_ring: pick_enum(
g("micropaymentFocusRing"),
dflt.micropayment_focus_ring,
),
whop_card_preset: pick_enum(g("whopCardPreset"), dflt.whop_card_preset),
whop_accent_color: pick_enum(g("whopAccentColor"), dflt.whop_accent_color),
whop_gray_color: pick_enum(g("whopGrayColor"), dflt.whop_gray_color),
whop_billing_details: pick_enum(g("whopBillingDetails"), dflt.whop_billing_details),
whop_separated: parse_bool(g("whopSeparated"), dflt.whop_separated),
whop_email_label: pick_enum(g("whopEmailLabel"), dflt.whop_email_label),
whop_field_chrome: pick_enum(g("whopFieldChrome"), dflt.whop_field_chrome),
whop_field_font_size: pick_enum(g("whopFieldFontSize"), dflt.whop_field_font_size),
whop_field_weight: pick_enum(g("whopFieldWeight"), dflt.whop_field_weight),
whop_focus_ring: pick_enum(g("whopFocusRing"), dflt.whop_focus_ring),
whop_radius: pick_enum(g("whopRadius"), dflt.whop_radius),
whop_shadow: pick_enum(g("whopShadow"), dflt.whop_shadow),
whop_method_icons: parse_bool(g("whopMethodIcons"), dflt.whop_method_icons),
whop_selection: pick_enum(g("whopSelection"), dflt.whop_selection),
show_powered_by: parse_bool(g("showPoweredBy"), dflt.show_powered_by),
custom_css: truncate_utf16(&value_str(g("customCss"), &dflt.custom_css)),
}
}
fn truncate_utf16(s: &str) -> String {
if utf16_len(s) <= CUSTOM_CSS_MAX_LENGTH {
return s.to_string();
}
let mut out = String::new();
let mut units = 0;
for c in s.chars() {
let w = c.len_utf16();
if units + w > CUSTOM_CSS_MAX_LENGTH {
break;
}
units += w;
out.push(c);
}
out
}
pub fn branding_variables(b: &CheckoutBranding) -> Vec<(&'static str, String)> {
vec![
("--dp-primary", b.primary.clone()),
("--dp-bg", b.background.clone()),
("--dp-surface", b.surface.clone()),
("--dp-text", b.text.clone()),
("--dp-heading", b.heading.clone()),
("--dp-muted", b.muted.clone()),
("--dp-border", b.border.clone()),
("--dp-accent-text", b.accent_text.clone()),
("--dp-btn-bg", b.button_background.clone()),
("--dp-btn-fg", b.button_text.clone()),
(
"--dp-radius-surface",
radius_value(b.radius_surface.into()).to_string(),
),
(
"--dp-radius-input",
radius_value(b.radius_input.into()).to_string(),
),
(
"--dp-radius-button",
radius_value(b.radius_button).to_string(),
),
(
"--dp-radius-badge",
radius_value(b.radius_badge).to_string(),
),
("--dp-font", font_stack(b.font_family).to_string()),
(
"--dp-heading-weight",
font_weight_value(b.heading_weight).to_string(),
),
(
"--dp-pad-surface",
surface_pad_value(b.surface_padding).to_string(),
),
(
"--dp-gap-vertical",
vertical_gap_value(b.vertical_gap).to_string(),
),
("--dp-input-pad", input_pad_value(b.input_size).to_string()),
(
"--dp-button-pad",
button_pad_value(b.button_size).to_string(),
),
("--dp-surcharge", b.surcharge_color.clone()),
("--dp-discount", b.discount_color.clone()),
(
"--dp-surcharge-ink",
readable_ink_on(&b.surcharge_color).to_string(),
),
(
"--dp-discount-ink",
readable_ink_on(&b.discount_color).to_string(),
),
(
"--dp-surcharge-size",
surcharge_font_size(b.surcharge_size).to_string(),
),
(
"--dp-surcharge-pad",
surcharge_pad(b.surcharge_size).to_string(),
),
(
"--dp-surcharge-radius",
surcharge_radius(b.surcharge_shape).to_string(),
),
(
"--dp-surcharge-weight",
surcharge_font_weight(b.surcharge_weight).to_string(),
),
(
"--dp-surcharge-border-width",
surcharge_border_width_value(
if b.surcharge_style == SurchargeStyle::Outline
&& b.surcharge_border_width == SurchargeBorderWidth::None
{
SurchargeBorderWidth::Thin
} else {
b.surcharge_border_width
},
)
.to_string(),
),
(
"--dp-surcharge-border-style",
b.surcharge_border_style.as_str().to_string(),
),
("--dp-shadow", shadow_for(b.surface_style).to_string()),
(
"--dp-surface-border",
if b.surface_style == SurfaceStyle::Outlined {
format!("1px solid {}", b.border)
} else {
"1px solid transparent".to_string()
},
),
]
}
pub fn branding_variables_css(b: &CheckoutBranding) -> String {
let mut out = String::from(":root{");
for (k, v) in branding_variables(b) {
out.push_str(k);
out.push(':');
out.push_str(&v);
out.push(';');
}
out.push('}');
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn token_maps_have_the_documented_values() {
assert_eq!(
font_stack(FontFamily::Inter),
"'Inter Variable', 'Inter', system-ui, -apple-system, sans-serif"
);
assert_eq!(
font_stack(FontFamily::Serif),
"Georgia, 'Times New Roman', serif"
);
assert_eq!(
font_stack(FontFamily::DmSans),
"'DM Sans Variable', 'DM Sans', system-ui, sans-serif"
);
assert_eq!(radius_value(CornerRadius::Square), "0px");
assert_eq!(radius_value(CornerRadius::Small), "6px");
assert_eq!(radius_value(CornerRadius::Medium), "12px");
assert_eq!(radius_value(CornerRadius::Large), "20px");
assert_eq!(radius_value(CornerRadius::Pill), "999px");
assert_eq!(font_weight_value(FontWeight::Regular), "400");
assert_eq!(font_weight_value(FontWeight::Medium), "500");
assert_eq!(font_weight_value(FontWeight::Semibold), "600");
assert_eq!(font_weight_value(FontWeight::Bold), "700");
assert_eq!(surface_pad_value(SpacingScale::Compact), "1rem");
assert_eq!(surface_pad_value(SpacingScale::Comfortable), "1.5rem");
assert_eq!(surface_pad_value(SpacingScale::Spacious), "2rem");
assert_eq!(vertical_gap_value(SpacingScale::Compact), "0.75rem");
assert_eq!(vertical_gap_value(SpacingScale::Comfortable), "1rem");
assert_eq!(vertical_gap_value(SpacingScale::Spacious), "1.5rem");
assert_eq!(input_pad_value(SizeScale::Sm), "0.5rem 0.75rem");
assert_eq!(input_pad_value(SizeScale::Md), "0.625rem 0.75rem");
assert_eq!(input_pad_value(SizeScale::Lg), "0.875rem 0.875rem");
assert_eq!(button_pad_value(SizeScale::Sm), "0.625rem 1rem");
assert_eq!(button_pad_value(SizeScale::Md), "0.875rem 1.25rem");
assert_eq!(button_pad_value(SizeScale::Lg), "1.125rem 1.5rem");
}
#[test]
fn logo_dimensions_scale() {
assert_eq!(
logo_dimensions(LogoSize::Sm),
LogoDimensions { px: 36, radius: 8 }
);
assert_eq!(
logo_dimensions(LogoSize::Md),
LogoDimensions { px: 48, radius: 12 }
);
assert_eq!(
logo_dimensions(LogoSize::Lg),
LogoDimensions { px: 64, radius: 16 }
);
}
#[test]
fn shadow_only_on_elevated() {
assert_eq!(
shadow_for(SurfaceStyle::Elevated),
"0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 32px -12px rgba(15, 23, 42, 0.08)"
);
assert_eq!(shadow_for(SurfaceStyle::Flat), "none");
assert_eq!(shadow_for(SurfaceStyle::Outlined), "none");
}
#[test]
fn is_hex_color_accepts_three_and_six_digits_only() {
assert!(is_hex_color("#fff"));
assert!(is_hex_color("#FFFFFF"));
assert!(is_hex_color(" #1E4FEB "), "surrounding space is trimmed");
assert!(!is_hex_color("fff"), "leading # required");
assert!(!is_hex_color("#ffff"));
assert!(!is_hex_color("#fffffff"));
assert!(!is_hex_color("#gggggg"));
assert!(!is_hex_color("#"));
assert!(!is_hex_color(""));
}
#[test]
fn contrast_ratio_matches_the_wcag_reference_values() {
let black_on_white = contrast_ratio("#000000", "#ffffff").unwrap();
assert!((black_on_white - 21.0).abs() < 1e-9);
assert!((contrast_ratio("#ffffff", "#000000").unwrap() - 21.0).abs() < 1e-9);
assert!((contrast_ratio("#ffffff", "#ffffff").unwrap() - 1.0).abs() < 1e-9);
let grey = contrast_ratio("#767676", "#ffffff").unwrap();
assert!(grey >= WCAG_AA_TEXT, "expected AA text pass, got {grey}");
assert!(grey < 5.0, "expected a near-threshold value, got {grey}");
assert!(
(contrast_ratio("#fff", "#000").unwrap() - 21.0).abs() < 1e-9,
"the 3-digit form expands to the same colour"
);
}
#[test]
fn an_unparseable_colour_has_no_ratio() {
assert_eq!(contrast_ratio("000", "#ffffff"), None);
assert_eq!(contrast_ratio("#ffffff", "not-a-colour"), None);
assert_eq!(contrast_ratio("#0g0g0g", "#ffffff"), None);
assert_eq!(contrast_ratio("#ffff", "#000000"), None);
assert_eq!(contrast_ratio("", ""), None);
}
#[test]
fn the_luma_split_is_not_a_readability_test() {
assert!(is_dark_surface("#ff00ff"));
assert!(contrast_ratio("#ff00ff", "#ffffff").unwrap() < WCAG_AA_TEXT);
assert!(!is_dark_surface("#00ff00"));
assert!(contrast_ratio("#00ff00", "#ffffff").unwrap() < WCAG_AA_TEXT);
}
#[test]
fn is_dark_surface_uses_perceived_luminance() {
assert!(is_dark_surface("#000000"));
assert!(is_dark_surface("#000"));
assert!(is_dark_surface("#1E4FEB"), "brand blue is dark (luma 82)");
assert!(!is_dark_surface("#ffffff"));
assert!(!is_dark_surface("#f8fafc"));
assert!(!is_dark_surface("#808080"));
assert!(is_dark_surface("#7f7f7f"), "one step darker flips it");
assert!(!is_dark_surface("not-a-color"));
assert!(!is_dark_surface("#zzzzzz"));
assert!(!is_dark_surface(""));
}
fn sanitize(css: &str) -> String {
sanitize_custom_css(Some(css)).expect("expected sanitized output")
}
#[test]
fn sanitize_rejects_absent_blank_and_oversized_input() {
assert_eq!(sanitize_custom_css(None), None);
assert_eq!(sanitize_custom_css(Some("")), None);
assert_eq!(sanitize_custom_css(Some(" \n\t ")), None);
let big = "a".repeat(CUSTOM_CSS_MAX_LENGTH + 1);
assert_eq!(sanitize_custom_css(Some(&big)), None);
let at_limit = "a".repeat(CUSTOM_CSS_MAX_LENGTH);
assert_eq!(sanitize_custom_css(Some(&at_limit)), Some(at_limit));
}
#[test]
fn sanitize_trims_and_passes_benign_css_through() {
assert_eq!(
sanitize(" .dp-card { background: linear-gradient(#fff, #000); } "),
".dp-card { background: linear-gradient(#fff, #000); }"
);
assert_eq!(
sanitize("@media (min-width: 40rem) { .x { transform: rotate(1deg) } }"),
"@media (min-width: 40rem) { .x { transform: rotate(1deg) } }"
);
}
#[test]
fn sanitize_escapes_style_close_tag() {
assert_eq!(
sanitize(".x{}</style><script>alert(1)</script>"),
".x{}<\\/style><script>alert(1)</script>",
"only the </style break-out is escaped"
);
assert_eq!(sanitize("</STYLE>"), "<\\/style>");
assert_eq!(sanitize("</styled-tag"), "<\\/styled-tag");
}
#[test]
fn sanitize_strips_import_rules() {
assert_eq!(
sanitize("@import url(https://evil.test/x.css); .a{}"),
" .a{}"
);
assert_eq!(sanitize("@IMPORT 'x.css';.a{}"), ".a{}");
assert_eq!(sanitize(".a{}\n@import \"x.css\""), ".a{}\n");
assert_eq!(
sanitize("@importantly { color: red }"),
"@importantly { color: red }"
);
}
#[test]
fn sanitize_comments_out_expression() {
assert_eq!(
sanitize("width: expression(alert(1));"),
"width: /* expression( */alert(1));"
);
assert_eq!(
sanitize("width: EXPRESSION (1)"),
"width: /* expression( */1)"
);
assert_eq!(
sanitize("/* expression of intent */"),
"/* expression of intent */"
);
}
#[test]
fn sanitize_comments_out_behavior_but_not_prefixed_properties() {
assert_eq!(sanitize("behavior: url(#x)"), "/* behavior: */ url(#x)");
assert_eq!(
sanitize(".a{ behavior : url(#x) }"),
".a{ /* behavior: */ url(#x) }"
);
assert_eq!(sanitize(".a{ BEHAVIOR:x }"), ".a{ /* behavior: */x }");
assert_eq!(sanitize("-webkit-behavior: x"), "-webkit-behavior: x");
assert_eq!(sanitize("scrollbehavior: x"), "scrollbehavior: x");
}
#[test]
fn sanitize_comments_out_moz_binding() {
assert_eq!(
sanitize("-moz-binding: url(evil.xml#x)"),
"/* -moz-binding: */ url(evil.xml#x)"
);
assert_eq!(sanitize("-MOZ-BINDING :x"), "/* -moz-binding: */x");
}
#[test]
fn sanitize_neutralizes_javascript_urls() {
assert_eq!(
sanitize("background: url(javascript:alert(1))"),
"background: url(invalid:alert(1))"
);
assert_eq!(
sanitize("background: URL ( \"javascript:alert(1)\" )"),
"background: url(invalid:alert(1)\" )"
);
assert_eq!(
sanitize("background: url('JAVASCRIPT:x')"),
"background: url(invalid:x')"
);
assert_eq!(
sanitize("background: url(https://cdn.test/a.png)"),
"background: url(https://cdn.test/a.png)"
);
}
#[test]
fn sanitize_handles_several_constructs_in_one_payload() {
let out = sanitize(
"@import url(evil);\n.a{ behavior: url(#x); -moz-binding: url(y); \
background: url( 'javascript:1' ); width: expression(2) }</style",
);
assert_eq!(
out,
"\n.a{ /* behavior: */ url(#x); /* -moz-binding: */ url(y); \
background: url(invalid:1' ); width: /* expression( */2) }<\\/style"
);
assert!(!out.contains("@import"), "{out}");
assert!(!out.contains("javascript:"), "{out}");
assert!(!out.contains("</style"), "{out}");
assert!(out.contains("url(invalid:"), "{out}");
assert!(out.contains("/* behavior: */"), "{out}");
assert!(out.contains("/* -moz-binding: */"), "{out}");
assert!(out.contains("/* expression( */"), "{out}");
assert!(out.contains("<\\/style"), "{out}");
}
#[test]
fn encode_badges_matches_the_typescript_json_string() {
assert_eq!(
encode_badges(&DEFAULT_BADGES),
"[{\"id\":\"secure\",\"label\":\"Secure\",\"textColor\":\"#047857\",\
\"backgroundColor\":\"#ecfdf5\",\"borderColor\":\"#a7f3d0\"},\
{\"id\":\"ssl\",\"label\":\"256-bit SSL\",\"textColor\":\"#1E4FEB\",\
\"backgroundColor\":\"#eff6ff\",\"borderColor\":\"#bfdbfe\"}]"
);
assert_eq!(
encode_badges(&[TrustBadge::new("a", "A", "#000", "#fff")]),
"[{\"id\":\"a\",\"label\":\"A\",\"textColor\":\"#000\",\"backgroundColor\":\"#fff\"}]"
);
assert_eq!(encode_badges(&[]), "[]");
}
#[test]
fn decode_badges_is_tolerant() {
assert_eq!(decode_badges(None), None);
assert_eq!(decode_badges(Some("not json")), None);
assert_eq!(
decode_badges(Some("{\"a\":1}")),
None,
"non-array is rejected"
);
assert_eq!(
decode_badges(Some("[]")),
Some(vec![]),
"an explicit empty list means 'hide the row'"
);
let decoded = decode_badges(Some("[{\"label\":\"L\"},{\"label\":\"\"},{\"id\":\"x\"}]"))
.expect("array parses");
assert_eq!(decoded.len(), 1, "label-less badges are dropped");
assert_eq!(decoded[0].id, "badge-0", "missing id falls back to index");
assert_eq!(decoded[0].text_color, "#0f172a");
assert_eq!(decoded[0].background_color, "#f1f5f9");
assert_eq!(decoded[0].border_color, None);
}
#[test]
fn badges_round_trip() {
let encoded = encode_badges(&DEFAULT_BADGES_DARK);
assert_eq!(decode_badges(Some(&encoded)).unwrap(), *DEFAULT_BADGES_DARK);
}
fn source_with(extras: Value) -> BrandingSource {
let mut rules = Map::new();
rules.insert(BRANDING_GROUP_KEY.to_string(), extras);
BrandingSource {
sdk_ui_rules: Some(rules),
..Default::default()
}
}
#[test]
fn decode_branding_without_a_source_is_the_default() {
assert_eq!(decode_branding(None), *DEFAULT_BRANDING);
assert_eq!(
decode_branding(Some(&BrandingSource::default())),
*DEFAULT_BRANDING
);
}
#[test]
fn decode_branding_prefers_the_public_name_aliases() {
let src = BrandingSource {
merchant_name: Some("Public".into()),
seller_name: Some("Request".into()),
merchant_logo: Some("https://a.test/logo.png".into()),
logo: Some("https://b.test/logo.png".into()),
..Default::default()
};
let b = decode_branding(Some(&src));
assert_eq!(b.display_name, "Public");
assert_eq!(b.logo_url, "https://a.test/logo.png");
let src = BrandingSource {
seller_name: Some("Request".into()),
logo: Some("https://b.test/logo.png".into()),
..Default::default()
};
let b = decode_branding(Some(&src));
assert_eq!(
b.display_name, "Request",
"falls back to the request spelling"
);
assert_eq!(b.logo_url, "https://b.test/logo.png");
}
#[test]
fn decode_branding_colour_fallback_chain() {
let mut src = source_with(json!({ "text": "#111111" }));
src.theme = Some("#123456".into());
let b = decode_branding(Some(&src));
assert_eq!(b.primary, "#123456");
assert_eq!(b.accent_text, "#123456", "accentText falls back to theme");
assert_eq!(
b.button_background, "#123456",
"button background falls back to theme"
);
assert_eq!(b.heading, "#111111", "heading falls back to the bag's text");
assert_eq!(b.text, "#111111");
let mut src = source_with(json!({ "heading": "#222222", "accentText": "#333333" }));
src.theme = Some("#123456".into());
src.payment_button_colour = Some("#654321".into());
let b = decode_branding(Some(&src));
assert_eq!(b.heading, "#222222");
assert_eq!(b.accent_text, "#333333");
assert_eq!(b.button_background, "#654321");
}
#[test]
fn decode_branding_tagline_prefers_the_bag() {
let mut src = source_with(json!({ "tagline": "from bag" }));
src.merchant_description = Some("from column".into());
assert_eq!(decode_branding(Some(&src)).tagline, "from bag");
let mut src = source_with(json!({}));
src.merchant_description = Some("from column".into());
assert_eq!(decode_branding(Some(&src)).tagline, "from column");
}
#[test]
fn decode_branding_normalizes_label_style() {
let bagged =
|v: &str| decode_branding(Some(&source_with(json!({ "labelStyle": v })))).label_style;
assert_eq!(bagged("above"), LabelStyle::Above);
assert_eq!(bagged("hidden"), LabelStyle::Hidden);
assert_eq!(
bagged("floating"),
LabelStyle::Above,
"legacy floating -> above"
);
let legacy = |v: &str| {
let src = BrandingSource {
payment_form_label_type: Some(v.to_string()),
..Default::default()
};
decode_branding(Some(&src)).label_style
};
assert_eq!(
legacy("never"),
LabelStyle::Hidden,
"legacy never -> hidden"
);
assert_eq!(legacy("hidden"), LabelStyle::Hidden);
assert_eq!(legacy("floating"), LabelStyle::Above);
assert_eq!(legacy("nonsense"), LabelStyle::Above, "default");
let mut src = source_with(json!({ "labelStyle": "hidden" }));
src.payment_form_label_type = Some("above".into());
assert_eq!(decode_branding(Some(&src)).label_style, LabelStyle::Hidden);
let mut src = source_with(json!({ "labelStyle": "floating" }));
src.payment_form_label_type = Some("never".into());
assert_eq!(decode_branding(Some(&src)).label_style, LabelStyle::Above);
}
#[test]
fn decode_branding_rejects_out_of_range_enum_values() {
let src = source_with(json!({
"radiusSurface": "pill",
"radiusButton": "pill",
"fontFamily": "comic-sans",
"inputSize": "xl",
"layout": "split",
}));
let b = decode_branding(Some(&src));
assert_eq!(
b.radius_surface,
NonPillRadius::Medium,
"a stale 'pill' surface radius drops back to medium"
);
assert_eq!(b.radius_button, CornerRadius::Pill, "buttons may be pill");
assert_eq!(b.font_family, FontFamily::Inter);
assert_eq!(b.input_size, SizeScale::Md);
assert_eq!(b.layout, LayoutStyle::Split);
}
#[test]
fn decode_branding_parses_stringified_booleans() {
let src = source_with(json!({
"showLogo": "true",
"showTotal": "false",
"summaryGradient": true,
"showOrderItems": "yes",
}));
let b = decode_branding(Some(&src));
assert!(b.show_logo, "'true' string flips the default false");
assert!(!b.show_total, "'false' string flips the default true");
assert!(b.summary_gradient, "a real boolean is honoured");
assert!(b.show_order_items, "an unparseable value keeps the default");
}
#[test]
fn decode_branding_powered_by_only_hides_on_explicit_false() {
let with = |v: Option<bool>| {
let src = BrandingSource {
branding_visibility: v,
..Default::default()
};
decode_branding(Some(&src)).show_powered_by
};
assert!(with(None), "absent means shown");
assert!(with(Some(true)));
assert!(!with(Some(false)), "only an explicit false hides it");
}
#[test]
fn decode_branding_reads_flat_copy_and_layout_columns() {
let src = BrandingSource {
payment_form_header_text: Some("Checkout".into()),
payment_button_text: Some("Pay now".into()),
custom_message_for_card_terms: Some("Terms".into()),
sdk_layout: Some("accordion".into()),
..Default::default()
};
let b = decode_branding(Some(&src));
assert_eq!(b.header_text, "Checkout");
assert_eq!(b.pay_button_label, "Pay now");
assert_eq!(b.card_terms_message, "Terms");
assert_eq!(b.payment_layout, PaymentLayout::Accordion);
}
#[test]
fn decode_branding_migrates_an_untouched_trust_row_to_notices() {
let b = decode_branding(Some(&source_with(json!({}))));
assert!(b.trust_badges.is_empty());
assert_eq!(b.notices, *DEFAULT_NOTICES);
let b = decode_branding(Some(&source_with(json!({ "trustBadges": "[]" }))));
assert!(
b.trust_badges.is_empty(),
"an explicit empty list is honoured"
);
assert!(b.notices.is_empty(), "and no notices are added to it");
let b = decode_branding(Some(&source_with(json!({ "trustBadges": "broken" }))));
assert!(b.trust_badges.is_empty(), "malformed reads as absent");
assert_eq!(b.notices, *DEFAULT_NOTICES);
}
#[test]
fn decode_branding_reads_custom_fields_from_the_bag() {
let b = decode_branding(Some(&source_with(json!({}))));
assert!(b.custom_fields.is_empty());
let b = decode_branding(Some(&source_with(json!({ "customFields": "broken" }))));
assert!(b.custom_fields.is_empty(), "malformed -> none");
let b = decode_branding(Some(&source_with(json!({
"customFields": r#"[{"key":"login","type":"email","required":true}]"#
}))));
assert_eq!(b.custom_fields.len(), 1);
assert_eq!(b.custom_fields[0].key, "login");
assert!(b.custom_fields[0].required);
}
#[test]
fn encode_branding_omits_custom_fields_when_there_are_none() {
let e = encode_branding(&default_branding());
let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
assert!(bag.get("customFields").is_none(), "{bag:?}");
}
#[test]
fn encode_branding_round_trips_custom_fields_through_the_bag() {
use crate::core::custom_fields::{CheckoutCustomField, CustomFieldType};
let mut b = default_branding();
let mut field = CheckoutCustomField::new("login");
field.field_type = CustomFieldType::Email;
field.required = true;
b.custom_fields = vec![field];
let encoded = encode_branding(&b);
let source =
source_with(serde_json::to_value(&encoded.sdk_ui_rules[BRANDING_GROUP_KEY]).unwrap());
assert_eq!(
decode_branding(Some(&source)).custom_fields,
b.custom_fields
);
}
fn customized() -> CheckoutBranding {
CheckoutBranding {
display_name: " Acme ".into(),
logo_url: "https://acme.test/logo.png".into(),
tagline: " fast checkout ".into(),
show_logo: true,
logo_shape: LogoShape::Circle,
logo_size: LogoSize::Lg,
primary: "#123456".into(),
surface: "#fefefe".into(),
radius_button: CornerRadius::Pill,
radius_surface: NonPillRadius::Large,
surface_style: SurfaceStyle::Outlined,
layout: LayoutStyle::Compact,
summary_position: SummaryPosition::Right,
show_total: false,
total_label: "Sum".into(),
label_style: LabelStyle::Hidden,
payment_layout: PaymentLayout::SpacedAccordion,
show_powered_by: false,
footer_text: " bye ".into(),
support_email: "help@acme.test".into(),
custom_css: ".a{}".into(),
header_text: " ".into(),
trust_badges: vec![TrustBadge::new("x", "X", "#000000", "#ffffff")],
..default_branding()
}
}
#[test]
fn encode_branding_fills_the_flat_columns() {
let b = customized();
let e = encode_branding(&b);
assert_eq!(e.theme, "#123456");
assert_eq!(e.logo.as_deref(), Some("https://acme.test/logo.png"));
assert_eq!(e.seller_name.as_deref(), Some("Acme"), "trimmed");
assert_eq!(e.payment_form_header_text, None, "blank copy becomes null");
assert_eq!(e.payment_button_colour, b.button_background);
assert_eq!(e.payment_button_text_colour, b.button_text);
assert_eq!(e.background_colour, b.background);
assert_eq!(e.sdk_layout, PaymentLayout::SpacedAccordion);
assert_eq!(
e.payment_form_label_type,
LegacyLabelType::Never,
"hidden maps back to the legacy `never`"
);
assert!(!e.branding_visibility);
let mut above = b.clone();
above.label_style = LabelStyle::Above;
assert_eq!(
encode_branding(&above).payment_form_label_type,
LegacyLabelType::Above
);
}
#[test]
fn encode_branding_writes_the_branding_bag() {
let e = encode_branding(&customized());
let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
assert_eq!(bag["radiusButton"], "pill");
assert_eq!(bag["radiusSurface"], "large");
assert_eq!(bag["surfaceStyle"], "outlined");
assert_eq!(bag["labelStyle"], "hidden");
assert_eq!(bag["showLogo"], "true", "booleans persist as strings");
assert_eq!(bag["showTotal"], "false");
assert_eq!(bag["totalLabel"], "Sum");
assert_eq!(bag["tagline"], "fast checkout", "trimmed");
assert_eq!(bag["footerText"], "bye");
assert_eq!(bag["supportEmail"], "help@acme.test");
assert_eq!(bag["customCss"], ".a{}");
assert_eq!(
bag["trustBadges"],
"[{\"id\":\"x\",\"label\":\"X\",\"textColor\":\"#000000\",\"backgroundColor\":\"#ffffff\"}]"
);
}
#[test]
fn encode_branding_omits_blank_optional_bag_entries() {
let bag = encode_branding(&default_branding()).sdk_ui_rules[BRANDING_GROUP_KEY].clone();
for key in ["tagline", "footerText", "supportEmail", "customCss"] {
assert!(!bag.contains_key(key), "{key} must be omitted when blank");
}
}
#[test]
fn encode_branding_with_base_preserves_unrelated_fields_and_rule_groups() {
let base = json!({
"show_card_terms": true,
"domain_name": "acme.test",
"theme": "#000000",
"sdk_ui_rules": {
"other_group": { "keep": "me" },
"branding": { "stale": "gone" },
},
});
let out = encode_branding_with_base(&customized(), Some(&base));
assert_eq!(
out["show_card_terms"],
json!(true),
"unknown fields survive"
);
assert_eq!(out["domain_name"], json!("acme.test"));
assert_eq!(
out["theme"],
json!("#123456"),
"encoded fields win over base"
);
assert_eq!(out["sdk_ui_rules"]["other_group"]["keep"], json!("me"));
assert_eq!(
out["sdk_ui_rules"]["branding"].get("stale"),
None,
"the branding group is replaced wholesale"
);
assert_eq!(
out["sdk_ui_rules"]["branding"]["radiusButton"],
json!("pill")
);
let bare = encode_branding_with_base(&customized(), None);
assert_eq!(
bare,
serde_json::to_value(encode_branding(&customized())).unwrap()
);
}
#[test]
fn encode_then_decode_round_trips() {
let original = customized();
let encoded = encode_branding(&original);
let source: BrandingSource =
serde_json::from_value(serde_json::to_value(&encoded).unwrap()).unwrap();
let decoded = decode_branding(Some(&source));
let mut expected = original.clone();
expected.display_name = "Acme".into();
expected.tagline = "fast checkout".into();
expected.footer_text = "bye".into();
expected.header_text = String::new();
assert_eq!(decoded, expected);
}
#[test]
fn round_trip_survives_the_dark_default() {
let encoded = encode_branding(&DEFAULT_BRANDING_DARK);
let source: BrandingSource =
serde_json::from_value(serde_json::to_value(&encoded).unwrap()).unwrap();
assert_eq!(decode_branding(Some(&source)), *DEFAULT_BRANDING_DARK);
}
#[test]
fn iso8601_matches_javascript_to_iso_string() {
assert_eq!(iso8601_millis(0), "1970-01-01T00:00:00.000Z");
assert_eq!(
iso8601_millis(1_700_000_000_000),
"2023-11-14T22:13:20.000Z"
);
assert_eq!(
iso8601_millis(1_700_000_000_123),
"2023-11-14T22:13:20.123Z"
);
assert_eq!(
iso8601_millis(1_709_164_800_000),
"2024-02-29T00:00:00.000Z"
);
assert_eq!(iso8601_millis(-1), "1969-12-31T23:59:59.999Z");
}
#[test]
fn build_branding_export_wraps_the_branding() {
let e = build_branding_export_at(&customized(), 1_700_000_000_000);
assert_eq!(e.format, "delopay-checkout-branding");
assert_eq!(e.version, 1);
assert_eq!(e.exported_at, "2023-11-14T22:13:20.000Z");
assert_eq!(e.branding, customized());
let json = serde_json::to_value(&e).unwrap();
assert_eq!(json["branding"]["radiusButton"], json!("pill"));
assert_eq!(json["branding"]["showPoweredBy"], json!(false));
}
#[test]
fn export_import_round_trips() {
let e = build_branding_export_at(&customized(), 0);
let raw = serde_json::to_value(&e).unwrap();
assert_eq!(parse_imported_branding(&raw), customized());
}
#[test]
fn parse_imported_branding_accepts_a_bare_object() {
let raw = serde_json::to_value(customized()).unwrap();
assert_eq!(parse_imported_branding(&raw), customized());
}
#[test]
fn parse_imported_branding_falls_back_on_junk() {
assert_eq!(parse_imported_branding(&json!(null)), *DEFAULT_BRANDING);
assert_eq!(
parse_imported_branding(&json!([1, 2, 3])),
*DEFAULT_BRANDING
);
assert_eq!(parse_imported_branding(&json!("nope")), *DEFAULT_BRANDING);
assert_eq!(parse_imported_branding(&json!({})), *DEFAULT_BRANDING);
}
#[test]
fn parse_imported_branding_validates_each_field_independently() {
let raw = json!({
"displayName": "Acme",
"primary": "not-a-hex",
"background": "#abc",
"surface": 42,
"fontFamily": "comic-sans",
"logoSize": "lg",
"radiusBadge": "square",
"showLogo": "true",
"showPoweredBy": false,
"labelStyle": "floating",
"totalLabel": 7,
"trustBadges": "not-an-array",
"unknownField": "ignored",
});
let b = parse_imported_branding(&raw);
assert_eq!(b.display_name, "Acme");
assert_eq!(
b.primary, DEFAULT_BRANDING.primary,
"bad hex keeps the default"
);
assert_eq!(b.background, "#abc", "a 3-digit hex is valid");
assert_eq!(
b.surface, DEFAULT_BRANDING.surface,
"non-strings keep the default"
);
assert_eq!(b.font_family, FontFamily::Inter);
assert_eq!(b.logo_size, LogoSize::Lg);
assert_eq!(b.radius_badge, CornerRadius::Square);
assert!(b.show_logo);
assert!(!b.show_powered_by);
assert_eq!(
b.label_style, DEFAULT_BRANDING.label_style,
"the importer does not accept the legacy floating value"
);
assert_eq!(b.total_label, DEFAULT_BRANDING.total_label);
assert!(b.trust_badges.is_empty());
assert_eq!(b.notices, *DEFAULT_NOTICES);
}
#[test]
fn parse_imported_branding_reads_loose_trust_badges() {
let raw = json!({
"trustBadges": [
{ "id": "a", "label": "A", "textColor": "#010101",
"backgroundColor": "#020202", "borderColor": "#030303" },
{ "label": "B", "textColor": "rgb(1,2,3)", "borderColor": "nope" },
{ "label": "" },
"not-an-object",
],
});
let badges = parse_imported_branding(&raw).trust_badges;
assert_eq!(
badges.len(),
2,
"label-less and non-object entries are dropped"
);
assert_eq!(badges[0].border_color.as_deref(), Some("#030303"));
assert_eq!(badges[1].id, "badge-1", "index-based id fallback");
assert_eq!(badges[1].text_color, "#0f172a", "non-hex colours fall back");
assert_eq!(badges[1].background_color, "#f1f5f9");
assert_eq!(badges[1].border_color, None, "a non-hex border is dropped");
let raw = json!({ "trustBadges": [] });
assert!(parse_imported_branding(&raw).trust_badges.is_empty());
}
#[test]
fn parse_imported_branding_truncates_custom_css() {
let raw = json!({ "customCss": "x".repeat(CUSTOM_CSS_MAX_LENGTH + 10) });
let css = parse_imported_branding(&raw).custom_css;
assert_eq!(css.len(), CUSTOM_CSS_MAX_LENGTH);
let raw = json!({ "customCss": ".a{}" });
assert_eq!(parse_imported_branding(&raw).custom_css, ".a{}");
}
#[test]
fn defaults_are_the_documented_palettes() {
assert_eq!(DEFAULT_BRANDING.primary, "#1E4FEB");
assert_eq!(DEFAULT_BRANDING.button_background, "#0A1130");
assert_eq!(DEFAULT_BRANDING.surface_style, SurfaceStyle::Elevated);
assert_eq!(DEFAULT_BRANDING.radius_badge, CornerRadius::Pill);
assert!(!DEFAULT_BRANDING.show_logo);
assert!(DEFAULT_BRANDING.show_powered_by);
assert!(DEFAULT_BRANDING.trust_badges.is_empty());
assert_eq!(DEFAULT_BRANDING.notices, *DEFAULT_NOTICES);
assert_eq!(DEFAULT_BRANDING_DARK.background, "#020617");
assert_eq!(DEFAULT_BRANDING_DARK.accent_text, "#60a5fa");
assert_eq!(
DEFAULT_BRANDING_DARK.surface_style,
SurfaceStyle::Flat,
"drop shadows don't read on dark surfaces"
);
assert!(DEFAULT_BRANDING_DARK.trust_badges.is_empty());
assert_eq!(DEFAULT_BRANDING_DARK.notices, *DEFAULT_NOTICES);
assert_eq!(
DEFAULT_BRANDING_DARK.total_label,
DEFAULT_BRANDING.total_label
);
assert_eq!(DEFAULT_BRANDING_DARK.layout, DEFAULT_BRANDING.layout);
assert_eq!(default_branding(), *DEFAULT_BRANDING);
assert_eq!(CheckoutBranding::default(), *DEFAULT_BRANDING);
assert_eq!(
clone_branding(&DEFAULT_BRANDING_DARK),
*DEFAULT_BRANDING_DARK
);
}
#[test]
fn branding_variables_cover_every_dp_token() {
let vars = branding_variables(&DEFAULT_BRANDING);
assert_eq!(vars.len(), 32);
let get = |k: &str| {
vars.iter()
.find(|(name, _)| *name == k)
.map(|(_, v)| v.clone())
.unwrap_or_else(|| panic!("missing {k}"))
};
assert_eq!(get("--dp-primary"), "#1E4FEB");
assert_eq!(get("--dp-bg"), "#f8fafc");
assert_eq!(get("--dp-btn-fg"), "#ffffff");
assert_eq!(get("--dp-radius-badge"), "999px");
assert_eq!(get("--dp-radius-surface"), "12px");
assert_eq!(get("--dp-heading-weight"), "600");
assert_eq!(get("--dp-pad-surface"), "1.5rem");
assert_eq!(get("--dp-gap-vertical"), "1rem");
assert_eq!(get("--dp-input-pad"), "0.625rem 0.75rem");
assert_eq!(get("--dp-button-pad"), "0.875rem 1.25rem");
assert_eq!(get("--dp-shadow"), shadow_for(SurfaceStyle::Elevated));
assert_eq!(
get("--dp-surface-border"),
"1px solid transparent",
"only the outlined style paints a border"
);
assert_eq!(vars[0].0, "--dp-primary", "order matches the TS writer");
assert_eq!(get("--dp-surcharge"), "#b45309");
assert_eq!(get("--dp-discount"), "#047857");
assert_eq!(get("--dp-surcharge-ink"), "#ffffff");
assert_eq!(get("--dp-discount-ink"), "#ffffff");
assert_eq!(get("--dp-surcharge-size"), "0.6875rem");
assert_eq!(get("--dp-surcharge-pad"), "1px 6px");
assert_eq!(get("--dp-surcharge-radius"), "999px");
assert_eq!(get("--dp-surcharge-weight"), "600");
assert_eq!(get("--dp-surcharge-border-width"), "1px");
assert_eq!(get("--dp-surcharge-border-style"), "solid");
}
#[test]
fn the_surcharge_ink_follows_the_colour_it_is_written_on() {
let mut pale = default_branding();
pale.surcharge_color = "#fbbf24".to_string();
pale.discount_color = "#34d399".to_string();
let vars = branding_variables(&pale);
let get = |k: &str| {
vars.iter()
.find(|(name, _)| *name == k)
.map(|(_, v)| v.clone())
.unwrap_or_else(|| panic!("missing {k}"))
};
assert_eq!(get("--dp-surcharge-ink"), "#000000");
assert_eq!(get("--dp-discount-ink"), "#000000");
assert_eq!(readable_ink_on("#b45309"), "#ffffff");
assert_eq!(readable_ink_on("not-a-colour"), "#ffffff");
}
#[test]
fn outline_never_publishes_a_zero_border_width() {
let mut outlined = default_branding();
outlined.surcharge_style = SurchargeStyle::Outline;
outlined.surcharge_border_width = SurchargeBorderWidth::None;
let vars = branding_variables(&outlined);
let width = vars
.iter()
.find(|(name, _)| *name == "--dp-surcharge-border-width")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(width, "1px");
let mut badged = default_branding();
badged.surcharge_style = SurchargeStyle::Badge;
badged.surcharge_border_width = SurchargeBorderWidth::None;
let vars = branding_variables(&badged);
let width = vars
.iter()
.find(|(name, _)| *name == "--dp-surcharge-border-width")
.map(|(_, v)| v.clone())
.unwrap();
assert_eq!(width, "0px");
}
#[test]
fn an_empty_airwallex_preset_stays_unchosen_through_a_round_trip() {
let encoded = encode_branding_with_base(&default_branding(), None);
let bag = encoded["sdk_ui_rules"]["branding"].clone();
assert_eq!(bag["airwallexCardPreset"], "");
let decoded = decode_branding(Some(&BrandingSource {
sdk_ui_rules: Some(serde_json::from_value(bag).unwrap()),
..BrandingSource::default()
}));
assert_eq!(decoded.airwallex_card_preset, None);
assert_eq!(
resolve_airwallex_card_preset(None, Some("single_row")),
AirwallexCardPreset::SingleRow
);
assert_eq!(
resolve_airwallex_card_preset(None, None),
AirwallexCardPreset::SplitFieldsLabelled
);
}
#[test]
fn sections_sort_by_number_then_by_catalogue_order() {
let mut order = default_method_section_order();
order.insert("wallet".to_string(), 10);
let mut ids = vec!["crypto", "wallet", "card", "made_up"];
ids.sort_by(|a, b| compare_sections(a, b, &order));
assert_eq!(ids, vec!["card", "wallet", "crypto", "made_up"]);
}
#[test]
fn an_overlong_section_caption_is_truncated_not_dropped() {
let long = "a".repeat(MAX_SECTION_LABEL_LENGTH + 1);
let raw = format!(r#"{{"card":{{"en":"{long}","de":" "}}}}"#);
let decoded = decode_method_section_labels(Some(&raw));
let card = decoded.get("card").expect("the section survives");
assert_eq!(card["en"].chars().count(), MAX_SECTION_LABEL_LENGTH);
assert_eq!(card["en"], "a".repeat(MAX_SECTION_LABEL_LENGTH));
assert!(!card.contains_key("de"));
let re_decoded =
decode_method_section_labels(Some(&encode_method_section_labels(&decoded)));
assert_eq!(re_decoded, decoded);
let blanks = decode_method_section_labels(Some(r#"{"card":{"en":" "}}"#));
assert!(blanks.is_empty());
}
#[test]
fn a_section_caption_resolves_through_its_locales() {
let mut labels = MethodSectionLabels::new();
labels.insert(
"card".to_string(),
BTreeMap::from([("de".to_string(), "Karte".to_string())]),
);
assert_eq!(section_label("card", "de-AT", &labels, None), "Karte");
assert_eq!(section_label("card", "en", &labels, None), "Karte");
assert_eq!(
section_label("wallet", "en", &labels, Some("Wallets")),
"Wallets"
);
assert_eq!(section_label("wallet", "en", &labels, None), "wallet");
assert_eq!(section_label("card_redirect", "de", &labels, None), "Karte");
}
#[test]
fn outlined_surfaces_get_a_real_border() {
let b = CheckoutBranding {
surface_style: SurfaceStyle::Outlined,
border: "#ff0000".into(),
..default_branding()
};
let vars = branding_variables(&b);
let border = vars
.iter()
.find(|(k, _)| *k == "--dp-surface-border")
.map(|(_, v)| v.as_str())
.unwrap();
assert_eq!(border, "1px solid #ff0000");
assert_eq!(
vars.iter()
.find(|(k, _)| *k == "--dp-shadow")
.map(|(_, v)| v.as_str()),
Some("none")
);
}
#[test]
fn branding_variables_css_renders_a_root_rule() {
let css = branding_variables_css(&DEFAULT_BRANDING);
assert!(css.starts_with(":root{--dp-primary:#1E4FEB;"), "{css}");
assert!(
css.ends_with("--dp-surface-border:1px solid transparent;}"),
"{css}"
);
}
#[test]
fn card_form_and_cancel_link_defaults_reproduce_the_previous_drawing() {
let b = &*DEFAULT_BRANDING;
assert!(b.cancel_link_enabled);
assert_eq!(b.cancel_link_position, CancelLinkPosition::Top);
assert_eq!(b.cancel_link_style, CancelLinkStyle::Link);
assert_eq!(b.stripe_theme, StripeTheme::Auto);
assert_eq!(b.stripe_inputs, StripeInputStyle::Spaced);
assert_eq!(b.stripe_labels, StripeLabelPlacement::Above);
assert_eq!(b.stripe_spacing, StripeSpacing::Comfortable);
assert_eq!(b.stripe_field_weight, CardFieldWeight::Medium);
assert_eq!(b.stripe_focus_ring, CardFocusRing::Strong);
assert!(!b.stripe_disable_animations);
assert_eq!(b.paypal_card_layout, PaypalCardLayout::Split);
assert_eq!(b.paypal_field_weight, CardFieldWeight::Regular);
assert_eq!(b.mollie_focus_ring, CardFocusRing::Strong);
assert_eq!(b.epayouts_label_style, PaypalLabelStyle::Above);
assert_eq!(b.nomupay_form_style, NomupayFormStyle::Plain);
assert!(b.nomupay_show_labels && b.nomupay_show_placeholders);
assert!(!b.nomupay_show_cvv_hint);
assert_eq!(b.nomupay_focus_ring, CardFocusRing::None);
assert_eq!(b.nomupay_apple_pay_button_type, ApplePayButtonType::Pay);
assert_eq!(
b.nomupay_google_pay_button_color,
GooglePayButtonColor::Auto
);
assert_eq!(b.micropayment_field_weight, CardFieldWeight::Regular);
assert_eq!(b.whop_card_preset, WhopCardPreset::CardStacked);
assert_eq!(b.whop_accent_color, WhopAccentColor::Auto);
assert_eq!(b.whop_radius, WhopRadius::Checkout);
assert_eq!(b.whop_shadow, WhopShadow::Soft);
assert!(b.whop_method_icons);
assert_eq!(b.whop_selection, WhopSelection::RadioTint);
assert_eq!(decode_branding(Some(&source_with(json!({})))), *b);
}
#[test]
fn decode_branding_reads_the_card_form_and_cancel_link_keys() {
let b = decode_branding(Some(&source_with(json!({
"cancelLinkEnabled": "false",
"cancelLinkPosition": "bottom",
"cancelLinkStyle": "button",
"stripeTheme": "night",
"stripeInputs": "condensed",
"stripeLabels": "floating",
"stripeSpacing": "spacious",
"stripeFieldFontSize": "lg",
"stripeDisableAnimations": "true",
"paypalCardLayout": "stacked",
"paypalLabelStyle": "none",
"mollieFieldChrome": "filled",
"micropaymentFocusRing": "subtle",
"nomupayFormStyle": "card",
"nomupayShowLabels": "false",
"nomupayApplePayButtonStyle": "white-outline",
"nomupayApplePayButtonType": "add-money",
"nomupayGooglePayButtonColor": "default",
"nomupayGooglePayButtonType": "checkout",
"whopCardPreset": "tiles",
"whopAccentColor": "crimson",
"whopGrayColor": "sand",
"whopBillingDetails": "full",
"whopSeparated": "true",
"whopEmailLabel": "floating",
"whopRadius": "large",
"whopShadow": "none",
"whopMethodIcons": "false",
"whopSelection": "tint",
"stripeTheme_typo": "flat",
"whopSelection_unknown": "x",
}))));
assert!(!b.cancel_link_enabled);
assert_eq!(b.cancel_link_position, CancelLinkPosition::Bottom);
assert_eq!(b.cancel_link_style, CancelLinkStyle::Button);
assert_eq!(b.stripe_theme, StripeTheme::Night);
assert_eq!(b.stripe_inputs, StripeInputStyle::Condensed);
assert_eq!(b.stripe_labels, StripeLabelPlacement::Floating);
assert_eq!(b.stripe_spacing, StripeSpacing::Spacious);
assert_eq!(b.stripe_field_font_size, CardFieldFontSize::Lg);
assert!(b.stripe_disable_animations);
assert_eq!(b.paypal_card_layout, PaypalCardLayout::Stacked);
assert_eq!(b.paypal_label_style, PaypalLabelStyle::None);
assert_eq!(b.mollie_field_chrome, CardFieldChrome::Filled);
assert_eq!(b.micropayment_focus_ring, CardFocusRing::Subtle);
assert_eq!(b.nomupay_form_style, NomupayFormStyle::Card);
assert!(!b.nomupay_show_labels);
assert_eq!(
b.nomupay_apple_pay_button_style,
ApplePayButtonStyle::WhiteOutline
);
assert_eq!(
b.nomupay_apple_pay_button_type,
ApplePayButtonType::AddMoney
);
assert_eq!(
b.nomupay_google_pay_button_color,
GooglePayButtonColor::Default
);
assert_eq!(
b.nomupay_google_pay_button_type,
GooglePayButtonType::Checkout
);
assert_eq!(b.whop_card_preset, WhopCardPreset::Tiles);
assert_eq!(b.whop_accent_color, WhopAccentColor::Crimson);
assert_eq!(b.whop_gray_color, WhopGrayColor::Sand);
assert_eq!(b.whop_billing_details, WhopBillingDetails::Full);
assert!(b.whop_separated);
assert_eq!(b.whop_email_label, WhopEmailLabel::Floating);
assert_eq!(b.whop_radius, WhopRadius::Large);
assert_eq!(b.whop_shadow, WhopShadow::None);
assert!(!b.whop_method_icons);
assert_eq!(b.whop_selection, WhopSelection::Tint);
let b = decode_branding(Some(&source_with(json!({
"stripeTheme": "neon",
"whopRadius": "pill",
}))));
assert_eq!(b.stripe_theme, StripeTheme::Auto);
assert_eq!(b.whop_radius, WhopRadius::Checkout);
}
#[test]
fn epayouts_card_keys_fall_back_to_the_paypal_values() {
let paypal_only = json!({
"paypalCardLayout": "stacked",
"paypalLabelStyle": "none",
"paypalFieldChrome": "underline",
"paypalFieldFontSize": "sm",
"paypalFieldWeight": "semibold",
"paypalFocusRing": "subtle",
"paypalValidTint": "true",
});
let b = decode_branding(Some(&source_with(paypal_only.clone())));
assert_eq!(b.epayouts_card_layout, PaypalCardLayout::Stacked);
assert_eq!(b.epayouts_label_style, PaypalLabelStyle::None);
assert_eq!(b.epayouts_field_chrome, CardFieldChrome::Underline);
assert_eq!(b.epayouts_field_font_size, CardFieldFontSize::Sm);
assert_eq!(b.epayouts_field_weight, CardFieldWeight::Semibold);
assert_eq!(b.epayouts_focus_ring, CardFocusRing::Subtle);
assert!(b.epayouts_valid_tint);
let imported = parse_imported_branding(&paypal_only);
assert_eq!(imported.epayouts_card_layout, PaypalCardLayout::Stacked);
assert!(imported.epayouts_valid_tint);
let mut own = paypal_only;
own["epayoutsCardLayout"] = json!("split");
own["epayoutsValidTint"] = json!("false");
let b = decode_branding(Some(&source_with(own)));
assert_eq!(b.epayouts_card_layout, PaypalCardLayout::Split);
assert!(!b.epayouts_valid_tint);
assert_eq!(b.paypal_card_layout, PaypalCardLayout::Stacked);
}
#[test]
fn encode_branding_writes_the_new_keys_and_round_trips() {
let mut b = default_branding();
b.cancel_link_style = CancelLinkStyle::Button;
b.stripe_theme = StripeTheme::Flat;
b.paypal_valid_tint = true;
b.epayouts_card_layout = PaypalCardLayout::Stacked;
b.nomupay_apple_pay_button_type = ApplePayButtonType::TopUp;
b.whop_accent_color = WhopAccentColor::Jade;
b.whop_selection = WhopSelection::Radio;
b.notices = vec![
CheckoutNotice::new(
"ship",
NoticeSection::Payment,
NoticeIcon::Truck,
"Free shipping",
)
.translation("de", "Kostenloser Versand"),
];
let e = encode_branding(&b);
let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
assert_eq!(bag["cancelLinkEnabled"], "true");
assert_eq!(bag["cancelLinkStyle"], "button");
assert_eq!(bag["stripeTheme"], "flat");
assert_eq!(bag["paypalValidTint"], "true");
assert_eq!(bag["epayoutsCardLayout"], "stacked");
assert_eq!(bag["nomupayApplePayButtonType"], "top-up");
assert_eq!(bag["whopAccentColor"], "jade");
assert_eq!(bag["whopSelection"], "radio");
assert_eq!(
bag["notices"],
r#"[{"id":"ship","section":"payment","icon":"truck","label":"Free shipping","labelTranslations":{"de":"Kostenloser Versand"}}]"#
);
assert!(
!bag.contains_key("trustBadges"),
"an empty badge list is not written"
);
let source: BrandingSource =
serde_json::from_value(serde_json::to_value(&e).unwrap()).unwrap();
assert_eq!(decode_branding(Some(&source)), b);
let export = build_branding_export_at(&b, 0);
let raw = serde_json::to_value(&export).unwrap();
assert_eq!(raw["branding"]["whopAccentColor"], "jade");
assert_eq!(parse_imported_branding(&raw), b);
}
#[test]
fn removing_every_notice_survives_a_save() {
let mut b = default_branding();
b.notices.clear();
let bag = encode_branding(&b).sdk_ui_rules[BRANDING_GROUP_KEY].clone();
assert_eq!(bag["notices"], "[]");
let source = source_with(serde_json::to_value(&bag).unwrap());
let decoded = decode_branding(Some(&source));
assert!(decoded.notices.is_empty());
assert!(decoded.trust_badges.is_empty());
}
#[test]
fn a_bom_only_notice_takes_no_section_slot() {
let raw = json!([
{"section": "summary", "label": "\u{FEFF}"},
{"section": "summary", "label": "One"},
{"section": "summary", "label": "Two"},
{"section": "summary", "label": "Three"},
]);
let notices = parse_notices_loose(Some(&raw)).unwrap();
let labels: Vec<&str> = notices.iter().map(|n| n.label.as_str()).collect();
assert_eq!(labels, ["One", "Two", "Three"]);
}
#[test]
fn a_bom_only_translation_is_dropped() {
let raw = json!([{
"section": "payment",
"label": "Secure",
"labelTranslations": {"de": "\u{FEFF}", "fr": "Sécurisé"}
}]);
let mut notices = parse_notices_loose(Some(&raw)).unwrap();
assert_eq!(notices[0].label_translations.len(), 1);
assert!(notices[0].label_translations.contains_key("fr"));
notices[0]
.label_translations
.insert("de".to_string(), "\u{FEFF}".to_string());
let encoded: Value = serde_json::from_str(&encode_notices(¬ices)).unwrap();
assert!(encoded[0]["labelTranslations"].get("de").is_none());
assert_eq!(encoded[0]["labelTranslations"]["fr"], "Sécurisé");
}
#[test]
fn a_nel_surrounded_label_is_not_trimmed() {
assert_eq!(js_trim("\u{0085}Fast\u{0085}"), "\u{0085}Fast\u{0085}");
assert_eq!(js_trim("\u{FEFF} Fast\u{3000}"), "Fast");
let raw = json!([
{"section": "summary", "label": "\u{0085}"},
{"section": "summary", "label": "\u{0085}Fast\u{0085}"},
]);
let notices = parse_notices_loose(Some(&raw)).unwrap();
assert_eq!(
notices.len(),
2,
"a NEL-only label is not blank to JavaScript"
);
let shown = shown_notices(¬ices, NoticeSection::Summary, None);
assert_eq!(shown[1].text, "\u{0085}Fast\u{0085}");
}
#[test]
fn decode_notices_normalizes_and_caps() {
let long = "x".repeat(NOTICE_LABEL_MAX_LENGTH + 5);
let raw = json!([
{"id": "a b!", "section": "summary", "icon": "star", "label": long},
{"id": "ab", "section": "summary", "icon": "nope", "label": "Dup id"},
{"section": "nowhere", "label": "Unknown section"},
{"section": "summary", "label": "Fourth, dropped"},
{"section": "payment", "label": " ", "labelTranslations": {"de": "Nur Deutsch", "fr": " "}},
{"section": "payment", "label": "", "labelTranslations": {}},
"not-an-object",
])
.to_string();
let notices = decode_notices(Some(&raw)).unwrap();
assert_eq!(notices.len(), 4);
assert_eq!(notices[0].id, "ab", "cleaned to [A-Za-z0-9_-]");
assert_eq!(notices[0].icon, NoticeIcon::Star);
assert_eq!(notices[0].label.chars().count(), NOTICE_LABEL_MAX_LENGTH);
assert_eq!(notices[1].id, "notice-2", "a repeated id is replaced");
assert_eq!(notices[1].icon, NOTICE_ICON_FALLBACK);
assert_eq!(notices[2].section, NoticeSection::Summary);
assert_eq!(notices[2].id, "notice-3");
assert_eq!(notices[3].section, NoticeSection::Payment);
assert_eq!(
notices[3].label_translations.len(),
1,
"blank override dropped"
);
assert_eq!(notice_text(¬ices[3], Some("de-AT")), "Nur Deutsch");
assert!(notice_text(¬ices[3], Some("en")).trim().is_empty());
let shown = shown_notices(¬ices, NoticeSection::Payment, Some("en"));
assert!(shown.is_empty(), "no text in this locale, nothing drawn");
assert_eq!(notices_in(¬ices, NoticeSection::Summary).len(), 3);
assert_eq!(decode_notices(None), None);
assert_eq!(decode_notices(Some("{}")), None, "not an array");
assert_eq!(decode_notices(Some("broken")), None);
assert_eq!(decode_notices(Some("[]")), Some(Vec::new()));
assert_eq!(
parse_notices_loose(Some(&json!([{"label": "Inline"}])))
.unwrap()
.len(),
1
);
}
#[test]
fn stock_badges_migrate_to_notices_and_configured_ones_stay() {
let migrated = resolve_notices_and_badges(Some(DEFAULT_BADGES_DARK.clone()), None);
assert!(migrated.trust_badges.is_empty());
assert_eq!(migrated.notices, *DEFAULT_NOTICES);
let tinted = vec![
TrustBadge::new("secure", "Secure", "#1e4feb", "#edf1fd").border_color("#bccaf9"),
TrustBadge::new("ssl", "256-bit SSL", "#1e4feb", "#edf1fd").border_color("#bccaf9"),
];
assert!(is_default_badge_set(&tinted));
let mut edited = DEFAULT_BADGES.clone();
edited[0].label = "Safe".to_string();
assert!(!is_default_badge_set(&edited));
let kept = resolve_notices_and_badges(Some(edited.clone()), None);
assert_eq!(kept.trust_badges, edited);
assert!(kept.notices.is_empty());
let mut recoloured = DEFAULT_BADGES.clone();
recoloured[1].text_color = "#ff0000".to_string();
assert!(!is_default_badge_set(&recoloured));
assert!(!is_default_badge_set(&[]));
let decided = resolve_notices_and_badges(Some(DEFAULT_BADGES.clone()), Some(Vec::new()));
assert_eq!(decided.trust_badges, *DEFAULT_BADGES);
assert!(decided.notices.is_empty());
}
#[test]
fn enum_wire_values_survive_serde() {
assert_eq!(
serde_json::to_string(&FontFamily::DmSans).unwrap(),
"\"dm-sans\""
);
assert_eq!(
serde_json::to_string(&PaymentLayout::SpacedAccordion).unwrap(),
"\"spaced_accordion\""
);
assert_eq!(
serde_json::from_str::<FontFamily>("\"jetbrains-mono\"").unwrap(),
FontFamily::JetbrainsMono
);
assert!(serde_json::from_str::<FontFamily>("\"comic-sans\"").is_err());
assert_eq!(NonPillRadius::from_wire("pill"), None);
assert_eq!(CornerRadius::from_wire("pill"), Some(CornerRadius::Pill));
assert_eq!(
CornerRadius::from(NonPillRadius::Large),
CornerRadius::Large
);
assert_eq!(LogoShape::Circle.to_string(), "circle");
}
}