arc-ui 0.4.0

Physics-first native Rust desktop UI component library & charts for GPUI (120+ interactive components ported from Arc).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
//! Ported from Arc (MIT) © 2026 Elia Kuratli
//! Reference: registry/blocks/empty-states/{empty-states.tsx,empty-states-art.ts}.
//! 插画直接移植上游十二帧、十个等点数图元;四种场景不使用替代图形。
use super::{child_id, text};
use crate::{Button, ButtonSize};
use arc_motion::{
    LayoutSnapshot, arc_spring_with_options, layout::layout_scope_key, sample_shared_layout,
};
use arc_tokens::{ActiveArcTheme as _, BlockTokens, Shadows, Spacing, Typography};
use gpui_kit::{
    App, BorderStyle, Bounds, Edges, ElementId, FocusHandle, InteractiveElement as _, IntoElement,
    KeyDownEvent, ParentElement, Pixels, RenderOnce, Role, ScrollHandle, SharedString,
    StatefulInteractiveElement as _, Styled, TestSupportExt as _, Window,
    base::{ElementExt as _, StyledExt as _},
    bounds, canvas, div, point, px, quad,
};
use std::{cell::RefCell, rc::Rc, time::Duration};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum EmptyScene {
    #[default]
    Search,
    Offline,
    Inbox,
    NotFound,
}
impl EmptyScene {
    fn index(self) -> usize {
        match self {
            Self::Search => 0,
            Self::Offline => 1,
            Self::Inbox => 2,
            Self::NotFound => 3,
        }
    }
    fn tab_label(self) -> &'static str {
        match self {
            Self::Search => "No results",
            Self::Offline => "Offline",
            Self::Inbox => "Caught up",
            Self::NotFound => "Not found",
        }
    }
    fn title(self) -> &'static str {
        match self {
            Self::Search => "No results for “Q3 roadmap”",
            Self::Offline => "You are offline",
            Self::Inbox => "All caught up",
            Self::NotFound => "Page not found",
        }
    }
    fn body(self) -> &'static str {
        match self {
            Self::Search => "Two filters are on: owner is Emma Collins and status is archived.",
            Self::Offline => "Edits are saved on this device and sync when the connection returns.",
            Self::Inbox => "You have read every message in Inbox. New mail lands here first.",
            Self::NotFound => "The link to /projects/atlas-2023 is broken, or the page has moved.",
        }
    }
    fn action(self) -> &'static str {
        match self {
            Self::Search => "Clear filters",
            Self::Offline => "Try again",
            Self::Inbox => "Check for mail",
            Self::NotFound => "Find the page",
        }
    }
    fn done_title(self) -> &'static str {
        match self {
            Self::Search => "12 results for “Q3 roadmap”",
            Self::Offline => "Back online",
            Self::Inbox => "Still all caught up",
            Self::NotFound => "Found it in Archive",
        }
    }
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(super) enum Phase {
    #[default]
    Idle,
    Loading,
    Done,
}
struct State {
    scene: EmptyScene,
    phase: Phase,
    from: Phase,
    generation: u64,
    tab_bounds: Rc<RefCell<[Option<Bounds<Pixels>>; 4]>>,
    tab_focus: [FocusHandle; 4],
    tab_scroll: ScrollHandle,
    container_width: f32,
}
impl State {
    fn choose(&mut self, scene: EmptyScene) {
        // 重按当前标签不能取消正在执行的动作;与上游 choose 一致。
        if self.scene != scene {
            self.scene = scene;
            self.phase = Phase::Idle;
            self.from = Phase::Idle;
            self.generation += 1;
        }
    }
}
type Action = Rc<dyn Fn(EmptyScene, &mut Window, &mut App)>;
#[derive(IntoElement)]
pub struct EmptyStates {
    id: ElementId,
    scene: Option<EmptyScene>,
    loading: bool,
    on_action: Option<Action>,
}
impl EmptyStates {
    pub fn new(id: impl Into<ElementId>) -> Self {
        Self {
            id: id.into(),
            scene: None,
            loading: false,
            on_action: None,
        }
    }
    pub fn scene(mut self, v: EmptyScene) -> Self {
        self.scene = Some(v);
        self
    }
    pub fn loading(mut self, v: bool) -> Self {
        self.loading = v;
        self
    }
    pub fn on_action(mut self, f: impl Fn(EmptyScene, &mut Window, &mut App) + 'static) -> Self {
        self.on_action = Some(Rc::new(f));
        self
    }
}
#[path = "empty_art.rs"]
mod empty_art;
use empty_art::artwork;

