use std::{
cell::RefCell,
collections::HashMap,
rc::Rc,
sync::{Mutex, OnceLock},
time::{SystemTime, UNIX_EPOCH},
};
use arc_motion::{arc_spring, is_reduced_motion, motion_now};
use arc_tokens::{ActiveArcTheme as _, Radii, Shadows, Spacing, SpringSpec, Typography};
use gpui_kit::{
AnyElement, App, Bounds, ElementId, FocusHandle, Hsla, IntoElement, KeyDownEvent, MouseButton,
ParentElement, PathBuilder, RenderOnce, Role, SharedString, Styled, Window, assets::IconName,
base::StyledExt as _, canvas, div, point, prelude::*, px, svg,
};
use crate::{
actions::button::{Button, ButtonSize, ButtonVariant},
inputs::switch::Switch,
};
pub const COOKIE_CONSENT_BAR_MAX_W: f32 = 660.0;
pub const COOKIE_CONSENT_PANEL_MAX_W: f32 = 420.0;
pub const COOKIE_CONSENT_CHIP_SIZE: f32 = 44.0;
pub type CookieConsentValue = HashMap<SharedString, bool>;
type ConsentChangeCallback =
Rc<dyn Fn(&Option<CookieConsentValue>, CookieConsentAction, &mut Window, &mut App)>;
type PreferencesOpenCallback = Rc<dyn Fn(&bool, &mut Window, &mut App)>;
type PolicyClickCallback = Rc<dyn Fn(&mut Window, &mut App)>;
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum CookieConsentAction {
AcceptAll,
RejectAll,
Save,
Reset,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum CookieConsentMode {
Bar,
Panel,
Chip,
}
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, Hash)]
pub enum CookieConsentPosition {
#[default]
Bottom,
BottomLeft,
BottomRight,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub enum CookieConsentSide {
Left,
Right,
Center,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct CookieCategory {
pub id: SharedString,
pub label: SharedString,
pub description: Option<SharedString>,
pub required: bool,
pub default_enabled: bool,
}
impl CookieCategory {
pub fn new(id: impl Into<SharedString>, label: impl Into<SharedString>) -> Self {
Self {
id: id.into(),
label: label.into(),
description: None,
required: false,
default_enabled: false,
}
}
pub fn description(mut self, description: impl Into<SharedString>) -> Self {
self.description = Some(description.into());
self
}
pub fn required(mut self, required: bool) -> Self {
self.required = required;
self
}
pub fn default_enabled(mut self, default_enabled: bool) -> Self {
self.default_enabled = default_enabled;
self
}
}
pub fn default_cookie_categories() -> Vec<CookieCategory> {
vec![
CookieCategory::new("necessary", "Strictly necessary")
.description(
"Sign-in, security, and core session state. The app cannot work without these.",
)
.required(true),
CookieCategory::new("preferences", "Preferences")
.description("Remember your language, region, and display settings."),
CookieCategory::new("analytics", "Analytics")
.description("Count visits and see which views help, only in aggregate."),
CookieCategory::new("marketing", "Marketing")
.description("Measure campaigns and show relevant announcements."),
]
}
#[derive(Clone, Debug, PartialEq)]
pub struct StoredCookieConsent {
pub value: CookieConsentValue,
pub version: SharedString,
pub updated_at_epoch_secs: f64,
}
fn consent_storage() -> &'static Mutex<HashMap<String, StoredCookieConsent>> {
static STORAGE: OnceLock<Mutex<HashMap<String, StoredCookieConsent>>> = OnceLock::new();
STORAGE.get_or_init(|| Mutex::new(HashMap::new()))
}
pub fn read_cookie_consent(storage_key: &str, version: &str) -> Option<StoredCookieConsent> {
consent_storage()
.lock()
.ok()
.and_then(|map| map.get(storage_key).cloned())
.filter(|entry| entry.version.as_ref() == version)
}
pub fn write_cookie_consent(storage_key: &str, stored: Option<StoredCookieConsent>) {
if let Ok(mut map) = consent_storage().lock() {
match stored {
Some(entry) => {
map.insert(storage_key.to_string(), entry);
}
None => {
map.remove(storage_key);
}
}
}
}
pub fn clear_cookie_consent(storage_key: &str) {
write_cookie_consent(storage_key, None);
}
pub fn cookie_consent_baseline(
categories: &[CookieCategory],
saved: Option<&CookieConsentValue>,
) -> CookieConsentValue {
categories
.iter()
.map(|cat| {
let allowed = if cat.required {
true
} else if let Some(v) = saved.and_then(|m| m.get(&cat.id)) {
*v
} else {
cat.default_enabled
};
(cat.id.clone(), allowed)
})
.collect()
}
pub fn cookie_consent_surface_metrics(
mode: CookieConsentMode,
container_width: f32,
position: CookieConsentPosition,
reopen_side: Option<CookieConsentSide>,
decided: bool,
show_reopen_button: bool,
) -> (f32, f32, CookieConsentSide) {
let align = match position {
CookieConsentPosition::BottomLeft => CookieConsentSide::Left,
CookieConsentPosition::BottomRight => CookieConsentSide::Right,
CookieConsentPosition::Bottom => CookieConsentSide::Center,
};
let chip_side = reopen_side.unwrap_or(if align == CookieConsentSide::Right {
CookieConsentSide::Right
} else {
CookieConsentSide::Left
});
let panel_side = if decided && show_reopen_button {
chip_side
} else {
align
};
match mode {
CookieConsentMode::Bar => (
container_width.clamp(260.0, COOKIE_CONSENT_BAR_MAX_W),
22.0,
align,
),
CookieConsentMode::Panel => (
container_width.clamp(260.0, COOKIE_CONSENT_PANEL_MAX_W),
26.0,
panel_side,
),
CookieConsentMode::Chip => (
COOKIE_CONSENT_CHIP_SIZE,
COOKIE_CONSENT_CHIP_SIZE * 0.5,
chip_side,
),
}
}
#[derive(Clone, Debug)]
pub struct CookieConsentLabels {
pub message: SharedString,
pub customize: SharedString,
pub accept_all: SharedString,
pub reject_all: SharedString,
pub save: SharedString,
pub preferences_title: SharedString,
pub preferences_description: SharedString,
pub always_on: SharedString,
pub policy_label: Option<SharedString>,
}
impl Default for CookieConsentLabels {
fn default() -> Self {
Self {
message: "We use essential cookies to run this app. With your OK, we’d also use optional ones to remember settings and learn what helps.".into(),
customize: "Customize".into(),
accept_all: "Accept all".into(),
reject_all: "Reject all".into(),
save: "Save choices".into(),
preferences_title: "Cookie preferences".into(),
preferences_description: "Choose which optional cookies we can use. You can change this any time.".into(),
always_on: "Always on".into(),
policy_label: None,
}
}
}
#[derive(Clone)]
struct ConsentInternalState {
consent: Option<CookieConsentValue>,
panel_open: bool,
draft: CookieConsentValue,
last_mode: Option<CookieConsentMode>,
mode_changed_at: f64,
last_area: f32,
measured_bar_h: Rc<RefCell<f32>>,
measured_panel_h: Rc<RefCell<f32>>,
focus_handle: FocusHandle,
}
fn paint_cookie_icon(bounds: Bounds<gpui_kit::Pixels>, color: Hsla, window: &mut Window) {
let cx = bounds.origin.x + bounds.size.width * 0.5;
let cy = bounds.origin.y + bounds.size.height * 0.5;
let scale = (bounds.size.width / px(24.0)).min(bounds.size.height / px(24.0));
let stroke = px(1.85 * scale);
let r = 9.2 * scale;
let mut ring = PathBuilder::stroke(stroke);
let steps = 28;
let start_deg = 12.0_f32;
let end_deg = 278.0_f32;
for i in 0..=steps {
let deg = start_deg + (end_deg - start_deg) * (i as f32 / steps as f32);
let rad = deg.to_radians();
let p = point(cx + px(r * rad.cos()), cy + px(r * rad.sin()));
if i == 0 {
ring.move_to(p);
} else {
ring.line_to(p);
}
}
ring.line_to(point(cx + px(2.4 * scale), cy - px(5.6 * scale)));
ring.line_to(point(cx + px(5.4 * scale), cy - px(4.2 * scale)));
ring.line_to(point(cx + px(6.2 * scale), cy - px(1.2 * scale)));
ring.line_to(point(
cx + px(r * start_deg.to_radians().cos()),
cy + px(r * start_deg.to_radians().sin()),
));
if let Ok(path) = ring.build() {
window.paint_path(path, color);
}
let chips = [
(-3.2_f32, -2.8_f32),
(-4.0_f32, 2.6_f32),
(0.8_f32, 4.2_f32),
(2.8_f32, 0.8_f32),
];
let dot_r = 1.15 * scale;
for (dx, dy) in chips {
let dcx = cx + px(dx * scale);
let dcy = cy + px(dy * scale);
let mut dot = PathBuilder::fill();
for i in 0..10 {
let a = (i as f32 / 10.0) * std::f32::consts::TAU;
let p = point(dcx + px(dot_r * a.cos()), dcy + px(dot_r * a.sin()));
if i == 0 {
dot.move_to(p);
} else {
dot.line_to(p);
}
}
dot.close();
if let Ok(path) = dot.build() {
window.paint_path(path, color);
}
}
}
#[derive(IntoElement)]
pub struct CookieConsent {
id: ElementId,
categories: Vec<CookieCategory>,
value_override: Option<Option<CookieConsentValue>>,
default_value: Option<CookieConsentValue>,
storage_key: Option<SharedString>,
version: SharedString,
preferences_open_override: Option<bool>,
default_preferences_open: bool,
position: CookieConsentPosition,
show_reopen_button: bool,
reopen_side: Option<CookieConsentSide>,
labels: CookieConsentLabels,
container_width_hint: f32,
on_change: Option<ConsentChangeCallback>,
on_preferences_open_change: Option<PreferencesOpenCallback>,
on_policy_click: Option<PolicyClickCallback>,
}
impl CookieConsent {
pub fn new(id: impl Into<ElementId>) -> Self {
Self {
id: id.into(),
categories: default_cookie_categories(),
value_override: None,
default_value: None,
storage_key: None,
version: "1".into(),
preferences_open_override: None,
default_preferences_open: false,
position: CookieConsentPosition::Bottom,
show_reopen_button: true,
reopen_side: None,
labels: CookieConsentLabels::default(),
container_width_hint: 720.0,
on_change: None,
on_preferences_open_change: None,
on_policy_click: None,
}
}
pub fn categories(mut self, categories: impl IntoIterator<Item = CookieCategory>) -> Self {
self.categories = categories.into_iter().collect();
self
}
pub fn value(mut self, value: Option<CookieConsentValue>) -> Self {
self.value_override = Some(value);
self
}
pub fn default_value(mut self, value: Option<CookieConsentValue>) -> Self {
self.default_value = value;
self
}
pub fn storage_key(mut self, key: impl Into<SharedString>) -> Self {
self.storage_key = Some(key.into());
self
}
pub fn version(mut self, version: impl Into<SharedString>) -> Self {
self.version = version.into();
self
}
pub fn preferences_open(mut self, open: bool) -> Self {
self.preferences_open_override = Some(open);
self
}
pub fn default_preferences_open(mut self, open: bool) -> Self {
self.default_preferences_open = open;
self
}
pub fn position(mut self, position: CookieConsentPosition) -> Self {
self.position = position;
self
}
pub fn show_reopen_button(mut self, show: bool) -> Self {
self.show_reopen_button = show;
self
}
pub fn reopen_side(mut self, side: CookieConsentSide) -> Self {
self.reopen_side = Some(side);
self
}
pub fn labels(mut self, labels: CookieConsentLabels) -> Self {
self.labels = labels;
self
}
pub fn container_width_hint(mut self, width_px: f32) -> Self {
self.container_width_hint = width_px.max(280.0);
self
}
pub fn on_change(
mut self,
handler: impl Fn(&Option<CookieConsentValue>, CookieConsentAction, &mut Window, &mut App)
+ 'static,
) -> Self {
self.on_change = Some(Rc::new(handler));
self
}
pub fn on_preferences_open_change(
mut self,
handler: impl Fn(&bool, &mut Window, &mut App) + 'static,
) -> Self {
self.on_preferences_open_change = Some(Rc::new(handler));
self
}
pub fn on_policy_click(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
self.on_policy_click = Some(Rc::new(handler));
self
}
}
impl RenderOnce for CookieConsent {
fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
let (colors, theme_mode) = {
let theme = cx.arc_theme();
(theme.colors, theme.mode)
};
let reduced = is_reduced_motion(cx);
let now = motion_now(cx);
let seeded = if let Some(ref ext) = self.value_override {
ext.clone()
} else if let Some(ref sk) = self.storage_key {
read_cookie_consent(sk.as_ref(), self.version.as_ref())
.map(|s| s.value)
.or_else(|| self.default_value.clone())
} else {
self.default_value.clone()
};
let init_draft = cookie_consent_baseline(&self.categories, seeded.as_ref());
let init_panel = self.default_preferences_open;
let state_cell = window
.use_keyed_state((self.id.clone(), "cookie-consent-state"), cx, |_, cx| {
Rc::new(RefCell::new(ConsentInternalState {
consent: seeded.clone(),
panel_open: init_panel,
draft: init_draft,
last_mode: None,
mode_changed_at: now - 1.0,
last_area: COOKIE_CONSENT_BAR_MAX_W * 68.0,
measured_bar_h: Rc::new(RefCell::new(0.0)),
measured_panel_h: Rc::new(RefCell::new(0.0)),
focus_handle: cx.focus_handle(),
}))
})
.read(cx)
.clone();
{
let mut st = state_cell.borrow_mut();
if let Some(ref ext) = self.value_override
&& st.consent != *ext
{
st.consent = ext.clone();
st.draft = cookie_consent_baseline(&self.categories, st.consent.as_ref());
}
if let Some(ext_open) = self.preferences_open_override {
st.panel_open = ext_open;
}
}
let snapshot = state_cell.borrow().clone();
let decided = snapshot.consent.is_some();
let mode: Option<CookieConsentMode> = if snapshot.panel_open {
Some(CookieConsentMode::Panel)
} else if !decided {
Some(CookieConsentMode::Bar)
} else if self.show_reopen_button {
Some(CookieConsentMode::Chip)
} else {
None
};
let Some(active_mode) = mode else {
return div().into_any_element();
};
let mode_changed_at = {
let mut st = state_cell.borrow_mut();
if st.last_mode != Some(active_mode) {
if st.last_mode.is_some() {
st.mode_changed_at = now;
}
st.last_mode = Some(active_mode);
}
st.mode_changed_at
};
let (target_w, target_r, side) = cookie_consent_surface_metrics(
active_mode,
self.container_width_hint,
self.position,
self.reopen_side,
decided,
self.show_reopen_button,
);
let default_bar_h = if target_w < 560.0 { 114.0 } else { 72.0 };
let default_panel_h = 176.0 + self.categories.len() as f32 * 58.0;
let measured_bar_h = *snapshot.measured_bar_h.borrow();
let measured_panel_h = *snapshot.measured_panel_h.borrow();
let target_h = match active_mode {
CookieConsentMode::Bar => {
if measured_bar_h > 36.0 {
measured_bar_h
} else {
default_bar_h
}
}
CookieConsentMode::Panel => {
if measured_panel_h > 100.0 {
measured_panel_h
} else {
default_panel_h
}
}
CookieConsentMode::Chip => COOKIE_CONSENT_CHIP_SIZE,
};
let target_area = target_w * target_h;
let is_growing = {
let mut st = state_cell.borrow_mut();
let growing = target_area >= st.last_area;
st.last_area = target_area;
growing
};
let morph_spec = if is_growing {
SpringSpec::visual(0.46, 0.0)
} else {
SpringSpec::visual(0.38, 0.0)
};
let anim_w = if reduced {
target_w
} else {
arc_spring(
(self.id.clone(), "surface-w"),
target_w,
morph_spec,
window,
cx,
)
};
let anim_h = if reduced {
target_h
} else {
arc_spring(
(self.id.clone(), "surface-h"),
target_h,
morph_spec,
window,
cx,
)
};
let anim_r = if reduced {
target_r
} else {
arc_spring(
(self.id.clone(), "surface-r"),
target_r,
morph_spec,
window,
cx,
)
};
let face_t = if reduced {
1.0_f32
} else {
((now - mode_changed_at) / 0.24).clamp(0.0, 1.0) as f32
};
if !reduced && face_t < 1.0 {
window.request_animation_frame();
}
let face_alpha = (1.0 - (1.0 - face_t).powi(2)).clamp(0.0, 1.0);
let face_y = if reduced {
0.0_f32
} else {
(1.0 - face_alpha) * 6.0
};
let is_morphing_h = (anim_h - target_h).abs() > 1.0;
let make_commit = |action: CookieConsentAction| {
let state_c = state_cell.clone();
let cats = self.categories.clone();
let sk = self.storage_key.clone();
let ver = self.version.clone();
let on_change_cb = self.on_change.clone();
let on_pref_cb = self.on_preferences_open_change.clone();
move |window: &mut Window, cx: &mut App| {
let (next_val, closed_panel) = {
let mut st = state_c.borrow_mut();
let next: CookieConsentValue = match action {
CookieConsentAction::Save => st.draft.clone(),
CookieConsentAction::AcceptAll => {
cats.iter().map(|c| (c.id.clone(), true)).collect()
}
CookieConsentAction::RejectAll => {
cats.iter().map(|c| (c.id.clone(), c.required)).collect()
}
CookieConsentAction::Reset => HashMap::new(),
};
let val_opt = if action == CookieConsentAction::Reset {
None
} else {
Some(next.clone())
};
st.consent = val_opt.clone();
st.draft = cookie_consent_baseline(&cats, st.consent.as_ref());
let was_open = st.panel_open;
st.panel_open = false;
(val_opt, was_open)
};
if let Some(ref storage_key) = sk {
let now_secs = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs_f64())
.unwrap_or(0.0);
write_cookie_consent(
storage_key.as_ref(),
next_val.clone().map(|v| StoredCookieConsent {
value: v,
version: ver.clone(),
updated_at_epoch_secs: now_secs,
}),
);
}
if let Some(ref cb) = on_change_cb {
cb(&next_val, action, window, cx);
}
if closed_panel && let Some(ref cb) = on_pref_cb {
cb(&false, window, cx);
}
window.refresh();
}
};
let policy_el: Option<AnyElement> = self.labels.policy_label.clone().map(|pl| {
let on_policy = self.on_policy_click.clone();
div()
.id((self.id.clone(), "policy-link"))
.cursor_pointer()
.text_size(Typography::TEXT_SM)
.text_color(colors.foreground)
.underline()
.hover(move |s| s.opacity(0.75))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
if let Some(ref cb) = on_policy {
cb(window, cx);
}
})
.child(pl)
.into_any_element()
});
let bar_h_measure = snapshot.measured_bar_h.clone();
let panel_h_measure = snapshot.measured_panel_h.clone();
let face_content: AnyElement = match active_mode {
CookieConsentMode::Bar => {
let state_open = state_cell.clone();
let cats_open = self.categories.clone();
let on_pref_open = self.on_preferences_open_change.clone();
let commit_reject = make_commit(CookieConsentAction::RejectAll);
let commit_accept = make_commit(CookieConsentAction::AcceptAll);
let stacked = target_w < 560.0;
let message_block = div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_col()
.gap(px(2.0))
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child(div().w_full().child(self.labels.message.clone()))
.when_some(policy_el, |el, p| {
el.child(div().flex().items_center().child(p))
});
let actions_row = div()
.flex()
.items_center()
.when(stacked, |el| el.justify_end().w_full())
.gap(px(6.0))
.flex_shrink_0()
.child(
Button::new((self.id.clone(), "btn-customize"))
.label(self.labels.customize.clone())
.size(ButtonSize::Sm)
.variant(ButtonVariant::Ghost)
.on_click(move |_, window, cx| {
{
let mut st = state_open.borrow_mut();
st.draft =
cookie_consent_baseline(&cats_open, st.consent.as_ref());
st.panel_open = true;
}
if let Some(ref cb) = on_pref_open {
cb(&true, window, cx);
}
window.refresh();
}),
)
.child(
Button::new((self.id.clone(), "btn-bar-reject"))
.label(self.labels.reject_all.clone())
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.on_click(move |_, window, cx| commit_reject(window, cx)),
)
.child(
Button::new((self.id.clone(), "btn-bar-accept"))
.label(self.labels.accept_all.clone())
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.on_click(move |_, window, cx| commit_accept(window, cx)),
);
let bar_layout = if stacked {
div()
.w(px(target_w))
.max_w_full()
.pt(px(14.0))
.pb(px(10.0))
.px(px(16.0))
.flex()
.flex_col()
.gap(Spacing::S3)
.child(message_block)
.child(actions_row)
} else {
div()
.w(px(target_w))
.max_w_full()
.py(px(12.0))
.pl(px(18.0))
.pr(px(12.0))
.flex()
.items_center()
.justify_between()
.gap(Spacing::S4)
.child(message_block)
.child(actions_row)
};
bar_layout
.mt(px(face_y))
.opacity(face_alpha)
.on_children_prepainted(move |children_bounds, _, _| {
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for b in children_bounds {
min_y = min_y.min(f32::from(b.origin.y));
max_y = max_y.max(f32::from(b.origin.y + b.size.height));
}
if max_y > min_y {
*bar_h_measure.borrow_mut() = (max_y - min_y) + 26.0;
}
})
.into_any_element()
}
CookieConsentMode::Panel => {
let state_close = state_cell.clone();
let on_pref_close = self.on_preferences_open_change.clone();
let commit_reject = make_commit(CookieConsentAction::RejectAll);
let commit_accept = make_commit(CookieConsentAction::AcceptAll);
let commit_save = make_commit(CookieConsentAction::Save);
let mut category_rows: Vec<AnyElement> = Vec::with_capacity(self.categories.len());
for (idx, cat) in self.categories.iter().enumerate() {
let cat_id = cat.id.clone();
let checked = *snapshot.draft.get(&cat_id).unwrap_or(&cat.required);
let state_sw = state_cell.clone();
let cat_id_sw = cat_id.clone();
let right_ctrl: AnyElement = if cat.required {
div()
.flex_shrink_0()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(self.labels.always_on.clone())
.into_any_element()
} else {
Switch::new((self.id.clone(), format!("cat-switch-{cat_id}")))
.checked(checked)
.on_checked_change(move |next_checked: &bool, window, _| {
{
let mut st = state_sw.borrow_mut();
st.draft.insert(cat_id_sw.clone(), *next_checked);
}
window.refresh();
})
.into_any_element()
};
category_rows.push(
div()
.w_full()
.py(px(10.0))
.when(idx > 0, |el| {
el.border_t_1().border_color(colors.border_subtle)
})
.flex()
.items_center()
.justify_between()
.gap(Spacing::S4)
.child(
div()
.flex_1()
.min_w(px(0.0))
.flex()
.flex_col()
.gap(px(2.0))
.child(
div()
.text_size(Typography::TEXT_SM)
.font_medium()
.text_color(colors.foreground)
.child(cat.label.clone()),
)
.when_some(cat.description.clone(), |el, desc| {
el.child(
div()
.text_size(Typography::TEXT_XS)
.text_color(colors.text_muted)
.child(desc),
)
}),
)
.child(right_ctrl)
.into_any_element(),
);
}
div()
.w(px(target_w))
.max_w_full()
.p(px(18.0))
.mt(px(face_y))
.opacity(face_alpha)
.flex()
.flex_col()
.gap(Spacing::S3)
.child(
div()
.w_full()
.flex()
.items_center()
.justify_between()
.gap(Spacing::S3)
.child(
div()
.text_size(Typography::TEXT_BASE)
.font_medium()
.text_color(colors.foreground)
.child(self.labels.preferences_title.clone()),
)
.child(
div()
.id((self.id.clone(), "btn-panel-close"))
.w(px(32.0))
.h(px(32.0))
.rounded_full()
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(colors.surface_muted))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
{
let mut st = state_close.borrow_mut();
st.panel_open = false;
}
if let Some(ref cb) = on_pref_close {
cb(&false, window, cx);
}
window.refresh();
})
.child(
svg()
.path(IconName::Close.path())
.size(px(16.0))
.text_color(colors.text_secondary),
),
),
)
.child(
div()
.w_full()
.flex()
.flex_col()
.gap(px(2.0))
.text_size(Typography::TEXT_SM)
.text_color(colors.text_secondary)
.child(
div()
.w_full()
.child(self.labels.preferences_description.clone()),
)
.when_some(policy_el, |el, p| {
el.child(div().flex().items_center().child(p))
}),
)
.child(div().w_full().flex().flex_col().children(category_rows))
.child(
div()
.w_full()
.pt(Spacing::S3)
.border_t_1()
.border_color(colors.border_subtle)
.flex()
.items_center()
.justify_between()
.gap(px(6.0))
.child(
div()
.flex()
.items_center()
.gap(px(6.0))
.flex_shrink_0()
.child(
Button::new((self.id.clone(), "btn-panel-reject"))
.label(self.labels.reject_all.clone())
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.on_click(move |_, window, cx| {
commit_reject(window, cx)
}),
)
.child(
Button::new((self.id.clone(), "btn-panel-accept"))
.label(self.labels.accept_all.clone())
.size(ButtonSize::Sm)
.variant(ButtonVariant::Secondary)
.on_click(move |_, window, cx| {
commit_accept(window, cx)
}),
),
)
.child(
Button::new((self.id.clone(), "btn-panel-save"))
.label(self.labels.save.clone())
.size(ButtonSize::Sm)
.variant(ButtonVariant::Primary)
.on_click(move |_, window, cx| commit_save(window, cx)),
),
)
.on_children_prepainted(move |children_bounds, _, _| {
let mut min_y = f32::INFINITY;
let mut max_y = f32::NEG_INFINITY;
for b in children_bounds {
min_y = min_y.min(f32::from(b.origin.y));
max_y = max_y.max(f32::from(b.origin.y + b.size.height));
}
if max_y > min_y {
*panel_h_measure.borrow_mut() = (max_y - min_y) + 38.0;
}
})
.into_any_element()
}
CookieConsentMode::Chip => {
let state_reopen = state_cell.clone();
let cats_reopen = self.categories.clone();
let on_pref_reopen = self.on_preferences_open_change.clone();
let cookie_color = colors.foreground;
div()
.id((self.id.clone(), "btn-reopen-chip"))
.w(px(COOKIE_CONSENT_CHIP_SIZE))
.h(px(COOKIE_CONSENT_CHIP_SIZE))
.rounded_full()
.opacity(face_alpha)
.flex()
.items_center()
.justify_center()
.cursor_pointer()
.hover(move |s| s.bg(colors.surface_muted))
.on_mouse_down(MouseButton::Left, move |_, window, cx| {
{
let mut st = state_reopen.borrow_mut();
st.draft = cookie_consent_baseline(&cats_reopen, st.consent.as_ref());
st.panel_open = true;
}
if let Some(ref cb) = on_pref_reopen {
cb(&true, window, cx);
}
window.refresh();
})
.child(
div().w(px(20.0)).h(px(20.0)).child(
canvas(
move |_, _, _| {},
move |bounds, _, window, _| {
paint_cookie_icon(bounds, cookie_color, window);
},
)
.size_full(),
),
)
.into_any_element()
}
};
let key_state = state_cell.clone();
let on_pref_esc = self.on_preferences_open_change.clone();
let focus_handle = snapshot.focus_handle.clone();
let wrapper = div().w_full().flex().items_end();
let wrapper = match side {
CookieConsentSide::Left => wrapper.justify_start(),
CookieConsentSide::Right => wrapper.justify_end(),
CookieConsentSide::Center => wrapper.justify_center(),
};
let mut surface = div()
.id(self.id)
.role(Role::Dialog)
.track_focus(&focus_handle)
.w(px(anim_w))
.max_w_full()
.rounded(px(anim_r.max(Radii::CONTROL.into())))
.border_1()
.border_color(colors.border)
.bg(colors.surface_raised)
.text_color(colors.foreground)
.shadow(Shadows::floating(theme_mode))
.overflow_hidden()
.flex()
.items_end()
.justify_center()
.on_key_down(move |event: &KeyDownEvent, window, cx| {
if event.keystroke.key.as_str() == "escape" {
let closed = {
let mut st = key_state.borrow_mut();
if st.panel_open {
st.panel_open = false;
true
} else {
false
}
};
if closed {
if let Some(ref cb) = on_pref_esc {
cb(&false, window, cx);
}
window.refresh();
}
}
})
.child(face_content);
if is_morphing_h || active_mode == CookieConsentMode::Chip {
surface = surface.h(px(anim_h.max(COOKIE_CONSENT_CHIP_SIZE)));
}
wrapper.child(surface).into_any_element()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cookie_consent_baseline_and_storage_versioning() {
let cats = default_cookie_categories();
let base = cookie_consent_baseline(&cats, None);
assert_eq!(base.get("necessary"), Some(&true));
assert_eq!(base.get("preferences"), Some(&false));
assert_eq!(base.get("analytics"), Some(&false));
assert_eq!(base.get("marketing"), Some(&false));
let key = "test-cookie-consent-v1";
clear_cookie_consent(key);
assert!(read_cookie_consent(key, "1").is_none());
let mut custom = base.clone();
custom.insert("analytics".into(), true);
write_cookie_consent(
key,
Some(StoredCookieConsent {
value: custom.clone(),
version: "1".into(),
updated_at_epoch_secs: 100.0,
}),
);
assert_eq!(
read_cookie_consent(key, "1").and_then(|s| s.value.get("analytics").copied()),
Some(true)
);
assert!(read_cookie_consent(key, "2").is_none());
clear_cookie_consent(key);
}
#[test]
fn cookie_consent_surface_metrics_morph_dimensions() {
let (bar_w, bar_r, bar_side) = cookie_consent_surface_metrics(
CookieConsentMode::Bar,
900.0,
CookieConsentPosition::Bottom,
None,
false,
true,
);
assert_eq!(bar_w, COOKIE_CONSENT_BAR_MAX_W);
assert_eq!(bar_r, 22.0);
assert_eq!(bar_side, CookieConsentSide::Center);
let (panel_w, panel_r, panel_side) = cookie_consent_surface_metrics(
CookieConsentMode::Panel,
900.0,
CookieConsentPosition::Bottom,
None,
true,
true,
);
assert_eq!(panel_w, COOKIE_CONSENT_PANEL_MAX_W);
assert_eq!(panel_r, 26.0);
assert_eq!(panel_side, CookieConsentSide::Left);
let (chip_w, chip_r, chip_side) = cookie_consent_surface_metrics(
CookieConsentMode::Chip,
900.0,
CookieConsentPosition::BottomRight,
None,
true,
true,
);
assert_eq!(chip_w, COOKIE_CONSENT_CHIP_SIZE);
assert_eq!(chip_r, 22.0);
assert_eq!(chip_side, CookieConsentSide::Right);
}
}