Skip to content

Visual Studio Code, rebuilt in Rust

Rust
27.6 KB
Raw Blame
//! updateTitleBarEntry.ts and updateTooltip.ts: the title bar's update entry (`update.titleBar`, before the layout
//! controls as titlebarPart.ts places `MenuId.TitleBarUpdate`) and its tooltip, shown on hover, on a click of an
//! entry without an action, and by itself for an error.
// The disabled reminder (`DISABLED_REMINDER_PERIOD`) is not here: it is for InvalidConfiguration and RunningAsAdmin,
// reasons the port's update service never gives. The port has no chat, so no request is ever in progress.

use std::cell::Cell;
use std::rc::Rc;
use std::time::Duration;

use gpui::{
    AnyElement, Animation, AnimationExt, Bounds, ClickEvent, Context, Div, Keystroke, Pixels, Rgba, Size, Window, canvas, div, img, linear_color_stop, linear_gradient,
    prelude::*, px, relative,
};
use serde_json::{Value, json};

use super::Workbench;
use super::hover::{HoverContent, HoverOptions, text_width};
use crate::update::{DisablementReason, State, Update};

/// The tooltip's hover target id.
pub(super) const TOOLTIP: &str = "update-title-bar";
/// The entry's action bar.
pub(super) const TOOLBAR: &str = "title-update";
const WIDTH: f32 = 300.;
const PADDING: f32 = 6.;
const GAP: f32 = 12.;
const LINE: f32 = 19.;

#[derive(Default)]
pub struct UpdateTitleBar {
    /// The `updateTitleBar` context key.
    context: bool,
    /// The entry's bounds in the main window, where the tooltip points.
    bounds: Rc<Cell<Bounds<Pixels>>>,
    /// `trapFocus`: the tooltip's focused button, set when a click on the entry opened it.
    pub(super) focused_button: Option<usize>,
}

/// The entry's look: updateTitleBarEntry.css `.prominent`, `.update-disabled`, `.progress-indefinite` and
/// `.progress-percent`.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Look {
    Plain,
    Prominent,
    Disabled,
    Indefinite,
    Percent(f32),
}

impl Workbench {
    /// `UpdateTitleBarContribution.onStateChange`, after the update state changed. With `update.titleBar` off the
    /// context still follows the state, so turning the setting on shows the entry the state asks for.
    pub(super) fn update_title_bar_state_changed(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let actionable = is_actionable(&self.update_state);
        let tooltip_visible = self.update_tooltip_visible();
        if tooltip_visible || !window.is_window_active() {
            self.update_title_bar.context = tooltip_visible || actionable;
            return;
        }
        let show_tooltip = matches!(self.update_state, State::Idle { error: Some(_), .. }) && self.setting("update.titleBar") != json!(false);
        self.update_title_bar.context = show_tooltip
            || match &self.update_state {
                State::Downloading { explicit, .. } => *explicit,
                State::Restarting { .. } => true,
                state => is_actionable(state),
            };
        if show_tooltip {
            self.show_update_tooltip(false, window, cx);
        }
    }

    /// `UpdateTitleBarEditorVisibleContext`: the setting, the context, and neither Zen Mode nor a debug session.
    pub(super) fn update_title_bar_entry_visible(&self) -> bool {
        self.setting("update.titleBar") != json!(false) && self.update_title_bar.context && !self.zen_mode.active && self.debug.state() == crate::debug::session::State::Inactive
    }

    fn update_tooltip_visible(&self) -> bool {
        self.hovers.sticky_shown(TOOLTIP)
    }

    /// `UpdateTitleBarEntry.showTooltip`: the sticky tooltip below the entry, its buttons focused when `focus`.
    fn show_update_tooltip(&mut self, focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        self.update_title_bar.focused_button = focus.then_some(0);
        self.show_managed_hover(TOOLTIP, HoverContent::Update, HoverOptions::instant().anchored_right().sticky(), Bounds::default(), window, cx);
    }

    /// The target's `dispose` of a shown tooltip (`onUserDismissedTooltip`).
    pub(super) fn update_tooltip_dismissed(&mut self) {
        self.update_title_bar.focused_button = None;
        let detailed = matches!(self.update_state, State::CheckingForUpdates { .. } | State::Downloading { .. });
        if !is_actionable(&self.update_state) && !detailed {
            self.update_title_bar.context = false;
        }
    }

