rgpui 1.3.0

GUI UI framework
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
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
//! 可调整大小的面板组:带拖拽手柄的多面板分栏布局。

use std::{cell::Cell, ops::Range, rc::Rc};

use crate::{prelude::FluentBuilder as _, *};

/// 面板最小尺寸。
const PANEL_MIN_SIZE: Pixels = px(100.0);
/// 手柄内边距(扩展热区)。
const HANDLE_PADDING: Pixels = px(4.0);
/// 手柄厚度。
const HANDLE_SIZE: Pixels = px(1.0);

/// 创建水平可调整大小的面板组。
pub fn h_resizable(id: impl Into<ElementId>, state: Entity<ResizableState>) -> ResizablePanelGroup {
    ResizablePanelGroup::new(id, state).axis(Axis::Horizontal)
}

/// 创建垂直可调整大小的面板组。
pub fn v_resizable(id: impl Into<ElementId>, state: Entity<ResizableState>) -> ResizablePanelGroup {
    ResizablePanelGroup::new(id, state).axis(Axis::Vertical)
}

/// 创建一个可调整大小的面板。
pub fn resizable_panel() -> ResizablePanel {
    ResizablePanel::new()
}

/// 面板调整事件。
#[derive(Clone, Debug)]
pub enum ResizablePanelEvent {
    /// 面板尺寸变化。
    Resized {
        /// 面板索引。
        panel_index: usize,
        /// 新尺寸。
        new_size: Pixels,
    },
}

/// 可调整大小的面板组状态。
#[derive(Debug, Clone)]
pub struct ResizableState {
    /// 排列轴。
    axis: Axis,
    /// 面板状态列表。
    panels: Vec<ResizablePanelState>,
    /// 面板尺寸列表。
    sizes: Vec<Pixels>,
    /// 正在拖拽调整的面板索引。
    resizing_panel_ix: Option<usize>,
    /// 容器边界。
    bounds: Bounds<Pixels>,
}

impl ResizableState {
    /// 创建状态实体。
    pub fn new(cx: &mut App) -> Entity<Self> {
        cx.new(|_| Self {
            axis: Axis::Horizontal,
            panels: vec![],
            sizes: vec![],
            resizing_panel_ix: None,
            bounds: Bounds::default(),
        })
    }

    /// 插入一个面板。
    pub fn insert_panel(
        &mut self,
        size: Option<Pixels>,
        index: Option<usize>,
        cx: &mut Context<Self>,
    ) {
        let panel_state = ResizablePanelState {
            size,
            ..Default::default()
        };

        if let Some(index) = index {
            self.panels.insert(index, panel_state);
            self.sizes.insert(index, size.unwrap_or(PANEL_MIN_SIZE));
        } else {
            self.panels.push(panel_state);
            self.sizes.push(size.unwrap_or(PANEL_MIN_SIZE));
        }

        cx.notify();
    }

    /// 移除指定索引的面板。
    pub fn remove_panel(&mut self, index: usize, cx: &mut Context<Self>) {
        if index >= self.panels.len() {
            return;
        }

        self.panels.remove(index);
        self.sizes.remove(index);

        if let Some(resizing_ix) = self.resizing_panel_ix {
            if resizing_ix > index {
                self.resizing_panel_ix = Some(resizing_ix - 1);
            } else if resizing_ix == index {
                self.resizing_panel_ix = None;
            }
        }

        cx.notify();
    }

    /// 获取面板尺寸列表。
    pub fn sizes(&self) -> &Vec<Pixels> {
        &self.sizes
    }

    /// 获取所有面板尺寸之和。
    pub fn total_size(&self) -> Pixels {
        self.sizes.iter().fold(px(0.0), |acc, &size| acc + size)
    }

    /// 清空所有面板。
    pub fn clear(&mut self) {
        self.panels.clear();
        self.sizes.clear();
    }

