Skip to main content

arc_ui/blocks/
page_header.rs

1//! Ported from Arc (MIT) © 2026 Elia Kuratli
2//! Reference: registry/blocks/page-header/page-header.tsx.
3//! 页面头部保留滚动收紧、四页签、问题完成和归档等桌面交互;真实媒体资源由调用方提供。
4use super::{child_id, text};
5use crate::{
6    Avatar, AvatarGroup, AvatarGroupMember, AvatarSize, Badge, BadgeTone, Button, ButtonSize,
7    ButtonVariant, DropdownItem, DropdownMenu, Progress,
8};
9use arc_motion::{
10    ArcPresence, ArcPresenceConfig, LayoutSnapshot, arc_spring, arc_spring_with_options,
11    layout::layout_scope_key, motion_now, sample_shared_layout, spring::SpringOptions,
12};
13use arc_tokens::{ActiveArcTheme as _, BlockTokens, Radii, Spacing, Typography};
14use gpui_kit::base::{ElementExt as _, StyledExt as _};
15use gpui_kit::{
16    App, BorderStyle, Bounds, Edges, ElementId, InteractiveElement as _, IntoElement,
17    ParentElement, Pixels, RenderOnce, Role, SharedString, StatefulInteractiveElement as _, Styled,
18    TestSupportExt as _, Window, assets::IconName, bounds, canvas, div, point, prelude::*, px,
19    quad, svg,
20};
21use std::{cell::RefCell, rc::Rc, time::Duration};
22
23#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
24pub enum PageSection {
25    #[default]
26    Overview,
27    Issues,
28    Updates,
29    Files,
30}
31impl PageSection {
32    fn order(self) -> usize {
33        match self {
34            Self::Overview => 0,
35            Self::Issues => 1,
36            Self::Updates => 2,
37            Self::Files => 3,
38        }
39    }
40    fn label(self) -> &'static str {
41        match self {
42            Self::Overview => "Overview",
43            Self::Issues => "Issues",
44            Self::Updates => "Updates",
45            Self::Files => "Files",
46        }
47    }
48}
49#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
50pub enum MilestoneState {
51    Done,
52    #[default]
53    Active,
54    Planned,
55}
56#[derive(Clone, Debug, PartialEq, Eq)]
57pub struct PagePerson {
58    pub name: SharedString,
59    pub photo: Option<SharedString>,
60}
61impl PagePerson {
62    pub fn new(name: impl Into<SharedString>) -> Self {
63        Self {
64            name: name.into(),
65            photo: None,
66        }
67    }
68    pub fn photo(mut self, photo: impl Into<SharedString>) -> Self {
69        self.photo = Some(photo.into());
70        self
71    }
72}
73impl From<&str> for PagePerson {
74    fn from(name: &str) -> Self {
75        Self::new(name)
76    }
77}
78impl From<String> for PagePerson {
79    fn from(name: String) -> Self {
80        Self::new(name)
81    }
82}
83impl From<SharedString> for PagePerson {
84    fn from(name: SharedString) -> Self {
85        Self::new(name)
86    }
87}
88#[derive(Clone, Debug)]
89pub struct PageIssue {
90    pub id: SharedString,
91    pub title: SharedString,
92    pub done: bool,
93    pub label: Option<SharedString>,
94    pub owner: Option<PagePerson>,
95}
96impl PageIssue {
97    pub fn new(id: impl Into<SharedString>, title: impl Into<SharedString>) -> Self {
98        Self {
99            id: id.into(),
100            title: title.into(),
101            done: false,
102            label: None,
103            owner: None,
104        }
105    }
106    pub fn label(mut self, label: impl Into<SharedString>) -> Self {
107        self.label = Some(label.into());
108        self
109    }
110    pub fn owner(mut self, owner: impl Into<SharedString>) -> Self {
111        self.owner = Some(PagePerson::new(owner));
112        self
113    }
114    pub fn owner_with(mut self, owner: PagePerson) -> Self {
115        self.owner = Some(owner);
116        self
117    }
118}
119#[derive(Clone, Debug)]
120pub struct PageMilestone {
121    pub id: SharedString,
122    pub name: SharedString,
123    pub note: SharedString,
124    pub state: MilestoneState,
125}
126impl PageMilestone {
127    pub fn new(
128        name: impl Into<SharedString>,
129        note: impl Into<SharedString>,
130        state: MilestoneState,
131    ) -> Self {
132        let name = name.into();
133        Self {
134            id: name.clone(),
135            name,
136            note: note.into(),
137            state,
138        }
139    }
140}
141#[derive(Clone, Debug)]
142pub struct PageActivity {
143    pub id: SharedString,
144    pub person: PagePerson,
145    pub text: SharedString,
146    pub time: SharedString,
147}
148impl PageActivity {
149    pub fn new(
150        id: impl Into<SharedString>,
151        person: impl Into<SharedString>,
152        text: impl Into<SharedString>,
153        time: impl Into<SharedString>,
154    ) -> Self {
155        Self {
156            id: id.into(),
157            person: PagePerson::new(person),
158            text: text.into(),
159            time: time.into(),
160        }
161    }
162}
163#[derive(Clone, Debug)]
164pub struct PageUpdate {
165    pub id: SharedString,
166    pub author: PagePerson,
167    pub date: SharedString,
168    pub body: SharedString,
169    pub status: Option<SharedString>,
170    pub tone: BadgeTone,
171}
172impl PageUpdate {
173    pub fn new(
174        id: impl Into<SharedString>,
175        author: impl Into<PagePerson>,
176        date: impl Into<SharedString>,
177        body: impl Into<SharedString>,
178    ) -> Self {
179        Self {
180            id: id.into(),
181            author: author.into(),
182            date: date.into(),
183            body: body.into(),
184            status: None,
185            tone: BadgeTone::Success,
186        }
187    }
188    pub fn status(mut self, status: impl Into<SharedString>, tone: BadgeTone) -> Self {
189        self.status = Some(status.into());
190        self.tone = tone;
191        self
192    }
193}
194#[derive(Clone, Debug)]
195pub struct PageFile {
196    pub id: SharedString,
197    pub name: SharedString,
198    pub kind: SharedString,
199    pub size: SharedString,
200    pub owner: Option<PagePerson>,
201    pub date: Option<SharedString>,
202}
203impl PageFile {
204    pub fn new(
205        id: impl Into<SharedString>,
206        name: impl Into<SharedString>,
207        kind: impl Into<SharedString>,
208        size: impl Into<SharedString>,
209    ) -> Self {
210        Self {
211            id: id.into(),
212            name: name.into(),
213            kind: kind.into(),
214            size: size.into(),
215            owner: None,
216            date: None,
217        }
218    }
219    pub fn owner(mut self, owner: impl Into<SharedString>) -> Self {
220        self.owner = Some(PagePerson::new(owner));
221        self
222    }
223    pub fn owner_with(mut self, owner: PagePerson) -> Self {
224        self.owner = Some(owner);
225        self
226    }
227    pub fn date(mut self, date: impl Into<SharedString>) -> Self {
228        self.date = Some(date.into());
229        self
230    }
231}
232#[derive(Clone, Copy, Debug, PartialEq, Eq)]
233enum SharePhase {
234    Idle,
235    Sending,
236    Sent,
237}
238#[derive(Clone, Copy, Debug, PartialEq, Eq)]
239enum NoticeTone {
240    Success,
241    Neutral,
242}
243impl NoticeTone {
244    fn glyph(self) -> &'static str {
245        match self {
246            Self::Success => "✓",
247            Self::Neutral => "•",
248        }
249    }
250}
251type Notice = Rc<dyn Fn(SharedString, &mut Window, &mut App)>;
252#[derive(IntoElement)]
253pub struct PageHeader {
254    id: ElementId,
255    title: SharedString,
256    description: SharedString,
257    issues: Vec<PageIssue>,
258    milestones: Vec<PageMilestone>,
259    activity: Vec<PageActivity>,
260    members: Vec<PagePerson>,
261    updates: Vec<PageUpdate>,
262    files: Vec<PageFile>,
263    project_url: Option<SharedString>,
264    section: PageSection,
265    archived: bool,
266    on_notice: Option<Notice>,
267}
268
269#[derive(Clone)]
270struct State {
271    section: PageSection,
272    archived: bool,
273    issues: Vec<PageIssue>,
274    scroll: gpui_kit::ScrollHandle,
275    condensed: bool,
276    notice: SharedString,
277    notice_tone: NoticeTone,
278    notice_at: f64,
279    following: bool,
280    sharing: SharePhase,
281    serial: u64,
282    updates: Vec<PageUpdate>,
283    collapsed: bool,
284    width: f32,
285    direction: f32,
286    /// 打开中的问题;完成后先播放退场,再从这里移除。
287    closing: Vec<SharedString>,
288    done_count: u32,
289    sample: Vec<PageIssue>,
290    /// 每枚页签的实测边界(canvas prepaint 记录),供指示线按真实 tab 定位。
291    tab_bounds: Rc<RefCell<[Option<Bounds<Pixels>>; 4]>>,
292}
293impl State {
294    fn notify(&mut self, message: impl Into<SharedString>, tone: NoticeTone, now: f64) {
295        self.notice = message.into();
296        self.notice_tone = tone;
297        self.notice_at = now;
298    }
299}
300impl PageHeader {
301    pub fn new(id: impl Into<ElementId>) -> Self {
302        Self {
303            id: id.into(),
304            title: "Checkout redesign".into(),
305            description:
306                "Rebuilding mobile checkout around saved payment methods and a single review step."
307                    .into(),
308            issues: vec![],
309            milestones: sample_milestones(),
310            activity: sample_activity(),
311            members: sample_members(),
312            updates: vec![],
313            files: vec![],
314            project_url: None,
315            section: PageSection::Overview,
316            archived: false,
317            on_notice: None,
318        }
319    }
320    pub fn title(mut self, v: impl Into<SharedString>) -> Self {
321        self.title = v.into();
322        self
323    }
324    pub fn description(mut self, v: impl Into<SharedString>) -> Self {
325        self.description = v.into();
326        self
327    }
328    pub fn issues(mut self, v: impl IntoIterator<Item = PageIssue>) -> Self {
329        self.issues = v.into_iter().collect();
330        self
331    }
332    pub fn milestones(mut self, v: impl IntoIterator<Item = PageMilestone>) -> Self {
333        self.milestones = v.into_iter().collect();
334        self
335    }
336    pub fn activity(mut self, v: impl IntoIterator<Item = PageActivity>) -> Self {
337        self.activity = v.into_iter().collect();
338        self
339    }
340    pub fn members(mut self, v: impl IntoIterator<Item = PagePerson>) -> Self {
341        self.members = v.into_iter().collect();
342        self
343    }
344    pub fn updates(mut self, v: impl IntoIterator<Item = PageUpdate>) -> Self {
345        self.updates = v.into_iter().collect();
346        self
347    }
348    pub fn files(mut self, v: impl IntoIterator<Item = PageFile>) -> Self {
349        self.files = v.into_iter().collect();
350        self
351    }
352    pub fn project_url(mut self, v: impl Into<SharedString>) -> Self {
353        self.project_url = Some(v.into());
354        self
355    }
356    pub fn section(mut self, v: PageSection) -> Self {
357        self.section = v;
358        self
359    }
360    pub fn archived(mut self, v: bool) -> Self {
361        self.archived = v;
362        self
363    }
364    pub fn on_notice(mut self, f: impl Fn(SharedString, &mut Window, &mut App) + 'static) -> Self {
365        self.on_notice = Some(Rc::new(f));
366        self
367    }
368}
369
370fn sample_members() -> Vec<PagePerson> {
371    [
372        "Emma Collins",
373        "Marcus Johnson",
374        "Ava Mitchell",
375        "Sofia Ramirez",
376        "Jasmine Brooks",
377    ]
378    .into_iter()
379    .map(PagePerson::new)
380    .collect()
381}
382fn sample_milestones() -> Vec<PageMilestone> {
383    vec![
384        PageMilestone::new(
385            "Saved payment methods",
386            "Shipped Sep 18",
387            MilestoneState::Done,
388        ),
389        PageMilestone::new(
390            "Single review step",
391            "In progress, due Oct 1",
392            MilestoneState::Active,
393        ),
394        PageMilestone::new(
395            "Staged rollout",
396            "Planned for Oct 14",
397            MilestoneState::Planned,
398        ),
399    ]
400}
401fn sample_activity() -> Vec<PageActivity> {
402    vec![
403        PageActivity::new("a1", "Ava Mitchell", "moved CHK-131 to review", "1h ago"),
404        PageActivity::new(
405            "a2",
406            "Marcus Johnson",
407            "merged the saved cards endpoint",
408            "3h ago",
409        ),
410        PageActivity::new(
411            "a3",
412            "Emma Collins",
413            "shared Checkout flows v3",
414            "Yesterday",
415        ),
416        PageActivity::new(
417            "a4",
418            "Sofia Ramirez",
419            "closed CHK-119, a double charge on retry",
420            "Yesterday",
421        ),
422        PageActivity::new(
423            "a5",
424            "Jasmine Brooks",
425            "set the rollout date to October 14",
426            "Sep 17",
427        ),
428    ]
429}
430fn avatar(id: ElementId, person: &PagePerson) -> Avatar {
431    let a = Avatar::new(id, person.name.clone());
432    match &person.photo {
433        Some(photo) => a.src(photo.clone()),
434        None => a,
435    }
436}
437impl RenderOnce for PageHeader {
438    fn render(self, w: &mut Window, cx: &mut App) -> impl IntoElement {
439        let colors = cx.arc_theme().colors;
440        let motion = cx.arc_theme().motion;
441        let now = motion_now(cx);
442        let sample = self.issues.clone();
443        let opening: Vec<PageIssue> = sample.iter().filter(|i| !i.done).cloned().collect();
444        let initial_done = sample.iter().filter(|i| i.done).count() as u32;
445        let state = w.use_keyed_state(child_id(&self.id, "state"), cx, |_, _| State {
446            section: self.section,
447            archived: self.archived,
448            issues: opening,
449            scroll: gpui_kit::ScrollHandle::new(),
450            condensed: false,
451            notice: "".into(),
452            notice_tone: NoticeTone::Success,
453            notice_at: f64::NEG_INFINITY,
454            following: false,
455            sharing: SharePhase::Idle,
456            serial: 0,
457            updates: self.updates.clone(),
458            collapsed: false,
459            width: 0.0,
460            direction: 1.0,
461            closing: vec![],
462            done_count: initial_done,
463            sample,
464            tab_bounds: Rc::new(RefCell::new([None; 4])),
465        });
466        let snap = state.read(cx).clone();
467        let open = snap.issues.len() as u32;
468        let done = snap.done_count;
469        let mut root = div()
470            .id(self.id.clone())
471            .role(Role::Region)
472            .aria_label(self.title.clone())
473            .relative()
474            .w_full()
475            .flex()
476            .flex_col()
477            .h(BlockTokens::PAGE_HEIGHT)
478            .overflow_hidden()
479            .rounded(Radii::PANEL)
480            .border_1()
481            .border_color(colors.border)
482            .bg(colors.surface)
483            .text_color(colors.foreground);
484        // GPUI 没有 ResizeObserver;用 prepaint 读取自身宽度,并以滞回阈值折叠次要操作。
485        let measure = state.clone();
486        root = root.on_prepaint(move |bounds, window, cx| {
487            let width = f32::from(bounds.size.width);
488            if width <= 0.0 {
489                return;
490            }
491            let mut changed = false;
492            measure.update(cx, |s, _| {
493                if (s.width - width).abs() > 0.5 {
494                    s.width = width;
495                    let collapsed = if s.collapsed {
496                        width < BlockTokens::ACTIONS_RETURN
497                    } else {
498                        width < BlockTokens::ACTIONS_COLLAPSE
499                    };
500                    if collapsed != s.collapsed {
501                        s.collapsed = collapsed;
502                        changed = true;
503                    }
504                }
505            });
506            if changed {
507                window.refresh();
508            }
509        });
510        let condensed = arc_spring(
511            (self.id.clone(), "header"),
512            if snap.condensed { 1.0 } else { 0.0 },
513            motion.spring.smooth,
514            w,
515            cx,
516        )
517        .clamp(0.0, 1.0);
518        let notice = self.on_notice.clone();
519        let archived = snap.archived;
520        let collapsed = snap.collapsed;
521        let following = snap.following;
522
523        // 上游:面包屑与紧凑标题共享同一单元格,收紧时交叉淡换。这里以透明度近似。
524        let chevron = || {
525            svg()
526                .path(IconName::ChevronRight.path())
527                .size(px(14.0))
528                .text_color(colors.border_strong)
529        };
530        let lead = if condensed < 0.5 {
531            div()
532                .flex()
533                .min_w(px(0.0))
534                .items_center()
535                .gap(Spacing::S1)
536                .opacity((1.0 - condensed * 2.0).clamp(0.0, 1.0))
537                .child(text("Northline", cx).text_color(colors.text_muted))
538                .child(chevron())
539                .child(text("Projects", cx).text_color(colors.text_muted))
540                .child(chevron())
541                .child(
542                    text(self.title.clone(), cx)
543                        .text_color(colors.text_secondary)
544                        .truncate(),
545                )
546        } else {
547            div()
548                .flex()
549                .min_w(px(0.0))
550                .items_center()
551                .gap(Spacing::S2)
552                .opacity(((condensed - 0.5) * 2.0).clamp(0.0, 1.0))
553                .child(
554                    Button::new(child_id(&self.id, "compact"))
555                        .label(self.title.clone())
556                        .accessibility_label(format!("{}, back to top", self.title))
557                        .size(ButtonSize::Sm)
558                        .variant(ButtonVariant::Ghost)
559                        .on_click({
560                            let st = state.clone();
561                            move |_, w, cx| {
562                                st.update(cx, |s, _| {
563                                    s.scroll.set_offset(gpui_kit::point(px(0.0), px(0.0)));
564                                    s.condensed = false;
565                                });
566                                w.refresh();
567                            }
568                        }),
569                )
570                .child(
571                    Badge::new(
572                        child_id(&self.id, "compact-status"),
573                        if archived { "Archived" } else { "On track" },
574                    )
575                    .tone(if archived {
576                        BadgeTone::Neutral
577                    } else {
578                        BadgeTone::Success
579                    }),
580                )
581        };
582        let mut actions = div().flex().flex_wrap().gap(Spacing::S2).items_center();
583        if !collapsed {
584            let follow_state = state.clone();
585            actions = actions.child(
586                Button::new(child_id(&self.id, "follow"))
587                    .label(if following { "Following" } else { "Follow" })
588                    .accessibility_label(if following {
589                        "Unfollow project"
590                    } else {
591                        "Follow project"
592                    })
593                    .selected(following)
594                    .size(ButtonSize::Sm)
595                    .variant(ButtonVariant::Secondary)
596                    .on_click(move |_, w, cx| toggle_follow(&follow_state, w, cx)),
597            );
598            let share_state = state.clone();
599            let sharing = snap.sharing;
600            actions = actions.child(
601                Button::new(child_id(&self.id, "share"))
602                    .label(match sharing {
603                        SharePhase::Sending => "Sharing…",
604                        SharePhase::Sent => "Shared",
605                        SharePhase::Idle => "Share update",
606                    })
607                    .loading(sharing == SharePhase::Sending)
608                    .disabled(archived || sharing != SharePhase::Idle)
609                    .size(ButtonSize::Sm)
610                    .variant(ButtonVariant::Secondary)
611                    .on_click(move |_, w, cx| share_update(&share_state, w, cx)),
612            );
613        }
614        let add_state = state.clone();
615        actions = actions.child(
616            Button::new(child_id(&self.id, "add-issue"))
617                .label("New issue")
618                .disabled(archived)
619                .size(ButtonSize::Sm)
620                .on_click(move |_, w, cx| create_issue(&add_state, w, cx)),
621        );
622        let copy_state = state.clone();
623        let project_url = self.project_url.clone();
624        let mut menu = DropdownMenu::new(child_id(&self.id, "more"), "More actions");
625        if collapsed {
626            let follow_state = state.clone();
627            menu = menu.item(
628                DropdownItem::new(if following { "Unfollow" } else { "Follow" })
629                    .on_select(move |_, w, cx| toggle_follow(&follow_state, w, cx)),
630            );
631            let share_state = state.clone();
632            menu = menu.item(
633                DropdownItem::new(match snap.sharing {
634                    SharePhase::Sending => "Sharing…",
635                    SharePhase::Sent => "Shared",
636                    SharePhase::Idle => "Share update",
637                })
638                .disabled(archived || snap.sharing != SharePhase::Idle)
639                .on_select(move |_, w, cx| share_update(&share_state, w, cx)),
640            );
641        }
642        menu = menu.item(
643            DropdownItem::new("Copy project link")
644                .separator_before(collapsed)
645                .disabled(project_url.is_none())
646                .on_select(move |_, w, cx| copy_link(&copy_state, project_url.as_ref(), w, cx)),
647        );
648        menu = menu.item(
649            DropdownItem::new(if archived {
650                "Restore project"
651            } else {
652                "Archive project"
653            })
654            .separator_before(true)
655            .on_select({
656                let archive_state = state.clone();
657                let notice = notice.clone();
658                move |_, w, cx| {
659                    toggle_archive(&archive_state, notice.as_ref(), w, cx);
660                }
661            }),
662        );
663        actions = actions.child(menu);
664        // intro 大标题区:收紧时随弹簧收起高度(上游 height: 0 ↔ auto)。
665        let intro = arc_spring(
666            (self.id.clone(), "intro"),
667            if snap.condensed { 0.0 } else { 1.0 },
668            motion.spring.smooth,
669            w,
670            cx,
671        )
672        .clamp(0.0, 1.0);
673        let member_row = AvatarGroup::new(child_id(&self.id, "members"))
674            .members(self.members.iter().map(|p| {
675                let member = AvatarGroupMember::new(p.name.clone());
676                match &p.photo {
677                    Some(photo) => member.src(photo.clone()),
678                    None => member,
679                }
680            }))
681            .max(4)
682            .size(AvatarSize::Sm)
683            .label("Project members");
684        root = root.child(
685            div()
686                .id(child_id(&self.id, "header"))
687                .pt(Spacing::S4)
688                .px(Spacing::S4)
689                .flex_none()
690                .child(
691                    div()
692                        .flex()
693                        .gap(Spacing::S4)
694                        .justify_between()
695                        .items_center()
696                        .child(div().flex_1().min_w(px(0.0)).child(lead))
697                        .child(actions),
698                )
699                .child(
700                    div()
701                        .overflow_hidden()
702                        .flex()
703                        .flex_col()
704                        .gap(Spacing::S2)
705                        .max_h(px(220.0 * intro))
706                        .pt(Spacing::S4)
707                        .when(intro > 0.02, |d| {
708                            d.child(
709                                div()
710                                    .flex()
711                                    .flex_wrap()
712                                    .items_center()
713                                    .gap(Spacing::S2)
714                                    .child(
715                                        div()
716                                            .text_size(Typography::TEXT_2XL)
717                                            .font_medium()
718                                            .child(self.title.clone()),
719                                    )
720                                    .child(
721                                        Badge::new(
722                                            child_id(&self.id, "status"),
723                                            if archived { "Archived" } else { "On track" },
724                                        )
725                                        .tone(
726                                            if archived {
727                                                BadgeTone::Neutral
728                                            } else {
729                                                BadgeTone::Success
730                                            },
731                                        ),
732                                    ),
733                            )
734                            .child(
735                                text(self.description.clone(), cx)
736                                    .text_color(colors.text_secondary),
737                            )
738                            .child(
739                                div()
740                                    .flex()
741                                    .flex_wrap()
742                                    .items_center()
743                                    .gap(Spacing::S4)
744                                    .child(member_row)
745                                    .child(
746                                        text("Led by Emma Collins", cx)
747                                            .text_color(colors.text_muted),
748                                    )
749                                    .child(text("Target Oct 14", cx).text_color(colors.text_muted)),
750                            )
751                        }),
752                ),
753        );
754        let sections = [
755            PageSection::Overview,
756            PageSection::Issues,
757            PageSection::Updates,
758            PageSection::Files,
759        ];
760        // 自绘页签:文字 + 计数 + 底部 2px accent 指示器。
761        // 上游指示器是每个激活 tab 内的绝对定位子元素(left/right 10px),
762        // 因此必须按单枚 tab 的真实边界定位与滑行(共享布局 FLIP),
763        // 不能按四等分比例铺在整条 tab 行上。
764        let tab_bounds = state.read(cx).tab_bounds.clone();
765        let selected_order = snap.section.order();
766        let indicator_scope = layout_scope_key(&self.id);
767        let indicator_morph = motion.spring.morph;
768        let indicator = canvas(
769            move |_, _, _| {},
770            move |list_rect, _, window, cx| {
771                let Some(tab_rect) = tab_bounds.borrow()[selected_order] else {
772                    window.request_animation_frame();
773                    return;
774                };
775                // 上游 .indicator:距 tab 左右各 10px,2px 高,顶部两角 2px 圆角。
776                let target = LayoutSnapshot::new(
777                    bounds(
778                        point(
779                            tab_rect.origin.x - list_rect.origin.x + px(10.0),
780                            tab_rect.origin.y - list_rect.origin.y + tab_rect.size.height - px(2.0),
781                        ),
782                        gpui_kit::size(tab_rect.size.width - px(20.0), px(2.0)),
783                    ),
784                    gpui_kit::Corners {
785                        top_left: px(2.0),
786                        top_right: px(2.0),
787                        bottom_right: px(0.0),
788                        bottom_left: px(0.0),
789                    },
790                );
791                let flip = sample_shared_layout(
792                    indicator_scope.clone(),
793                    "indicator",
794                    target,
795                    Some(indicator_morph),
796                    window,
797                    cx,
798                );
799                let paint = bounds(
800                    point(
801                        list_rect.origin.x + flip.bounds.origin.x,
802                        list_rect.origin.y + flip.bounds.origin.y,
803                    ),
804                    flip.bounds.size,
805                );
806                window.paint_quad(quad(
807                    paint,
808                    flip.corner_radii,
809                    colors.accent,
810                    Edges::default(),
811                    colors.accent,
812                    BorderStyle::Solid,
813                ));
814            },
815        );
816        let mut tabs = div()
817            .relative()
818            .flex()
819            .gap(Spacing::S1)
820            .mt(Spacing::S3)
821            .mx(-Spacing::S4)
822            .px(Spacing::S4 - Spacing::S2)
823            .border_b_1()
824            .border_color(colors.border)
825            .child(indicator);
826        for section in sections {
827            let count = match section {
828                PageSection::Issues => Some(snap.issues.len()),
829                PageSection::Updates => Some(snap.updates.len()),
830                PageSection::Files => Some(self.files.len()),
831                PageSection::Overview => None,
832            };
833            let selected = snap.section == section;
834            let st = state.clone();
835            let measured = state.read(cx).tab_bounds.clone();
836            let measure_index = section.order();
837            let measure = canvas(
838                move |bounds, _, _| {
839                    measured.borrow_mut()[measure_index] = Some(bounds);
840                },
841                |_, _, _, _| {},
842            )
843            .absolute()
844            .inset_0();
845            let mut tab = div()
846                .id(child_id(&self.id, format!("tab-{}", section.label())))
847                .test_support()
848                .role(Role::Tab)
849                .aria_selected(selected)
850                .aria_label(match count {
851                    Some(count) => format!("{} · {count}", section.label()),
852                    None => section.label().to_owned(),
853                })
854                .cursor_pointer()
855                .relative()
856                .h(px(44.0))
857                .px(Spacing::S2)
858                .flex()
859                .flex_none()
860                .items_center()
861                .gap(Spacing::S1)
862                .text_size(Typography::TEXT_SM)
863                .font_medium()
864                .whitespace_nowrap()
865                .text_color(if selected {
866                    colors.foreground
867                } else {
868                    colors.text_muted
869                })
870                .hover(move |s| s.text_color(colors.foreground))
871                .on_click(move |_, w, cx| {
872                    st.update(cx, |s, _| {
873                        if section != s.section {
874                            s.direction = if section.order() > s.section.order() {
875                                1.0
876                            } else {
877                                -1.0
878                            };
879                        }
880                        s.section = section;
881                        s.scroll.set_offset(gpui_kit::point(px(0.0), px(0.0)));
882                    });
883                    w.refresh();
884                })
885                .child(measure)
886                .child(section.label());
887            if let Some(count) = count {
888                tab = tab.child(
889                    text(count.to_string(), cx)
890                        .text_color(if selected {
891                            colors.text_secondary
892                        } else {
893                            colors.text_muted
894                        })
895                        .text_size(Typography::TEXT_SM),
896                );
897            }
898            tabs = tabs.child(tab);
899        }
900        root = root.child(tabs);
901        let scroll_state = state.clone();
902        let mut body = div()
903            .id(child_id(&self.id, "body"))
904            .test_support()
905            .p(Spacing::S6)
906            .flex_1()
907            .min_h(px(0.0))
908            .track_scroll(&snap.scroll)
909            .on_scroll(move |_, w, cx| {
910                scroll_state.update(cx, |s, _| {
911                    let top = -f32::from(s.scroll.offset().y);
912                    s.condensed = if s.condensed {
913                        top > BlockTokens::EXPAND_AT
914                    } else {
915                        top > BlockTokens::CONDENSE_AT
916                    };
917                });
918                w.refresh();
919            })
920            .overflow_y_scroll();
921        // 面板沿页签方向滑入;key 绑定 section,切换时从对应方向开始。
922        let slide = arc_spring_with_options(
923            (
924                child_id(&self.id, format!("panel-{}", snap.section.label())),
925                "slide",
926            ),
927            0.0,
928            SpringOptions::new(motion.spring.smooth).with_initial_value(snap.direction * 12.0),
929            w,
930            cx,
931        );
932        body = body.ml(px(slide.value));
933        match snap.section {
934            PageSection::Overview => {
935                body = body.child(
936                    Progress::new(child_id(&self.id, "progress"))
937                        .value(done as f32)
938                        .max((open + done).max(1) as f32)
939                        .label(format!("{done} of {} issues done", open + done))
940                        .show_value(true),
941                );
942                body = body.child(
943                    div()
944                        .id(child_id(&self.id, "milestones"))
945                        .role(Role::List)
946                        .aria_label("Milestones")
947                        .flex()
948                        .flex_col()
949                        .gap(Spacing::S1)
950                        .child(div().font_medium().child("Milestones"))
951                        .children(self.milestones.iter().map(|m| {
952                            let (glyph, color) = match m.state {
953                                MilestoneState::Done => ("✓", colors.success),
954                                MilestoneState::Active => ("◌", colors.accent),
955                                MilestoneState::Planned => ("○", colors.text_muted),
956                            };
957                            div()
958                                .id(child_id(&self.id, format!("milestone-{}", m.id)))
959                                .test_support()
960                                .role(Role::ListItem)
961                                .flex()
962                                .items_center()
963                                .gap(Spacing::S2)
964                                .child(div().text_color(color).child(glyph))
965                                .child(div().flex_1().child(m.name.clone()))
966                                .child(text(m.note.clone(), cx))
967                        })),
968                );
969                body = body.child(
970                    div()
971                        .id(child_id(&self.id, "activity"))
972                        .role(Role::List)
973                        .aria_label("Recent activity")
974                        .flex()
975                        .flex_col()
976                        .gap(Spacing::S2)
977                        .child(div().font_medium().child("Recent activity"))
978                        .children(self.activity.iter().map(|a| {
979                            div()
980                                .id(child_id(&self.id, format!("activity-{}", a.id)))
981                                .test_support()
982                                .role(Role::ListItem)
983                                .flex()
984                                .items_center()
985                                .gap(Spacing::S2)
986                                .child(avatar(
987                                    child_id(&self.id, format!("who-{}", a.id)),
988                                    &a.person,
989                                ))
990                                .child(
991                                    div()
992                                        .flex_1()
993                                        .child(format!("{} {}", a.person.name, a.text)),
994                                )
995                                .child(text(a.time.clone(), cx))
996                        })),
997                );
998            }
999            PageSection::Issues => {
1000                body = body.role(Role::List).aria_label("Open issues");
1001                let has_issues = !snap.issues.is_empty();
1002                let all_closing =
1003                    !has_issues || snap.issues.iter().all(|i| snap.closing.contains(&i.id));
1004                for issue in snap.issues {
1005                    let issue_state = state.clone();
1006                    let key = issue.id.clone();
1007                    let issue_id = issue.id.clone();
1008                    let issue_title = issue.title.clone();
1009                    let closing = snap.closing.contains(&issue.id);
1010                    let id = child_id(&self.id, format!("issue-{}", issue.id));
1011                    // 完成后行高随退场弹簧收起,380ms 后再从列表移除并累加进度。
1012                    let presence = ArcPresence::new((id.clone(), "row"), !closing)
1013                        .animate_initial(false)
1014                        .config(ArcPresenceConfig {
1015                            enter_duration: motion.duration.standard,
1016                            exit_duration: Duration::from_millis(380),
1017                            enter_ease: motion.ease.enter,
1018                            exit_ease: motion.ease.standard,
1019                            fade_on_reduced_motion: true,
1020                        })
1021                        .sample(w, cx);
1022                    if !presence.should_render() {
1023                        continue;
1024                    }
1025                    let cb = self.on_notice.clone();
1026                    let mut row = div()
1027                        .id(id)
1028                        .role(Role::ListItem)
1029                        .opacity(presence.progress)
1030                        .max_h(BlockTokens::ROW_HEIGHT * presence.progress)
1031                        .overflow_hidden()
1032                        .flex()
1033                        .items_center()
1034                        .gap(Spacing::S2)
1035                        .p(Spacing::S2)
1036                        .child(
1037                            Button::new(child_id(&self.id, format!("check-{}", issue.id)))
1038                                .label(if closing { "✓" } else { "○" })
1039                                .accessibility_label(format!(
1040                                    "Mark {} {}",
1041                                    issue.title,
1042                                    if closing { "open" } else { "done" }
1043                                ))
1044                                .disabled(closing)
1045                                .size(ButtonSize::Sm)
1046                                .variant(ButtonVariant::Ghost)
1047                                .on_click(move |_, w, cx| {
1048                                    let now = motion_now(cx);
1049                                    let first = issue_state.update(cx, |s, _| {
1050                                        if s.closing.contains(&key) {
1051                                            return false;
1052                                        }
1053                                        s.closing.push(key.clone());
1054                                        s.notify(
1055                                            format!("{key} marked done"),
1056                                            NoticeTone::Success,
1057                                            now,
1058                                        );
1059                                        true
1060                                    });
1061                                    if !first {
1062                                        return;
1063                                    }
1064                                    let weak = issue_state.downgrade();
1065                                    let removal = issue_id.clone();
1066                                    w.spawn(cx, async move |cx| {
1067                                        cx.background_executor()
1068                                            .timer(Duration::from_millis(380))
1069                                            .await;
1070                                        let _ = cx.update(|w, cx| {
1071                                            let _ = weak.update(cx, |s, _| {
1072                                                s.issues.retain(|i| i.id != removal);
1073                                                s.closing.retain(|c| c != &removal);
1074                                                s.done_count += 1;
1075                                            });
1076                                            w.refresh();
1077                                        });
1078                                    })
1079                                    .detach();
1080                                    if let Some(cb) = &cb {
1081                                        cb(format!("{} marked done", issue_id).into(), w, cx)
1082                                    }
1083                                    w.refresh();
1084                                }),
1085                        )
1086                        .child(
1087                            div()
1088                                .text_color(colors.text_muted)
1089                                .child(issue_title.clone()),
1090                        )
1091                        .child(div().flex_1().child(issue_title));
1092                    if let Some(label) = issue.label.clone() {
1093                        row = row.child(Badge::new(
1094                            child_id(&self.id, format!("label-{}", issue.id)),
1095                            label,
1096                        ));
1097                    }
1098                    if let Some(owner) = issue.owner.as_ref() {
1099                        row = row.child(avatar(
1100                            child_id(&self.id, format!("owner-{}", issue.id)),
1101                            owner,
1102                        ));
1103                    }
1104                    body = body.child(row);
1105                }
1106                if all_closing {
1107                    let st = state.clone();
1108                    body = body.child(
1109                        div()
1110                            .id(child_id(&self.id, "empty-issues"))
1111                            .test_support()
1112                            .flex()
1113                            .flex_col()
1114                            .items_center()
1115                            .gap(Spacing::S2)
1116                            .p(Spacing::S6)
1117                            .child(div().font_medium().child("No open issues"))
1118                            .child(text("Everything in this project is done.", cx))
1119                            .child(
1120                                Button::new(child_id(&self.id, "restore-issues"))
1121                                    .label("Restore sample issues")
1122                                    .size(ButtonSize::Sm)
1123                                    .variant(ButtonVariant::Secondary)
1124                                    .on_click(move |_, w, cx| {
1125                                        let now = motion_now(cx);
1126                                        st.update(cx, |s, _| {
1127                                            s.issues = s
1128                                                .sample
1129                                                .iter()
1130                                                .filter(|i| !i.done)
1131                                                .cloned()
1132                                                .collect();
1133                                            s.done_count =
1134                                                s.sample.iter().filter(|i| i.done).count() as u32;
1135                                            s.closing.clear();
1136                                            s.notify(
1137                                                "Sample issues restored",
1138                                                NoticeTone::Neutral,
1139                                                now,
1140                                            );
1141                                        });
1142                                        w.refresh();
1143                                    }),
1144                            ),
1145                    );
1146                }
1147            }
1148            PageSection::Updates => {
1149                body = body.role(Role::List);
1150                if snap.updates.is_empty() {
1151                    body = body.child(text("No project updates yet", cx));
1152                }
1153                for update in snap.updates {
1154                    let mut head = div()
1155                        .flex()
1156                        .items_center()
1157                        .gap(Spacing::S2)
1158                        .child(div().font_medium().child(update.author.name.clone()))
1159                        .child(text(update.date.clone(), cx));
1160                    if let Some(status) = update.status.clone() {
1161                        head = head.child(
1162                            Badge::new(child_id(&self.id, format!("status-{}", update.id)), status)
1163                                .tone(update.tone),
1164                        );
1165                    }
1166                    body = body.child(
1167                        div()
1168                            .id(child_id(&self.id, format!("update-{}", update.id)))
1169                            .test_support()
1170                            .role(Role::ListItem)
1171                            .p(Spacing::S3)
1172                            .flex()
1173                            .gap(Spacing::S3)
1174                            .child(avatar(
1175                                child_id(&self.id, format!("author-{}", update.id)),
1176                                &update.author,
1177                            ))
1178                            .child(
1179                                div()
1180                                    .flex_1()
1181                                    .flex()
1182                                    .flex_col()
1183                                    .gap(Spacing::S1)
1184                                    .child(head)
1185                                    .child(text(update.body, cx)),
1186                            ),
1187                    );
1188                }
1189            }
1190            PageSection::Files => {
1191                body = body.role(Role::List);
1192                if self.files.is_empty() {
1193                    body = body.child(text("No project files", cx));
1194                }
1195                for file in self.files {
1196                    body = body.child(
1197                        div()
1198                            .id(child_id(&self.id, format!("file-{}", file.id)))
1199                            .test_support()
1200                            .role(Role::ListItem)
1201                            .p(Spacing::S3)
1202                            .flex()
1203                            .items_center()
1204                            .gap(Spacing::S3)
1205                            .child(div().text_color(colors.text_secondary).child("▤"))
1206                            .child(
1207                                div()
1208                                    .flex_1()
1209                                    .flex()
1210                                    .flex_col()
1211                                    .child(div().font_medium().child(file.name))
1212                                    .child(text(format!("{} · {}", file.kind, file.size), cx)),
1213                            )
1214                            .when_some(file.owner.as_ref(), |d, owner| {
1215                                d.child(avatar(
1216                                    child_id(&self.id, format!("owner-{}", file.id)),
1217                                    owner,
1218                                ))
1219                            })
1220                            .when_some(file.date, |d, date| d.child(text(date, cx))),
1221                    );
1222                }
1223            }
1224        }
1225        let notice_live = (now - snap.notice_at) < 3.2 && !snap.notice.is_empty();
1226        if notice_live {
1227            w.request_animation_frame();
1228        }
1229        let tone = snap.notice_tone;
1230        let toast_color = match tone {
1231            NoticeTone::Success => colors.success,
1232            NoticeTone::Neutral => colors.text_secondary,
1233        };
1234        root.child(body.child(div().min_h(BlockTokens::PAGE_BODY_MIN)))
1235            .child(
1236                div()
1237                    .id(child_id(&self.id, "notice"))
1238                    .role(Role::Status)
1239                    .child(snap.notice.clone())
1240                    .when(notice_live, |d| {
1241                        d.absolute()
1242                            .bottom(Spacing::S4)
1243                            .left(Spacing::S4)
1244                            .flex()
1245                            .items_center()
1246                            .gap(Spacing::S2)
1247                            .px(Spacing::S4)
1248                            .py(Spacing::S2)
1249                            .rounded(Radii::PANEL)
1250                            .border_1()
1251                            .border_color(colors.border)
1252                            .bg(colors.surface_raised)
1253                            .text_color(colors.foreground)
1254                            .child(div().text_color(toast_color).child(tone.glyph()))
1255                            .child(snap.notice.clone())
1256                    }),
1257            )
1258            .child(
1259                div()
1260                    .id(child_id(&self.id, "members-sr"))
1261                    .role(Role::Status)
1262                    .aria_label(format!("{} project members", self.members.len()))
1263                    .opacity(0.0)
1264                    .child(self.members.len().to_string()),
1265            )
1266    }
1267}
1268fn toggle_follow(state: &gpui_kit::Entity<State>, w: &mut Window, cx: &mut App) {
1269    let now = motion_now(cx);
1270    state.update(cx, |s, _| {
1271        s.following = !s.following;
1272        let message = if s.following {
1273            "Following project"
1274        } else {
1275            "Stopped following project"
1276        };
1277        s.notify(message, NoticeTone::Success, now);
1278    });
1279    w.refresh();
1280}
1281fn share_update(state: &gpui_kit::Entity<State>, w: &mut Window, cx: &mut App) {
1282    if state.read(cx).sharing != SharePhase::Idle {
1283        return;
1284    }
1285    let now = motion_now(cx);
1286    state.update(cx, |s, _| {
1287        s.sharing = SharePhase::Sending;
1288        s.notify("Sharing update…", NoticeTone::Neutral, now);
1289    });
1290    let weak = state.downgrade();
1291    w.spawn(cx, async move |cx| {
1292        cx.background_executor()
1293            .timer(Duration::from_millis(700))
1294            .await;
1295        let _ = cx.update(|w, cx| {
1296            let now = motion_now(cx);
1297            let _ = weak.update(cx, |s, _| {
1298                s.serial += 1;
1299                let key: SharedString = format!("local-update-{}", s.serial).into();
1300                s.updates.insert(
1301                    0,
1302                    PageUpdate::new(
1303                        key,
1304                        "You",
1305                        "Just now",
1306                        "Local project update shared with the preview team.",
1307                    )
1308                    .status("On track", BadgeTone::Success),
1309                );
1310                if s.section != PageSection::Updates {
1311                    s.direction = if PageSection::Updates.order() > s.section.order() {
1312                        1.0
1313                    } else {
1314                        -1.0
1315                    };
1316                }
1317                s.section = PageSection::Updates;
1318                s.sharing = SharePhase::Sent;
1319                s.notify(
1320                    "Local update shared; no request sent",
1321                    NoticeTone::Success,
1322                    now,
1323                );
1324            });
1325            w.refresh();
1326        });
1327        cx.background_executor()
1328            .timer(Duration::from_millis(1800))
1329            .await;
1330        let _ = cx.update(|w, cx| {
1331            let _ = weak.update(cx, |s, _| {
1332                if s.sharing == SharePhase::Sent {
1333                    s.sharing = SharePhase::Idle;
1334                }
1335            });
1336            w.refresh();
1337        });
1338    })
1339    .detach();
1340    w.refresh();
1341}
1342fn create_issue(state: &gpui_kit::Entity<State>, w: &mut Window, cx: &mut App) {
1343    let now = motion_now(cx);
1344    state.update(cx, |s, _| {
1345        s.serial += 1;
1346        let key: SharedString = format!("local-issue-{}", s.serial).into();
1347        s.issues
1348            .push(PageIssue::new(key, "Review the next project task"));
1349        if s.section != PageSection::Issues {
1350            s.direction = if PageSection::Issues.order() > s.section.order() {
1351                1.0
1352            } else {
1353                -1.0
1354            };
1355        }
1356        s.section = PageSection::Issues;
1357        s.notify("Local issue created", NoticeTone::Success, now);
1358    });
1359    w.refresh();
1360}
1361fn copy_link(
1362    state: &gpui_kit::Entity<State>,
1363    url: Option<&SharedString>,
1364    w: &mut Window,
1365    cx: &mut App,
1366) {
1367    let Some(url) = url else { return };
1368    cx.write_to_clipboard(gpui_kit::ClipboardItem::new_string(url.to_string()));
1369    let now = motion_now(cx);
1370    state.update(cx, |s, _| s.notify("Link copied", NoticeTone::Success, now));
1371    w.refresh();
1372}
1373fn toggle_archive(
1374    state: &gpui_kit::Entity<State>,
1375    notice: Option<&Notice>,
1376    w: &mut Window,
1377    cx: &mut App,
1378) {
1379    let now = motion_now(cx);
1380    let mut archived = false;
1381    state.update(cx, |s, _| {
1382        s.archived = !s.archived;
1383        archived = s.archived;
1384        let message = if archived {
1385            "Project archived"
1386        } else {
1387            "Project restored"
1388        };
1389        s.notify(message, NoticeTone::Neutral, now);
1390    });
1391    w.refresh();
1392    if let Some(cb) = notice {
1393        cb(
1394            if archived {
1395                "Project archived"
1396            } else {
1397                "Project restored"
1398            }
1399            .into(),
1400            w,
1401            cx,
1402        )
1403    }
1404}
1405#[cfg(test)]
1406mod tests {
1407    use super::*;
1408    #[test]
1409    fn sections_are_distinct() {
1410        assert_ne!(PageSection::Issues, PageSection::Files);
1411        assert!(PageSection::Files.order() > PageSection::Overview.order());
1412    }
1413}