    /// The bounds the tooltip points at: the entry's, once it was laid out.
    pub(super) fn update_entry_bounds(&self) -> Option<Bounds<Pixels>> {
        Some(self.update_title_bar.bounds.get()).filter(|bounds| bounds.size.width > px(0.))
    }

    /// `UpdateTitleBarEntry.render` and `onStateChange`: the state's label, its look, and a click that runs the
    /// state's action or opens the tooltip.
    pub(super) fn update_title_bar_entry(&self, bar: &'static str, track_bounds: bool, cx: &mut Context<Self>) -> Option<Div> {
        if !self.update_title_bar_entry_visible() {
            return None;
        }
        let (label, look) = entry_label(&self.update_state);
        let prominent = look == Look::Prominent;
        let button = self.color("button.background");
        let button_hover = self.color("button.hoverBackground");
        let toolbar_hover = self.color("toolbar.hoverBackground");
        let progress = self.color("progressBar.background");
        let label_color = (look == Look::Disabled).then(|| self.color("disabledForeground"));
        let mut text = div().relative().text_size(px(12.)).when_some(label_color, |text, color| text.text_color(color)).child(label);
        match look {
            Look::Indefinite if !self.is_motion_reduced() => text = text.child(shimmer(progress)),
            Look::Indefinite => text = text.child(div().absolute().left_0().bottom(px(1.)).h(px(1.)).w_full()),
            Look::Percent(percent) => {
                let mut rest = progress;
                rest.a *= 0.25;
                text = text.child(
                    div().absolute().left_0().bottom(px(1.)).h(px(1.)).w_full().rounded(px(1.)).overflow_hidden().flex().child(div().h_full().w(relative(percent / 100.)).bg(progress)).child(div().h_full().flex_1().bg(rest)),
                );
            }
            _ => {}
        }
        let bounds = self.update_title_bar.bounds.clone();
        let entry = div()
            .id("update-indicator")
            .role(gpui::Role::Button)
            .aria_label(label)
            .relative()
            // titlebarpart.css: `right: 8px` on macOS, then `margin-right: var(--vscode-spacing-size40)`.
            .right(px(8.))
            .mr(px(4.))
            .h(px(22.))
            .px(px(8.))
            .flex()
            .items_center()
            .whitespace_nowrap()
            .rounded(px(4.))
            .border_1()
            .border_color(if prominent { button } else { gpui::transparent_black().into() })
            .when(prominent, |entry| entry.bg(button).text_color(self.color("button.foreground")).hover(move |entry| entry.bg(button_hover).border_color(button_hover)))
            .when(!prominent, |entry| entry.hover(move |entry| entry.bg(toolbar_hover)))
            .cursor_pointer()
            .child(text)
            .child(self.hover_target(TOOLTIP, HoverContent::Update, HoverOptions::instant().anchored_right()))
            .on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| workbench.run_update_title_bar_action(window, cx)));
        let entry = self.action_bar_item(bar, "update", entry, cx);
        // A new place redraws once more, so the tooltip shown with it points at the entry.
        let entry = entry.when(track_bounds, |entry| entry.child(
                canvas(
                    move |painted, window, cx| {
                        if bounds.replace(painted) != painted {
                            super::part_view::redraw_after_frame(window, cx);
                        }
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .size_full(),
            ));
        // titlebarPart.ts: `MenuId.TitleBarUpdate` is a toolbar of its own, one tab stop.
        Some(self.action_bar(bar, false, div().child(entry), cx))
    }

    /// updateTitleBarEntry.ts: `workbench.action.showHover` on the focused entry shows its tooltip focused
    /// (`focusTooltip`). True when the entry has the focus.
    pub(super) fn focus_update_tooltip(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
        if self.focused_action_bar(window) != Some(TOOLBAR) {
            return false;
        }
        self.show_update_tooltip(true, window, cx);
        true
    }

    /// `runAction`.
    fn run_update_title_bar_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let command = match self.update_state {
            State::AvailableForDownload { .. } => "update.downloadNow",
            State::Downloaded { .. } => "update.install",
            State::Ready { .. } => "update.restart",
            _ => return self.show_update_tooltip(true, window, cx),
        };
        self.execute_command(command, Vec::new(), window, cx);
    }

    /// The tooltip's keys while its buttons have the focus: Tab and Shift+Tab move it, Enter and Space press the
    /// button, Escape closes the tooltip.
    pub(super) fn update_tooltip_key(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) -> bool {
        let Some(focused) = self.update_title_bar.focused_button.filter(|_| self.update_tooltip_visible()) else { return false };
        let buttons = self.update_tooltip_buttons();
        match keystroke.key.as_str() {
            "tab" if !buttons.is_empty() => {
                let step = if keystroke.modifiers.shift { buttons.len() - 1 } else { 1 };
                self.update_title_bar.focused_button = Some((focused + step) % buttons.len());
                cx.notify();
            }
            "enter" | "space" => {
                if let Some((_, command, args)) = buttons.into_iter().nth(focused) {
                    self.run_update_tooltip_button(command, args, window, cx);
                }
            }
            "escape" => self.dismiss_hover(cx),
            _ => return false,
        }
        true
    }

    /// `runCommandAndClose`.
    fn run_update_tooltip_button(&mut self, command: &'static str, args: Vec<Value>, window: &mut Window, cx: &mut Context<Self>) {
        self.dismiss_hover(cx);
        self.execute_command(command, args, window, cx);
    }

    /// The button bar: Release Notes for the update's version, else the running one's, then the state's action.
    fn update_tooltip_buttons(&self) -> Vec<(&'static str, &'static str, Vec<Value>)> {
        let version = update_of(&self.update_state).map_or_else(crate::product::display_version, |update| update.product_version.clone());
        let mut buttons = Vec::new();
        if !version.is_empty() {
            buttons.push(("Release Notes", "update.showCurrentReleaseNotes", vec![json!(version)]));
        }
        if let Some((label, command)) = self.update_tooltip_action() {
            buttons.push((label, command, Vec::new()));
        }
        buttons
    }

    fn update_tooltip_action(&self) -> Option<(&'static str, &'static str)> {
        match self.update_state {
            State::AvailableForDownload { .. } => Some(("Download", "update.downloadNow")),
            State::Downloaded { .. } => Some(("Install", "update.install")),
            State::Ready { .. } if self.setting("update.mode") == json!("manual") => Some(("Restart", "update.restart")),
            _ => None,
        }
    }

    /// `UpdateTooltip.renderState` (updateTooltip.css) and its estimated size for the hover's placement; the hover
    /// takes the height the content lays out to.
    pub(super) fn update_tooltip(&self, window: &Window, cx: &mut Context<Self>) -> (Size<f32>, AnyElement) {
        let content = tooltip_content(&self.update_state, self.setting("update.mode").as_str().unwrap_or("default"));
        let foreground = self.color("foreground");
        let description = self.color("descriptionForeground");
        let mut height = 2. * PADDING + LINE;
        let mut tooltip = div()
            .w(px(WIDTH))
            .p(px(PADDING))
            .flex()
            .flex_col()
            .gap(px(GAP))
            .text_color(description)
            .text_size(px(12.))
            .line_height(px(LINE))
            .whitespace_normal()
            .child(div().font_weight(gpui::FontWeight::SEMIBOLD).text_size(px(13.)).text_color(foreground).child(content.title));

        let product = crate::product::display_version();
        let commit = crate::product::get("commit").as_str().unwrap_or_default().to_owned();
        let update = update_of(&self.update_state);
        let mut details = div().flex().flex_col().justify_center().child(div().mb(px(4.)).font_weight(gpui::FontWeight::SEMIBOLD).text_color(foreground).child(crate::product::name_long().to_owned()));
        let mut details_height = LINE + 4.;
        if !product.is_empty() {
            let (label, copy) = version_label("Current Version", &product, &commit);
            details = details.child(self.version_row("current-version", label, copy, cx));
            details_height += LINE;
        }
        if let Some(update) = update.filter(|update| !update.product_version.is_empty()) {
            let (label, copy) = version_label("Latest Version", &update.product_version, &update.version);
            details = details.child(self.version_row("latest-version", label, copy, cx));
            details_height += LINE;
        }
        let released = update.map(|update| update.timestamp).filter(|timestamp| *timestamp > 0).or_else(product_date).and_then(format_date);
        if let Some(date) = released {
            details = details.child(div().child(format!("Released {date}")));
            details_height += LINE;
        }
        tooltip = tooltip.child(div().flex().gap(px(12.)).child(div().id("update-tooltip-logo").flex_none().size(px(48.)).p(px(5.)).role(gpui::Role::Image).aria_label(crate::product::name_long().to_owned()).child(img(self.app_logo.clone()).size_full())).child(details));
        height += GAP + details_height.max(48.);

        if let Some(progress) = content.progress {
            tooltip = tooltip.child(self.update_tooltip_progress(&progress));
            height += GAP + 4. + 4. + 2. * LINE;
        }
        if let Some((message, icon)) = &content.message {
            let icon_color = match *icon {
                Some("warning") => self.color("editorWarning.foreground"),
                Some("error") => self.color("editorError.foreground"),
                _ => description,
            };
            let lines = (text_width(message, false, window) * 13. / 12. / (WIDTH - 2. * PADDING - 20.)).ceil().max(1.);
            height += GAP + lines * LINE;
            tooltip = tooltip.child(
                div().flex().items_start().gap(px(4.)).text_size(px(13.)).children(icon.map(|icon| div().flex_none().mt(px(2.)).child(self.icon(icon, 16., 16., icon_color)))).child(div().id("update-tooltip-message").flex_1().role(gpui::Role::Label).aria_label(message.clone()).child(message.clone())),
            );
        }
        let buttons = self.update_tooltip_buttons();
        if !buttons.is_empty() {
            height += GAP + LINE + 10.;
            tooltip = tooltip.child(self.update_tooltip_button_bar(buttons, cx));
        }
        (Size { width: WIDTH, height }, tooltip.into_any_element())
    }

    /// `createVersionRow`: the label and a copy button that shows while the row is hovered.
    fn version_row(&self, id: &'static str, label: String, copy: String, cx: &mut Context<Self>) -> Div {
        let group = format!("{id}-row");
        let icon_color = self.color("descriptionForeground");
        div().group(group.clone()).flex().items_center().gap(px(4.)).child(label).child(
            div()
                .id(id)
                .role(gpui::Role::Button)
                .aria_label("Copy")
                .mt(px(-2.))
                .cursor_pointer()
                .opacity(0.)
                .group_hover(group, |button| button.opacity(1.))
                .child(self.icon("copy", 16., 16., icon_color))
                .on_click(cx.listener(move |_, _: &ClickEvent, _, cx| {
                    cx.stop_propagation();
                    cx.write_to_clipboard(gpui::ClipboardItem::new_string(copy.clone()));
                })),
        )
    }

    fn update_tooltip_progress(&self, progress: &Progress) -> Div {
        let bar = self.color("progressBar.background");
        let mut track = bar;
        track.a *= 0.3;
        let text = |left: String, right: String| div().flex().justify_between().child(div().child(left)).child(div().child(right));
        div()
            .flex()
            .flex_col()
            .child(div().h(px(4.)).rounded(px(4.)).overflow_hidden().bg(track).child(div().h_full().rounded(px(4.)).w(relative(progress.percent as f32 / 100.)).bg(bar)))
            .child(text(format!("{}%", progress.percent), progress.size.clone()).mt(px(4.)))
            .child(text(progress.time_remaining.clone(), progress.speed.clone()))
    }

    /// `.button-bar`: Release Notes on the left, the action on the right; the focused one has the focus outline.
    fn update_tooltip_button_bar(&self, buttons: Vec<(&'static str, &'static str, Vec<Value>)>, cx: &mut Context<Self>) -> Div {
        let focus_border = self.color("focusBorder");
        let focused = self.update_title_bar.focused_button;
        let mut bar = div().flex().items_center().justify_end().gap(px(8.));
        for (index, (label, command, args)) in buttons.into_iter().enumerate() {
            let primary = command != "update.showCurrentReleaseNotes";
            let (background, hover, foreground, border) = match primary {
                true => ("button.background", "button.hoverBackground", "button.foreground", self.theme.color("button.border")),
                false => ("button.secondaryBackground", "button.secondaryHoverBackground", "button.secondaryForeground", self.theme.color("button.secondaryBorder").or_else(|| self.theme.color("button.border"))),
            };
            let hover = self.color(hover);
            let button = div()
                .id(("update-tooltip-button", index))
                .when(!primary, |button| button.mr_auto())
                .px(px(12.))
                .py(px(4.))
                .rounded(px(4.))
                .border_1()
                .border_color(gpui::transparent_black())
                .when_some(border, |button, border| button.border_color(border))
                .relative()
                // `outline: 1px solid var(--vscode-focusBorder); outline-offset: 2px`.
                .when(focused == Some(index), |button| button.child(div().absolute().inset(px(-3.)).rounded(px(6.)).border_1().border_color(focus_border)))
                .bg(self.color(background))
                .text_color(self.color(foreground))
                .whitespace_nowrap()
                .cursor_pointer()
                .hover(move |button| button.bg(hover))
                .child(label)
                .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| workbench.run_update_tooltip_button(command, args.clone(), window, cx)));
            bar = bar.child(button);
        }
        bar
    }
}