impl RenderOnce for EmptyStates {
    fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
        let state = w.use_keyed_state(child_id(&self.id, "state"), cx, |_, cx| State {
            scene: self.scene.unwrap_or_default(),
            phase: Phase::Idle,
            from: Phase::Idle,
            generation: 0,
            tab_bounds: Rc::new(RefCell::new([None; 4])),
            tab_focus: std::array::from_fn(|index| cx.focus_handle().tab_stop(index == 0)),
            tab_scroll: ScrollHandle::new(),
            container_width: f32::from(BlockTokens::PANEL_WIDTH),
        });
        if let Some(scene) = self.scene
            && scene != state.read(cx).scene
        {
            state.update(cx, |s, _| {
                s.scene = scene;
                s.phase = Phase::Idle;
                s.from = Phase::Idle;
                s.generation += 1;
            });
        }
        let scene = state.read(cx).scene;
        let phase = if self.loading {
            Phase::Loading
        } else {
            state.read(cx).phase
        };
        let colors = cx.arc_theme().colors;
        let motion = cx.arc_theme().motion;
        // 上游 .tabs:标签宽度来自自身内容,空间足够时等比分配;窄容器不压缩文字而横向溢出。
        // 高亮不是按四等分百分比定位,而是取当前标签的真实边界,交给共享布局 registry 做 FLIP。
        let scenes = [
            EmptyScene::Search,
            EmptyScene::Offline,
            EmptyScene::Inbox,
            EmptyScene::NotFound,
        ];
        let tab_bounds = state.read(cx).tab_bounds.clone();
        let tab_focus = state.read(cx).tab_focus.clone();
        let tab_scroll = state.read(cx).tab_scroll.clone();
        let container_width = state.read(cx).container_width;
        let compact = container_width <= BlockTokens::EMPTY_TABS_COMPACT_AT;
        let tab_padding = if compact {
            BlockTokens::EMPTY_TAB_COMPACT_PADDING
        } else {
            px(
                (container_width * BlockTokens::EMPTY_TAB_PADDING_RATIO).clamp(
                    BlockTokens::EMPTY_TAB_PADDING_MIN,
                    BlockTokens::EMPTY_TAB_PADDING_MAX,
                ),
            )
        };
        let tab_text_size = if compact {
            Typography::TEXT_XS
        } else {
            Typography::TEXT_SM
        };
        // 上游 grid 的 flex-fraction 语义:空间不足时四列全部取最宽标签的
        // 基数(等宽溢出滚动),而不是各自卡在各自 min-content。taffy flex
        // 的隐式下限是逐项的,这里用上一帧测得的最宽宽度作为统一 min_w 复现。
        let tab_min_w = state
            .read(cx)
            .tab_bounds
            .borrow()
            .iter()
            .flatten()
            .map(|b| b.size.width)
            .max()
            .unwrap_or(px(0.0));
        let selected_scene = scene;
        let scope = layout_scope_key(&self.id);
        let highlight_bg = colors.surface;
        let highlight_border = colors.border;
        let highlight_shadow = Shadows::resting(cx.arc_theme().mode);
        let morph = motion.spring.morph;
        let highlight = canvas(
            |_, _, _| {},
            move |list_rect, _, window, cx| {
                let Some(tab_rect) = tab_bounds.borrow()[selected_scene.index()] else {
                    window.request_animation_frame();
                    return;
                };
                let target = LayoutSnapshot::uniform_radius(
                    bounds(tab_rect.origin - list_rect.origin, tab_rect.size),
                    BlockTokens::EMPTY_TAB_RADIUS,
                );
                let flip = sample_shared_layout(
                    scope.clone(),
                    "selection",
                    target,
                    Some(morph),
                    window,
                    cx,
                );
                let paint_bounds = bounds(
                    point(
                        list_rect.origin.x + flip.bounds.origin.x,
                        list_rect.origin.y + flip.bounds.origin.y,
                    ),
                    flip.bounds.size,
                );
                window.paint_drop_shadows(paint_bounds, flip.corner_radii, &highlight_shadow);
                window.paint_quad(quad(
                    paint_bounds,
                    flip.corner_radii,
                    highlight_bg,
                    Edges::all(px(1.0)),
                    highlight_border,
                    BorderStyle::Solid,
                ));
            },
        )
        .absolute()
        .inset_0();
        let key_state = state.clone();
        let key_focus = tab_focus.clone();
        let key_scroll = tab_scroll.clone();
        let mut tabs = div()
            .id(child_id(&self.id, "tabs"))
            .test_support()
            .role(Role::TabList)
            .aria_label("Empty state")
            .relative()
            .flex()
            .flex_row()
            // 上游 grid repeat(4, minmax(max-content, 1fr)) 在 taffy 中无直接对应
            // (minmax(min-content,1fr) 是「基数+均摊剩余」而非 CSS 的等宽 fr 语义),
            // 故用 flex 等效:宽容器 basis 0 + grow 1 严格等分;compact 时 shrink 0
            // 保持文字不压缩,由 overflow 滚动容器承载溢出。
            .gap(BlockTokens::EMPTY_TABS_GAP)
            .w_full()
            .max_w(BlockTokens::EMPTY_TABS_WIDTH)
            .overflow_x_scroll()
            .track_scroll(&tab_scroll)
            .on_key_down(move |event: &KeyDownEvent, w, cx| {
                let index = key_state.read(cx).scene.index();
                let next = match event.keystroke.key.as_str() {
                    "right" => (index + 1) % scenes.len(),
                    "left" => (index + scenes.len() - 1) % scenes.len(),
                    "home" => 0,
                    "end" => scenes.len() - 1,
                    "enter" | "space" => index,
                    _ => return,
                };
                key_state.update(cx, |s, _| s.choose(scenes[next]));
                key_focus[next].focus(w, cx);
                // 第一个绝对子元素是高亮 canvas,不参与标签序号。
                key_scroll.scroll_to_item(next + 1);
                cx.stop_propagation();
                w.refresh();
            })
            .p(BlockTokens::EMPTY_TABS_PADDING)
            .rounded(BlockTokens::EMPTY_TABS_RADIUS)
            .border_1()
            .border_color(colors.border)
            .bg(colors.surface_muted)
            .child(highlight);
        for next in scenes {
            let selected = scene == next;
            let st = state.clone();
            let focus = tab_focus[next.index()].clone().tab_stop(selected);
            let click_focus = focus.clone();
            let click_scroll = tab_scroll.clone();
            let measured = state.read(cx).tab_bounds.clone();
            let measure_index = next.index();
            let measure = canvas(
                move |bounds, _, _| {
                    measured.borrow_mut()[measure_index] = Some(bounds);
                },
                |_, _, _, _| {},
            )
            .absolute()
            .inset_0();
            // 宽容器四列严格等分(等效上游 1fr:basis 0 + grow 1);
            // compact 保持内容宽不压缩(默认 basis auto + shrink 0)。
            let tab = div()
                .id(child_id(&self.id, format!("scene-{}", next.index())))
                .test_support()
                .role(Role::Tab)
                .aria_selected(selected)
                .tab_index(if selected { 0 } else { -1 })
                .tab_stop(selected)
                .track_focus(&focus)
                .cursor_pointer()
                .relative()
                .min_h(BlockTokens::EMPTY_TAB_HEIGHT)
                .px(tab_padding);
            let tab = if compact {
                tab.flex_grow(0.0).flex_shrink(0.0)
            } else {
                tab.flex_grow(1.0)
                    .flex_basis(px(0.0))
                    .flex_shrink(1.0)
                    .min_w(tab_min_w)
            };
            // 点击部分可见标签时滚入视野(对齐浏览器原生 scrollIntoView 行为);
            // 偏移 +1 与键盘路径一致:第一个绝对子元素是高亮 canvas。
            tabs = tabs.child(
                tab.flex()
                    .items_center()
                    .justify_center()
                    .rounded(BlockTokens::EMPTY_TAB_RADIUS)
                    .text_size(tab_text_size)
                    .whitespace_nowrap()
                    .font_medium()
                    .text_color(if selected {
                        colors.foreground
                    } else {
                        colors.text_muted
                    })
                    .hover(|s| s.text_color(colors.foreground))
                    .on_click(move |_, w, cx| {
                        st.update(cx, |s, _| s.choose(next));
                        click_focus.focus(w, cx);
                        click_scroll.scroll_to_item(next.index() + 1);
                        w.refresh();
                    })
                    .child(measure)
                    .child(next.tab_label()),
            );
        }
        // 上游 loading 沿用触发前的标题和按钮文案,收件箱重复检查不能退回初始标题。
        let copy_done =
            phase == Phase::Done || (phase == Phase::Loading && state.read(cx).from == Phase::Done);
        let title = if copy_done {
            scene.done_title()
        } else {
            scene.title()
        };
        let line = match (scene, phase) {
            (EmptyScene::Offline, Phase::Loading) => "Reaching sync.northwind.example…",
            (EmptyScene::Inbox, Phase::Loading) => "Checking for new mail…",
            (EmptyScene::NotFound, Phase::Loading) => "Searching the workspace for Atlas…",
            (EmptyScene::Search, Phase::Done) => {
                "Filters cleared. Showing matches from every owner and status."
            }
            (EmptyScene::Offline, Phase::Done) => {
                "Three edits synced to the Northwind workspace just now."
            }
            (EmptyScene::Inbox, Phase::Done) => {
                "Checked just now. Nothing new since 8:30 this morning."
            }
            (EmptyScene::NotFound, Phase::Done) => {
                "Atlas 2023 roadmap moved to /archive/atlas-2023 in March."
            }
            _ => scene.body(),
        };
        // 上游 .swap:文案变化时旧文上移淡出、新文自下 8px 升入(blur 桌面省略)。
        // 以文本为 key 的弹簧从初值 8 起跳,文案不变时弹簧保持终点不动。
        let title_rise = arc_spring_with_options(
            (child_id(&self.id, "title-rise"), SharedString::from(title)),
            0.0,
            arc_motion::spring::SpringOptions::new(motion.spring.snappy)
                .with_initial_value(BlockTokens::EMPTY_COPY_ENTER_Y),
            w,
            cx,
        );
        let line_rise = arc_spring_with_options(
            (child_id(&self.id, "line-rise"), SharedString::from(line)),
            0.0,
            arc_motion::spring::SpringOptions::new(motion.spring.snappy)
                .with_initial_value(BlockTokens::EMPTY_COPY_ENTER_Y),
            w,
            cx,
        );
        if !title_rise.settled || !line_rise.settled {
            w.request_animation_frame();
        }
        let rise_opacity = |v: f32| (1.0 - v / BlockTokens::EMPTY_COPY_ENTER_Y).clamp(0.0, 1.0);
        let action_label = if copy_done {
            match scene {
                EmptyScene::Search => "Restore filters",
                EmptyScene::Offline => "Go offline",
                EmptyScene::Inbox => "Check again",
                EmptyScene::NotFound => "Show broken link",
            }
        } else {
            scene.action()
        };
        let st = state.clone();
        let size_state = state.clone();
        let cb = self.on_action;
        super::surface(cx)
            .id(self.id.clone())
            .role(Role::Region)
            .aria_label("Empty states")
            .relative()
            .on_prepaint(move |bounds, window, cx| {
                let width = f32::from(bounds.size.width);
                if (size_state.read(cx).container_width - width).abs() > 0.5 {
                    size_state.update(cx, |s, _| s.container_width = width);
                    window.refresh();
                }
            })
            .test_support()
            .py(px((container_width * 0.05).clamp(16.0, 48.0)))
            .px(px((container_width * 0.04).clamp(16.0, 40.0)))
            .gap(px((container_width * 0.04).clamp(20.0, 32.0)))
            .items_center()
            .child(tabs)
            .child(
                div()
                    .flex()
                    .flex_col()
                    .items_center()
                    .gap(Spacing::S5)
                    .w_full()
                    .max_w(px(480.0))
                    .child(artwork(
                        &self.id,
                        scene,
                        phase,
                        container_width - 2.0 * (container_width * 0.04).clamp(16.0, 40.0) - 2.0,
                        w,
                        cx,
                    ))
                    .child(
                        div()
                            .flex()
                            .flex_col()
                            .items_center()
                            .w_full()
                            .gap(Spacing::S4)
                            .child(
                                div()
                                    .flex()
                                    .flex_col()
                                    .items_center()
                                    .id(child_id(&self.id, "copy"))
                                    .test_support()
                                    .gap(px(6.0))
                                    .w_full()
                                    .px(Spacing::S2)
                                    .text_center()
                                    .child(
                                        div()
                                            .id(child_id(&self.id, "status"))
                                            .test_support()
                                            .role(Role::Status)
                                            .aria_label(title)
                                            .text_size(if container_width >= 560.0 {
                                                Typography::TEXT_XL
                                            } else {
                                                Typography::TEXT_LG
                                            })
                                            .font_medium()
                                            .text_color(colors.foreground)
                                            .relative()
                                            .top(px(title_rise.value))
                                            .opacity(rise_opacity(title_rise.value))
                                            .child(title),
                                    )
                                    .child(
                                        text(line, cx)
                                            .text_size(Typography::TEXT_SM)
                                            .max_w(px(360.0))
                                            .relative()
                                            .top(px(line_rise.value))
                                            .opacity(rise_opacity(line_rise.value)),
                                    ),
                            )
                            .child(
                                div().w_full().flex().justify_center().child(
                                    Button::new(child_id(&self.id, "action"))
                                        .label(action_label)
                                        .loading(phase == Phase::Loading)
                                        .disabled(phase == Phase::Loading)
                                        .size(ButtonSize::Sm)
                                        .on_click(move |_, w, cx| {
                                            let wait = BlockTokens::EMPTY_WAITS_MS[scene.index()];
                                            let generation = st.update(cx, |s, _| {
                                                s.generation += 1;
                                                s.from = phase;
                                                s.phase = if phase == Phase::Done
                                                    && scene != EmptyScene::Inbox
                                                {
                                                    Phase::Idle
                                                } else if wait == 0 {
                                                    Phase::Done
                                                } else {
                                                    Phase::Loading
                                                };
                                                s.generation
                                            });
                                            if st.read(cx).phase == Phase::Loading {
                                                let weak = st.downgrade();
                                                w.spawn(cx, async move |cx| {
                                                    cx.background_executor()
                                                        .timer(Duration::from_millis(wait))
                                                        .await;
                                                    let _ = cx.update(|w, cx| {
                                                        let _ = weak.update(cx, |s, _| {
                                                            if s.generation == generation {
                                                                s.phase = Phase::Done;
                                                            }
                                                        });
                                                        w.refresh();
                                                    });
                                                })
                                                .detach();
                                            }
                                            if let Some(cb) = &cb {
                                                cb(scene, w, cx);
                                            }
                                            w.refresh();
                                        }),
                                ),
                            ),
                    ),
            )
            .rounded(px(20.0))
    }
}
#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn scenes_have_distinct_actions_and_completion_copy() {
        for scene in [
            EmptyScene::Search,
            EmptyScene::Offline,
            EmptyScene::Inbox,
            EmptyScene::NotFound,
        ] {
            assert!(!scene.action().is_empty());
            assert_ne!(scene.title(), scene.done_title());
        }
    }
}