    /// 同步面板数量(渲染时根据子元素数量补齐)。
    fn sync_panels_count(&mut self, axis: Axis, panels_count: usize) {
        self.axis = axis;

        if panels_count > self.panels.len() {
            let diff = panels_count - self.panels.len();
            self.panels
                .extend(vec![ResizablePanelState::default(); diff]);
            self.sizes.extend(vec![PANEL_MIN_SIZE; diff]);
        }
    }

    /// 更新面板尺寸与边界。
    fn update_panel_size(
        &mut self,
        index: usize,
        bounds: Bounds<Pixels>,
        size_range: Range<Pixels>,
        cx: &mut Context<Self>,
    ) {
        if index >= self.panels.len() {
            return;
        }

        let size = bounds.size.along(self.axis);
        self.sizes[index] = size;
        self.panels[index].size = Some(size);
        self.panels[index].bounds = bounds;
        self.panels[index].size_range = size_range;

        cx.notify();
    }

    /// 结束拖拽调整,派发 Resized 事件。
    fn done_resizing(&mut self, cx: &mut Context<Self>) {
        if let Some(index) = self.resizing_panel_ix {
            let new_size = self.sizes.get(index).copied().unwrap_or(PANEL_MIN_SIZE);

            cx.emit(ResizablePanelEvent::Resized {
                panel_index: index,
                new_size,
            });
        }

        self.resizing_panel_ix = None;
    }

    /// 获取面板的尺寸约束范围。
    fn panel_size_range(&self, index: usize) -> Range<Pixels> {
        self.panels
            .get(index)
            .map(|p| p.size_range.clone())
            .unwrap_or(PANEL_MIN_SIZE..Pixels::MAX)
    }

    /// 把面板实际渲染尺寸同步回 sizes 列表。
    fn sync_real_panel_sizes(&mut self, _: &App) {
        for (i, panel) in self.panels.iter().enumerate() {
            if i < self.sizes.len() {
                self.sizes[i] = panel.bounds.size.along(self.axis).floor();
            }
        }
    }

    /// 调整面板尺寸,把增/减量扩散到相邻面板。
    fn resize_panel(&mut self, index: usize, size: Pixels, _: &mut Window, cx: &mut Context<Self>) {
        let old_sizes = self.sizes.clone();

        if index >= old_sizes.len() - 1 {
            return;
        }

        let size = size.floor();
        let container_size = self.bounds.size.along(self.axis);

        self.sync_real_panel_sizes(cx);

        let move_changed = size - old_sizes[index];
        if move_changed == px(0.0) {
            return;
        }

        let size_range = self.panel_size_range(index);
        let new_size = size.clamp(size_range.start, size_range.end);
        let is_expand = move_changed > px(0.0);

        let main_ix = index;
        let mut new_sizes = old_sizes.clone();
        let mut ix = index;

        if is_expand {
            let mut changed = new_size - old_sizes[index];
            new_sizes[index] = new_size;

            while changed > px(0.0) && ix < old_sizes.len() - 1 {
                ix += 1;
                let size_range = self.panel_size_range(ix);
                let available_size = (new_sizes[ix] - size_range.start).max(px(0.0));
                let to_reduce = changed.min(available_size);
                new_sizes[ix] -= to_reduce;
                changed -= to_reduce;
            }
        } else {
            let mut changed = old_sizes[index] - new_size;
            new_sizes[index + 1] += changed;
            new_sizes[index] = new_size;

            let right_size_range = self.panel_size_range(index + 1);
            if new_sizes[index + 1] > right_size_range.end {
                let overflow = new_sizes[index + 1] - right_size_range.end;
                new_sizes[index + 1] = right_size_range.end;
                changed = overflow;

                while changed > px(0.0) && ix > 0 {
                    ix -= 1;
                    let size_range = self.panel_size_range(ix);
                    let available_size = (new_sizes[ix] - size_range.start).max(px(0.0));
                    let to_reduce = changed.min(available_size);
                    changed -= to_reduce;
                    new_sizes[ix] -= to_reduce;
                }
            }
        }

        let total_size: Pixels = new_sizes.iter().fold(px(0.0), |acc, &size| acc + size);
        if total_size > container_size {
            let overflow = total_size - container_size;
            let size_range = self.panel_size_range(main_ix);
            new_sizes[main_ix] = (new_sizes[main_ix] - overflow).max(size_range.start);
        }

        for (i, _) in old_sizes.iter().enumerate() {
            if i < new_sizes.len() && i < self.panels.len() {
                let size = new_sizes[i];
                self.panels[i].size = Some(size);
            }
        }

        self.sizes = new_sizes;
        cx.notify();
    }
}