/// `ACTIONABLE_STATES`.
fn is_actionable(state: &State) -> bool {
    matches!(state, State::AvailableForDownload { .. } | State::Downloaded { .. } | State::Ready { .. })
}

fn update_of(state: &State) -> Option<&Update> {
    match state {
        State::AvailableForDownload { update } | State::Downloading { update, .. } | State::Downloaded { update } | State::Ready { update, .. } | State::Restarting { update, .. } => Some(update),
        _ => None,
    }
}

/// `UpdateTitleBarEntry.onStateChange`.
fn entry_label(state: &State) -> (&'static str, Look) {
    match state {
        State::Disabled(_) => ("Update", Look::Disabled),
        State::CheckingForUpdates { .. } => ("Checking...", Look::Indefinite),
        State::AvailableForDownload { .. } | State::Downloaded { .. } | State::Ready { .. } => ("Update", Look::Prominent),
        State::Downloading { downloaded_bytes, total_bytes, .. } => ("Downloading...", progress_percent(*downloaded_bytes, *total_bytes).map_or(Look::Indefinite, |percent| Look::Percent(percent as f32))),
        State::Restarting { .. } => ("Restarting...", Look::Indefinite),
        State::Uninitialized | State::Idle { .. } => ("Update", Look::Plain),
    }
}

