subspace-dashboard 0.5.0

Subspace Framework board kit: the Dashboard trait, shared widgets and design tokens. Internal crate; apps depend on `subspace-framework`.
Documentation
use super::{external, external_marked, external_marked_with_label};
use crate::Tokens;
use gpui_kit::test::{TestSupportExt as _, TestWindowExt as _};
use gpui_kit::{
    AppContext as _, Bounds, ClipboardItem, Context, Element as _, ElementId, FocusHandle,
    InteractiveElement as _, IntoElement, ParentElement as _, Pixels, Render, RenderOnce as _,
    Role, Styled as _, TestAppContext, VisualTestContext, Window, WindowBounds, WindowOptions,
    accesskit, canvas, div, px, size,
};
use std::{cell::RefCell, rc::Rc};

const WEB_URL: &str = "https://example.com/releases?product=subspace";

struct ExternalLinkFixture {
    url: &'static str,
    focus: FocusHandle,
    marked: bool,
}

impl Render for ExternalLinkFixture {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .track_focus(&self.focus)
            .tab_group()
            .flex()
            .flex_col()
            .items_start()
            .p_4()
            .child(
                // Base Link is RenderOnce, so observe its tight host instead.
                // Pointer and keyboard events still reach the production link.
                div()
                    .id("external-link-host")
                    .test_support()
                    .flex()
                    .child(self.link()),
            )
    }
}

impl ExternalLinkFixture {
    fn link(&self) -> gpui_kit::AnyElement {
        let tokens = Tokens::one_dark();
        if self.marked {
            external_marked_with_label(
                "external-link",
                "example.com",
                "Open project repository: example.com",
                self.url,
                &tokens,
            )
        } else {
            external("external-link", "Project repository", self.url, &tokens)
        }
    }
}

fn mount(cx: &mut TestAppContext, url: &'static str) -> VisualTestContext {
    mount_link(cx, url, false)
}

fn mount_link(cx: &mut TestAppContext, url: &'static str, marked: bool) -> VisualTestContext {
    cx.update(gpui_kit::init);
    let (window, _) = cx.update(|cx| {
        gpui_kit::open_window(
            WindowOptions {
                window_bounds: Some(WindowBounds::Windowed(Bounds::new(
                    Default::default(),
                    size(px(640.), px(480.)),
                ))),
                ..Default::default()
            },
            cx,
            |window, cx| {
                cx.new(|cx| {
                    let focus = cx.focus_handle();
                    focus.focus(window, cx);
                    ExternalLinkFixture { url, focus, marked }
                })
            },
        )
        .expect("open external link test window")
    });
    let mut cx = VisualTestContext::from_window(window, cx);
    settle(&mut cx);
    cx
}

/// Renders the production link during a draw and records the role and
/// accessibility node it writes, as GPUI does for assistive technology.
struct LinkSemantics {
    captured: Rc<RefCell<Option<(Option<Role>, accesskit::Node)>>>,
}

impl Render for LinkSemantics {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        let captured = self.captured.clone();
        canvas(
            move |_, window, cx| {
                let element = super::link(
                    "external-link".into(),
                    (
                        "example.com".into(),
                        "Open project repository: example.com".into(),
                    ),
                    WEB_URL.into(),
                    &Tokens::one_dark(),
                    true,
                )
                .render(window, cx)
                .into_element();
                let role = element.a11y_role();
                let mut node = accesskit::Node::new(role.unwrap_or(Role::Unknown));
                element.write_a11y_info(&mut node);
                *captured.borrow_mut() = Some((role, node));
            },
            |_, _, _, _| {},
        )
    }
}

#[gpui_kit::test]
fn a_marked_link_is_a_link_named_for_its_purpose_not_its_host(cx: &mut TestAppContext) {
    cx.update(gpui_kit::init);
    let captured = Rc::new(RefCell::new(None));
    let probe = captured.clone();
    let (_, cx) = cx.add_window_view(move |_, _| LinkSemantics { captured: probe });
    cx.update(|window, cx| window.draw(cx).clear(cx));
    let (role, node) = captured.borrow_mut().take().unwrap();
    assert_eq!(role, Some(Role::Link));
    assert_eq!(node.label(), Some("Open project repository: example.com"));
    assert!(node.supports_action(accesskit::Action::Click));
}

#[gpui_kit::test]
fn a_marked_link_paints_its_host_and_still_opens_the_full_url(cx: &mut TestAppContext) {
    let mut cx = mount_link(cx, WEB_URL, true);
    cx.update(|window, cx| {
        let texts = gpui_kit::base::test_support::texts(window);
        assert!(texts.iter().any(|text| text.text() == "example.com"));
        window.press("tab", cx);
        window.press("enter", cx);
    });
    assert_eq!(cx.opened_url().as_deref(), Some(WEB_URL));
}

fn settle(cx: &mut VisualTestContext) {
    cx.run_until_parked();
    cx.update(|window, cx| window.render_frame(cx));
}

#[gpui_kit::test]
fn pointer_opens_the_production_external_link(cx: &mut TestAppContext) {
    let mut cx = mount(cx, " https://example.com/releases?product=subspace ");
    assert_eq!(cx.opened_url(), None);
    cx.update(|window, cx| {
        let host = window.find("external-link-host");
        assert!(host.visible());
        assert!(host.bounds().size.width > px(0.));
        assert!(host.bounds().size.height > px(0.));
        window.click("external-link-host", cx);
    });
    assert_eq!(cx.opened_url().as_deref(), Some(WEB_URL));
}