impl EventEmitter<ResizablePanelEvent> for ResizableState {}

/// 单个面板的运行时状态。
#[derive(Debug, Clone, Default)]
struct ResizablePanelState {
    /// 当前尺寸。
    size: Option<Pixels>,
    /// 尺寸约束范围。
    size_range: Range<Pixels>,
    /// 面板边界。
    bounds: Bounds<Pixels>,
}

/// 可调整大小的面板组:多个面板之间带拖拽手柄。
#[derive(IntoElement)]
pub struct ResizablePanelGroup {
    /// 元素 ID。
    id: ElementId,
    /// 绑定状态实体。
    state: Entity<ResizableState>,
    /// 排列轴。
    axis: Axis,
    /// 面板子元素列表。
    children: Vec<ResizablePanel>,
}

impl ResizablePanelGroup {
    /// 创建面板组。
    fn new(id: impl Into<ElementId>, state: Entity<ResizableState>) -> Self {
        Self {
            id: id.into(),
            axis: Axis::Horizontal,
            children: vec![],
            state,
        }
    }

    /// 设置排列轴。
    pub fn axis(mut self, axis: Axis) -> Self {
        self.axis = axis;
        self
    }

    /// 追加一个面板。
    pub fn child(mut self, panel: impl Into<ResizablePanel>) -> Self {
        self.children.push(panel.into());
        self
    }

    /// 追加一组面板。
    pub fn children<I>(mut self, panels: impl IntoIterator<Item = I>) -> Self
    where
        I: Into<ResizablePanel>,
    {
        self.children = panels.into_iter().map(|panel| panel.into()).collect();
        self
    }

    /// 把另一个面板组作为子面板嵌套进来。
    pub fn group(self, group: ResizablePanelGroup) -> Self {
        self.child(resizable_panel().child(group.into_any_element()))
    }
}

impl<T> From<T> for ResizablePanel
where
    T: Into<AnyElement>,
{
    fn from(value: T) -> Self {
        resizable_panel().child(value.into())
    }
}

impl EventEmitter<ResizablePanelEvent> for ResizablePanelGroup {}

impl RenderOnce for ResizablePanelGroup {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        let state = self.state.clone();

        let panels_count = self.children.len();
        self.state.update(cx, |state, _| {
            state.sync_panels_count(self.axis, panels_count);
        });

        let container = div()
            .id(self.id)
            .flex()
            .size_full()
            .when(self.axis.is_horizontal(), |this| this.flex_row())
            .when(self.axis.is_vertical(), |this| this.flex_col());

        container
            .children(
                self.children
                    .into_iter()
                    .enumerate()
                    .map(|(index, mut panel)| {
                        panel.index = index;
                        panel.axis = self.axis;
                        panel.state = Some(self.state.clone());
                        panel
                    }),
            )
            .child({
                canvas(
                    move |bounds, _, cx| {
                        state.update(cx, |state, _| {
                            state.bounds = bounds;
                        })
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .size_full()
            })
            .child(ResizePanelGroupElement {
                state: self.state.clone(),
                axis: self.axis,
            })
    }
}

/// 可调整大小的面板组中的单个面板。
#[derive(IntoElement)]
pub struct ResizablePanel {
    /// 排列轴。
    axis: Axis,
    /// 面板索引(渲染时由组设置)。
    index: usize,
    /// 所属组的状态。
    state: Option<Entity<ResizableState>>,
    /// 初始尺寸。
    initial_size: Option<Pixels>,
    /// 尺寸约束范围。
    size_range: Range<Pixels>,
    /// 子元素列表。
    children: Vec<AnyElement>,
    /// 是否可见。
    visible: bool,
    /// 用户样式。
    style: StyleRefinement,
}

impl ResizablePanel {
    /// 创建面板。
    fn new() -> Self {
        Self {
            index: 0,
            initial_size: None,
            state: None,
            size_range: (PANEL_MIN_SIZE..Pixels::MAX),
            axis: Axis::Horizontal,
            children: vec![],
            visible: true,
            style: StyleRefinement::default(),
        }
    }