#[derive(Debug, PartialEq)]
struct TooltipContent {
    title: String,
    /// The message and its codicon.
    message: Option<(String, Option<&'static str>)>,
    progress: Option<Progress>,
}

#[derive(Debug, PartialEq)]
struct Progress {
    percent: u64,
    size: String,
    time_remaining: String,
    speed: String,
}

/// `renderState`'s title, message and download progress of a state.
fn tooltip_content(state: &State, mode: &str) -> TooltipContent {
    let content = |title: &str, message: Option<(&str, Option<&'static str>)>| TooltipContent { title: title.into(), message: message.map(|(text, icon)| (text.into(), icon)), progress: None };
    match state {
        State::Uninitialized => content("Initializing", Some(("Initializing update service...", None))),
        State::Disabled(reason) => content(
            "Updates Disabled",
            Some(match reason {
                DisablementReason::NotBuilt => ("Updates are not available for this build.", Some("info")),
                DisablementReason::ManuallyDisabled => ("Updates are manually disabled. Change the \"update.mode\" setting to enable.", Some("warning")),
                DisablementReason::MissingConfiguration => ("Updates are disabled because no update URL is configured.", Some("info")),
            }),
        ),
        State::Idle { error: Some(error), .. } => TooltipContent { title: "Update Error".into(), message: Some((error.clone(), Some("error"))), progress: None },
        State::Idle { not_available: true, .. } => content("No Update Available", Some(("There are no updates currently available.", Some("info")))),
        State::Idle { .. } => content(
            "Up to Date",
            match mode {
                "none" => Some(("Automatic updates are disabled.", Some("warning"))),
                "manual" => Some(("Automatic updates will be checked but not installed automatically.", None)),
                "start" => Some(("Updates will be applied on restart.", None)),
                "default" => Some(("Automatic updates are enabled. Happy Coding!", Some("smiley"))),
                _ => None,
            },
        ),
        State::CheckingForUpdates { .. } => content("Checking for Updates", Some(("Checking for updates, please wait...", None))),
        State::AvailableForDownload { .. } => content("Update Available", None),
        State::Downloading { downloaded_bytes, total_bytes: Some(total), started_at, .. } if *total > 0 => {
            let elapsed = started_at.elapsed();
            let progress = Progress {
                percent: progress_percent(*downloaded_bytes, Some(*total)).unwrap_or(0),
                size: format!("{} / {}", format_bytes(*downloaded_bytes as f64), format_bytes(*total as f64)),
                speed: download_speed(*downloaded_bytes, elapsed).map(|speed| format!("{}/s", format_bytes(speed))).unwrap_or_default(),
                time_remaining: time_remaining(*downloaded_bytes, *total, elapsed).filter(|seconds| *seconds > 0).map(|seconds| format!("~{} remaining", format_time_remaining(seconds))).unwrap_or_default(),
            };
            TooltipContent { title: "Downloading Update".into(), message: None, progress: Some(progress) }
        }
        State::Downloading { .. } => content("Downloading Update", Some(("Downloading update, please wait...", None))),
        State::Downloaded { .. } => content("Update is Ready to Install", None),
        State::Ready { .. } if mode == "manual" => content("Update Installed", None),
        State::Ready { .. } => content("Restart to Update", None),
        State::Restarting { .. } => content(&format!("Restarting {}", crate::product::name_short()), Some(("Restarting to update, please wait...", None))),
    }
}

/// "Current Version: 1.148.0 (abcdef1)" and the text its copy button copies, with the whole commit.
fn version_label(prefix: &str, version: &str, commit: &str) -> (String, String) {
    match commit.get(..7) {
        Some(short) => (format!("{prefix}: {version} ({short})"), format!("{version} ({commit})")),
        None => (format!("{prefix}: {version}"), version.to_owned()),
    }
}

/// updateUtils.ts `computeProgressPercent`.
fn progress_percent(current: u64, max: Option<u64>) -> Option<u64> {
    let max = max.filter(|max| *max > 0)?;
    Some(((current as f64 / max as f64) * 100.).round().clamp(0., 100.) as u64)
}

/// `computeDownloadSpeed`, in bytes per second.
fn download_speed(downloaded: u64, elapsed: Duration) -> Option<f64> {
    (downloaded > 0 && !elapsed.is_zero()).then(|| downloaded as f64 / elapsed.as_secs_f64())
}

/// `computeDownloadTimeRemaining`, in whole seconds.
fn time_remaining(downloaded: u64, total: u64, elapsed: Duration) -> Option<u64> {
    if downloaded == 0 || total == 0 || elapsed.is_zero() {
        return None;
    }
    let remaining = total.saturating_sub(downloaded);
    Some((remaining as f64 / (downloaded as f64 / elapsed.as_secs_f64())).ceil() as u64)
}

/// `formatTimeRemaining`.
fn format_time_remaining(seconds: u64) -> String {
    let hours = seconds as f64 / 3600.;
    if hours >= 1. {
        let hours = format_decimal(hours);
        return if hours == "1" { format!("{hours} hour") } else { format!("{hours} hours") };
    }
    match seconds / 60 {
        0 => format!("{seconds}s"),
        minutes => format!("{minutes} min"),
    }
}

/// `formatBytes`.
fn format_bytes(bytes: f64) -> String {
    if bytes < 1024. {
        return format!("{bytes} B");
    }
    let mut value = bytes / 1024.;
    for unit in ["KB", "MB"] {
        if value < 1024. {
            return format!("{} {unit}", format_decimal(value));
        }
        value /= 1024.;
    }
    format!("{} GB", format_decimal(value))
}

/// `formatDecimal`: one decimal, without ".0".
fn format_decimal(value: f64) -> String {
    let rounded = (value * 10.).round() / 10.;
    if rounded.fract() == 0. { format!("{rounded:.0}") } else { format!("{rounded:.1}") }
}

/// product.json `date` (`tryParseDate`), in ms since the epoch.
fn product_date() -> Option<i64> {
    let date = crate::product::get("date");
    Some(chrono::DateTime::parse_from_rfc3339(date.as_str()?).ok()?.timestamp_millis())
}

/// `formatDate`: `toLocaleDateString` with a short month, as en-US writes it ("Jun 5, 2026").
fn format_date(timestamp: i64) -> Option<String> {
    Some(chrono::DateTime::from_timestamp_millis(timestamp)?.with_timezone(&chrono::Local).format("%b %-d, %Y").to_string())
}

/// `.progress-indefinite .indicator-progress`: a 1px line clipping a strip of two gradient tiles, each twice the
/// line's width, moved by one tile every 1.5s.
fn shimmer(color: Rgba) -> impl IntoElement {
    let clear = Rgba { a: 0., ..color };
    let tile = || {
        div()
            .h_full()
            .w(relative(0.5))
            .flex()
            .child(div().h_full().w(relative(0.8)).bg(linear_gradient(90., linear_color_stop(clear, 0.), linear_color_stop(color, 1.))))
            .child(div().h_full().w(relative(0.2)).bg(linear_gradient(90., linear_color_stop(color, 0.), linear_color_stop(clear, 1.))))
    };
    let strip = div().absolute().top_0().h_full().w(relative(4.)).flex().child(tile()).child(tile());
    div().absolute().left_0().bottom(px(1.)).h(px(1.)).w_full().rounded(px(1.)).overflow_hidden().child(strip.with_animation(
        "update-indicator-shimmer",
        Animation::new(Duration::from_millis(1500)).repeat().with_easing(gpui::ease_in_out),
        |strip, delta| strip.left(relative(-3. + 2. * delta)),
    ))
}

#[cfg(test)]
mod tests;