#[gpui_kit::test]
fn enter_opens_a_keyboard_focused_external_link(cx: &mut TestAppContext) {
    let mut cx = mount(cx, WEB_URL);
    cx.update(|window, cx| {
        window.press("tab", cx);
        assert!(window.focused(cx).is_some());
        window.press("enter", cx);
    });
    assert_eq!(cx.opened_url().as_deref(), Some(WEB_URL));
}

#[gpui_kit::test]
fn space_opens_a_keyboard_focused_mail_link(cx: &mut TestAppContext) {
    let mut cx = mount(cx, "mailto:maintainer@example.com");
    cx.update(|window, cx| {
        window.press("tab", cx);
        assert!(window.focused(cx).is_some());
        window.press("space", cx);
    });
    assert_eq!(
        cx.opened_url().as_deref(),
        Some("mailto:maintainer@example.com")
    );
}

#[gpui_kit::test]
fn pointer_and_keyboard_cannot_open_an_unsafe_destination(cx: &mut TestAppContext) {
    let mut cx = mount(cx, "javascript:alert('test-only')");
    cx.update(|window, cx| {
        window.click("external-link-host", cx);
        assert!(window.focused(cx).is_some());
        window.press("enter", cx);
        window.press("space", cx);
    });
    assert_eq!(cx.opened_url(), None);
}

#[gpui_kit::test]
fn right_click_copies_the_destination_without_opening_it(cx: &mut TestAppContext) {
    let mut cx = mount(cx, WEB_URL);
    cx.update(|window, cx| {
        cx.write_to_clipboard(ClipboardItem::new_string("unchanged".into()));
        window.right_click("external-link-host", cx);
    });
    settle(&mut cx);
    assert_eq!(cx.opened_url(), None);
    assert_eq!(
        cx.read_from_clipboard().and_then(|item| item.text()),
        Some("unchanged".into())
    );
    cx.update(|window, cx| {
        assert_eq!(window.find(0usize).label(), Some("Copy link"));
        window.click(0usize, cx);
    });
    settle(&mut cx);
    assert_eq!(
        cx.read_from_clipboard().and_then(|item| item.text()),
        Some(WEB_URL.into())
    );
    assert_eq!(cx.opened_url(), None);
    cx.update(|window, _| assert!(window.try_find(0usize).is_none()));
}

/// A bare address with no break opportunities, far wider than the panel.
const LONG_ADDRESS: &str = "https://example.invalid/fixture-review-0042-unbroken";

/// The same marked link twice: in a host wide enough to show the whole
/// address, which gives its natural width, and in a narrow fixed-width panel
/// like an inspector's value column.
struct NarrowPanelFixture;

impl Render for NarrowPanelFixture {
    fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
        div()
            .flex()
            .flex_col()
            .items_start()
            .gap_4()
            .p_4()
            .child(div().id("wide-host").flex().child(long_link()))
            .child(
                div()
                    .id("narrow-panel")
                    .test_support()
                    .flex()
                    .w(px(120.))
                    .child(long_link()),
            )
    }
}

fn long_link() -> gpui_kit::AnyElement {
    let tokens = Tokens::one_dark();
    external_marked("long-link", LONG_ADDRESS, LONG_ADDRESS, &tokens)
}

fn mount_panels(cx: &mut TestAppContext) -> VisualTestContext {
    cx.update(gpui_kit::init);
    let (window, _) = cx.update(|cx| {
        gpui_kit::open_window(
            WindowOptions {
                window_bounds: Some(WindowBounds::Windowed(Bounds::new(
                    Default::default(),
                    size(px(640.), px(480.)),
                ))),
                ..Default::default()
            },
            cx,
            |_, cx| cx.new(|_| NarrowPanelFixture),
        )
        .expect("open narrow panel test window")
    });
    let mut cx = VisualTestContext::from_window(window, cx);
    settle(&mut cx);
    cx
}

/// Where the address's text element was laid out and painted inside the
/// identified element `within`.
fn painted_address(window: &Window, within: &'static str) -> Bounds<Pixels> {
    let within = ElementId::from(within);
    gpui_kit::base::test_support::texts(window)
        .into_iter()
        .find(|text| text.text() == LONG_ADDRESS && text.path().contains(&within))
        .unwrap_or_else(|| panic!("{LONG_ADDRESS} was not painted in {within:?}"))
        .bounds()
}

#[gpui_kit::test]
fn a_long_marked_address_shortens_to_fit_a_narrow_panel(cx: &mut TestAppContext) {
    let mut cx = mount_panels(cx);
    cx.update(|window, _| {
        let panel = window.find("narrow-panel").bounds();
        let natural = painted_address(window, "wide-host");
        let label = painted_address(window, "narrow-panel");
        // Too long to fit, so a pass is not down to short text.
        assert!(natural.size.width > panel.size.width);
        // The label itself, not a host that merely has `max_w_full`, stays in
        // the panel and stops short of its edge by the glyph's gap and
        // extra-small size, a rem between them, so the glyph shows too.
        assert!(label.size.width > px(0.));
        assert!(label.left() >= panel.left());
        assert!(
            panel.right() - label.right() >= window.rem_size(),
            "label {label:?} leaves no room for the glyph in {panel:?}"
        );
    });
}