    /// 添加子内容。
    pub fn child(mut self, child: impl IntoElement) -> Self {
        self.children.push(child.into_any_element());
        self
    }

    /// 设置可见性。
    pub fn visible(mut self, visible: bool) -> Self {
        self.visible = visible;
        self
    }

    /// 设置初始尺寸。
    pub fn size(mut self, size: impl Into<Pixels>) -> Self {
        self.initial_size = Some(size.into());
        self
    }

    /// 设置尺寸约束范围。
    pub fn size_range(mut self, range: impl Into<Range<Pixels>>) -> Self {
        self.size_range = range.into();
        self
    }

    /// 设置最小尺寸。
    pub fn min_size(mut self, min: impl Into<Pixels>) -> Self {
        self.size_range.start = min.into();
        self
    }

    /// 设置最大尺寸。
    pub fn max_size(mut self, max: impl Into<Pixels>) -> Self {
        self.size_range.end = max.into();
        self
    }
}

impl Styled for ResizablePanel {
    fn style(&mut self) -> &mut StyleRefinement {
        &mut self.style
    }
}

impl RenderOnce for ResizablePanel {
    fn render(self, _: &mut Window, cx: &mut App) -> impl IntoElement {
        if !self.visible {
            return div().id(("resizable-panel", self.index)).into_any_element();
        }

        let state = self
            .state
            .as_ref()
            .expect("ResizablePanel must be used within a ResizablePanelGroup");

        let panel_state = state.read(cx).panels.get(self.index).cloned();

        let size_range = self.size_range.clone();
        let has_custom_size =
            self.initial_size.is_some() || panel_state.as_ref().and_then(|p| p.size).is_some();

        let mut panel_div = div()
            .id(("resizable-panel", self.index))
            .flex()
            .flex_grow_1()
            .size_full()
            .relative();

        panel_div = panel_div.when(self.axis.is_vertical(), |this| {
            this.min_h(size_range.start).max_h(size_range.end)
        });

        panel_div = panel_div.when(self.axis.is_horizontal(), |this| {
            this.min_w(size_range.start).max_w(size_range.end)
        });

        panel_div = panel_div.when(!has_custom_size, |this| this.flex_shrink());

        if let Some(initial_size) = self.initial_size {
            let should_use_flex_none = panel_state
                .as_ref()
                .map(|p| p.size.is_none() && !initial_size.is_zero())
                .unwrap_or(false);

            panel_div = panel_div
                .when(should_use_flex_none, |this| this.flex_none())
                .flex_basis(initial_size);
        }

        if let Some(panel_state) = panel_state.as_ref() {
            if let Some(size) = panel_state.size {
                panel_div = panel_div.flex_basis(size);
            }
        }

        let user_style = self.style;

        panel_div.style().refine(&user_style);
        panel_div
            .children(self.children)
            .when(self.index > 0, |this| {
                let handle_index = self.index - 1;
                let state = state.clone();

                this.child(ResizeHandle::new(
                    ("resizable-handle", handle_index),
                    self.axis,
                    DragPanel,
                    move |drag_panel, _, _, cx| {
                        cx.stop_propagation();
                        state.update(cx, |state, _| {
                            state.resizing_panel_ix = Some(handle_index);
                        });
                        cx.new(|_| (*drag_panel).clone())
                    },
                ))
            })
            .child({
                let state = state.clone();
                let index = self.index;
                let size_range = self.size_range.clone();

                canvas(
                    move |bounds, _, cx| {
                        state.update(cx, |state, cx| {
                            state.update_panel_size(index, bounds, size_range.clone(), cx)
                        })
                    },
                    |_, _, _, _| {},
                )
                .absolute()
                .size_full()
            })
            .into_any_element()
    }
}

/// 拖拽中的占位渲染实体。
#[derive(Clone)]
struct DragPanel;

impl Render for DragPanel {
    fn render(&mut self, _: &mut Window, _: &mut Context<'_, Self>) -> impl IntoElement {
        Empty
    }
}

/// 自定义手柄元素:覆盖在面板间隙上的拖拽热区。
struct ResizeHandle<T: 'static, E: 'static + Render> {
    /// 元素 ID。
    id: ElementId,
    /// 排列轴。
    axis: Axis,
    /// 拖拽值。
    drag_value: Rc<T>,
    /// 拖拽回调(返回拖拽中的渲染实体)。
    on_drag: Rc<dyn Fn(Rc<T>, &Point<Pixels>, &mut Window, &mut App) -> Entity<E>>,
}

impl<T: 'static, E: 'static + Render> ResizeHandle<T, E> {
    /// 创建手柄。
    fn new(
        id: impl Into<ElementId>,
        axis: Axis,
        value: T,
        f: impl Fn(Rc<T>, &Point<Pixels>, &mut Window, &mut App) -> Entity<E> + 'static,
    ) -> Self {
        Self {
            id: id.into(),
            axis,
            drag_value: Rc::new(value),
            on_drag: Rc::new(f),
        }
    }
}

/// 手柄的激活状态(用 Cell 跨事件共享)。
#[derive(Default, Debug, Clone)]
struct ResizeHandleState {
    /// 是否激活(按下)。
    active: Cell<bool>,
}

impl ResizeHandleState {
    /// 设置激活状态。
    fn set_active(&self, active: bool) {
        self.active.set(active);
    }

    /// 是否激活。
    fn is_active(&self) -> bool {
        self.active.get()
    }
}

impl<T: 'static, E: 'static + Render> IntoElement for ResizeHandle<T, E> {
    type Element = ResizeHandle<T, E>;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl<T: 'static, E: 'static + Render> Element for ResizeHandle<T, E> {
    type RequestLayoutState = AnyElement;
    type PrepaintState = ();

    fn id(&self) -> Option<ElementId> {
        Some(self.id.clone())
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        id: Option<&GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (crate::LayoutId, Self::RequestLayoutState) {
        let neg_offset = -HANDLE_PADDING;
        let axis = self.axis;
        // 提前提取主题色,避免在 with_element_state 闭包内借用 cx。
        let theme = cx.theme();
        let accent = theme.tokens.accent;
        let border = theme.tokens.border;

        window.with_element_state(id.unwrap(), |state, window| {
            let state = state.unwrap_or_else(ResizeHandleState::default);

            let bg_color = if state.is_active() { accent } else { border };

            let mut handle_element = div()
                .id(self.id.clone())
                .occlude()
                .absolute()
                .flex_shrink_0()
                .group("handle");

            let on_drag = self.on_drag.clone();
            let drag_value = self.drag_value.clone();
            handle_element = handle_element
                .on_drag(drag_value.clone(), move |_, position, window, cx| {
                    (on_drag)(drag_value.clone(), &position, window, cx)
                });

            handle_element = match axis {
                Axis::Horizontal => handle_element
                    .cursor_col_resize()
                    .top_0()
                    .left(neg_offset)
                    .h_full()
                    .w(HANDLE_SIZE)
                    .px(HANDLE_PADDING),
                Axis::Vertical => handle_element
                    .cursor_row_resize()
                    .top(neg_offset)
                    .left_0()
                    .w_full()
                    .h(HANDLE_SIZE)
                    .py(HANDLE_PADDING),
            };

            handle_element = handle_element.child(
                div()
                    .bg(bg_color)
                    .group_hover("handle", |this| this.bg(accent))
                    .when(axis.is_horizontal(), |this| this.h_full().w(HANDLE_SIZE))
                    .when(axis.is_vertical(), |this| this.w_full().h(HANDLE_SIZE)),
            );

            let mut el = handle_element.into_any_element();
            let layout_id = el.request_layout(window, cx);

            ((layout_id, el), state)
        })
    }

    fn prepaint(
        &mut self,
        _: Option<&GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        _: crate::Bounds<Pixels>,
        request_layout: &mut Self::RequestLayoutState,
        window: &mut Window,
        cx: &mut App,
    ) -> Self::PrepaintState {
        request_layout.prepaint(window, cx);
    }

    fn paint(
        &mut self,
        id: Option<&GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        bounds: crate::Bounds<Pixels>,
        request_layout: &mut Self::RequestLayoutState,
        _: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        request_layout.paint(window, cx);

        window.with_element_state(id.unwrap(), |state: Option<ResizeHandleState>, window| {
            let state = state.unwrap_or_else(ResizeHandleState::default);

            window.on_mouse_event({
                let state = state.clone();
                move |event: &MouseDownEvent, phase, window, _| {
                    if bounds.contains(&event.position) && phase.bubble() {
                        state.set_active(true);
                        window.refresh();
                    }
                }
            });

            window.on_mouse_event({
                let state = state.clone();
                move |_: &MouseUpEvent, _, window, _| {
                    if state.is_active() {
                        state.set_active(false);
                        window.refresh();
                    }
                }
            });

            ((), state)
        });
    }
}

/// 面板组根元素:在布局阶段挂载滚轮移动/松开事件监听。
struct ResizePanelGroupElement {
    /// 绑定状态实体。
    state: Entity<ResizableState>,
    /// 排列轴。
    axis: Axis,
}

impl IntoElement for ResizePanelGroupElement {
    type Element = Self;

    fn into_element(self) -> Self::Element {
        self
    }
}

impl Element for ResizePanelGroupElement {
    type RequestLayoutState = ();
    type PrepaintState = ();

    fn id(&self) -> Option<crate::ElementId> {
        None
    }

    fn source_location(&self) -> Option<&'static std::panic::Location<'static>> {
        None
    }

    fn request_layout(
        &mut self,
        _: Option<&crate::GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        window: &mut Window,
        cx: &mut App,
    ) -> (crate::LayoutId, Self::RequestLayoutState) {
        (window.request_layout(Style::default(), None, cx), ())
    }

    fn prepaint(
        &mut self,
        _: Option<&crate::GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        _: &mut Window,
        _: &mut App,
    ) -> Self::PrepaintState {
    }

    fn paint(
        &mut self,
        _: Option<&crate::GlobalElementId>,
        _: Option<&crate::InspectorElementId>,
        _: Bounds<Pixels>,
        _: &mut Self::RequestLayoutState,
        _: &mut Self::PrepaintState,
        window: &mut Window,
        cx: &mut App,
    ) {
        window.on_mouse_event({
            let state = self.state.clone();
            let axis = self.axis;
            let current_ix = state.read(cx).resizing_panel_ix;

            move |event: &MouseMoveEvent, phase, window, cx| {
                if !phase.bubble() {
                    return;
                }

                let Some(panel_index) = current_ix else {
                    return;
                };

                state.update(cx, |state, cx| {
                    if let Some(panel) = state.panels.get(panel_index) {
                        let new_size = match axis {
                            Axis::Horizontal => event.position.x - panel.bounds.left(),
                            Axis::Vertical => event.position.y - panel.bounds.top(),
                        };

                        state.resize_panel(panel_index, new_size, window, cx);
                    }

                    cx.notify();
                });
            }
        });

        window.on_mouse_event({
            let state = self.state.clone();
            let current_ix = state.read(cx).resizing_panel_ix;

            move |_: &MouseUpEvent, phase, _, cx| {
                if current_ix.is_none() {
                    return;
                }

                if phase.bubble() {
                    state.update(cx, |state, cx| {
                        state.done_resizing(cx);
                    });
                }
            }
        });
    }
}