ailloli_ui_widgets/editor/pane.rs
1//! Framed text/code editor composition with tabs and active-file metadata.
2//!
3//! An [`EditorPane`] owns one editor content view and paints two chrome rows:
4//! selectable tabs followed by a title, path, or file breadcrumb. Tabs and the
5//! active tab can be supplied as static values or live signals.
6
7use std::path::Path;
8use std::rc::Rc;
9
10use ailloli_ui_core::event::pointer::{MouseButton, PointerEvent};
11use ailloli_ui_core::event::Event;
12use ailloli_ui_core::style::{FlexItemStyle, LayoutSizeHint, LayoutStyle};
13use ailloli_ui_core::{
14 Border, ClipShape, Color, Constraints, FontId, IconId, Offset, Radius, Rect, Size, TextStyle,
15 Theme,
16};
17use ailloli_ui_editor::{Document, DocumentSource};
18use ailloli_ui_runtime::component::{
19 Binding, ComponentNode, Context, IntoView, Signal, View, Widget,
20};
21use ailloli_ui_runtime::input::EventCtx;
22use ailloli_ui_runtime::layout::{ChildLayout, LayoutChild, LayoutCtx, LayoutResult};
23use ailloli_ui_runtime::scene::PaintCtx;
24use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawImage, DrawRRect, DrawRect, DrawText};
25use ailloli_ui_text::{TextBuffer, TextLayoutParams, TextSystem, WrapMode};
26
27use crate::controls::tabs::{TabsItem, TabsStyle};
28use crate::controls::{draw_tabs_bar_with_options, TabsBarOptions};
29use crate::editor::{CodeEditor, Editor};
30#[cfg(feature = "files")]
31use crate::files::{breadcrumb_segments, FileBreadcrumbStyle};
32use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
33#[cfg(feature = "files")]
34use ailloli_ui_fs::FileUri;
35
36/// Shared retained callback for the pane's combined action stream.
37type ActionHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, EditorPaneAction)>;
38/// Shared retained callback for one tab identifier.
39type TabHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, String)>;
40
41/// Default intrinsic pane width in logical pixels before layout constraints.
42const DEFAULT_PANE_WIDTH: f32 = 640.0;
43/// Default intrinsic pane height in logical pixels before layout constraints.
44const DEFAULT_PANE_HEIGHT: f32 = 420.0;
45
46/// Metadata rendered for one editor-pane tab.
47///
48/// Empty identifiers are accepted but should be avoided because identifiers
49/// drive selection and callbacks. `None` for `path`, `icon`, or `icon_tint`
50/// means that the corresponding decoration or override is absent.
51///
52/// # Examples
53///
54/// ```
55/// use ailloli_ui_widgets::editor::{EditorPaneTab, EditorPaneTabKind};
56/// let tab = EditorPaneTab::code("main", "main.rs").path("src/main.rs");
57/// assert_eq!(tab.id, "main");
58/// assert_eq!(tab.kind, EditorPaneTabKind::Code);
59/// assert_eq!(tab.path.as_deref(), Some("src/main.rs"));
60/// ```
61#[derive(Clone, Debug, PartialEq)]
62pub struct EditorPaneTab {
63 /// Stable identifier emitted by selection and close actions.
64 pub id: String,
65 /// Visible tab label and fallback active title.
66 pub title: String,
67 /// Optional display path or URI used by the header/breadcrumb.
68 pub path: Option<String>,
69 /// Whether to render the unsaved-change indicator.
70 pub dirty: bool,
71 /// Semantic tab category used for the scope strip.
72 pub kind: EditorPaneTabKind,
73 /// Optional leading icon.
74 pub icon: Option<IconId>,
75 /// Optional icon tint; `None` uses the pane's muted-path color.
76 pub icon_tint: Option<Color>,
77}
78
79impl EditorPaneTab {
80 /// Creates an undecorated, clean tab of [`EditorPaneTabKind::Other`].
81 ///
82 /// # Examples
83 ///
84 /// ```
85 /// use ailloli_ui_widgets::editor::{EditorPaneTab, EditorPaneTabKind};
86 /// let tab = EditorPaneTab::new("notes", "Notes");
87 /// assert_eq!(tab.kind, EditorPaneTabKind::Other);
88 /// assert!(!tab.dirty && tab.path.is_none() && tab.icon.is_none());
89 /// ```
90 pub fn new(id: impl Into<String>, title: impl Into<String>) -> Self {
91 Self {
92 id: id.into(),
93 title: title.into(),
94 path: None,
95 dirty: false,
96 kind: EditorPaneTabKind::Other,
97 icon: None,
98 icon_tint: None,
99 }
100 }
101
102 /// Creates a tab categorized as plain text.
103 ///
104 /// # Examples
105 ///
106 /// ```
107 /// use ailloli_ui_widgets::editor::{EditorPaneTab, EditorPaneTabKind};
108 /// assert_eq!(EditorPaneTab::text("readme", "README").kind, EditorPaneTabKind::Text);
109 /// ```
110 pub fn text(id: impl Into<String>, title: impl Into<String>) -> Self {
111 Self::new(id, title).kind(EditorPaneTabKind::Text)
112 }
113
114 /// Creates a tab categorized as source code.
115 ///
116 /// # Examples
117 ///
118 /// ```
119 /// use ailloli_ui_widgets::editor::{EditorPaneTab, EditorPaneTabKind};
120 /// assert_eq!(EditorPaneTab::code("lib", "lib.rs").kind, EditorPaneTabKind::Code);
121 /// ```
122 pub fn code(id: impl Into<String>, title: impl Into<String>) -> Self {
123 Self::new(id, title).kind(EditorPaneTabKind::Code)
124 }
125
126 /// Sets the display path or URI used by the active header.
127 ///
128 /// Empty strings behave as absent while resolving the header. With the
129 /// `files` feature, URI strings, slash paths, backslash paths, and
130 /// `parent > child` labels are normalized for breadcrumb rendering.
131 ///
132 /// # Examples
133 ///
134 /// ```
135 /// use ailloli_ui_widgets::editor::EditorPaneTab;
136 /// let tab = EditorPaneTab::code("lib", "lib.rs").path("src/lib.rs");
137 /// assert_eq!(tab.path.as_deref(), Some("src/lib.rs"));
138 /// ```
139 pub fn path(mut self, path: impl Into<String>) -> Self {
140 self.path = Some(path.into());
141 self
142 }
143
144 /// Marks whether the tab has unsaved changes.
145 ///
146 /// # Examples
147 ///
148 /// ```
149 /// use ailloli_ui_widgets::editor::EditorPaneTab;
150 /// assert!(EditorPaneTab::text("draft", "Draft").dirty(true).dirty);
151 /// ```
152 pub fn dirty(mut self, dirty: bool) -> Self {
153 self.dirty = dirty;
154 self
155 }
156
157 /// Replaces the semantic category used by the tab scope strip.
158 ///
159 /// # Examples
160 ///
161 /// ```
162 /// use ailloli_ui_widgets::editor::{EditorPaneTab, EditorPaneTabKind};
163 /// let tab = EditorPaneTab::new("log", "Log").kind(EditorPaneTabKind::Text);
164 /// assert_eq!(tab.kind, EditorPaneTabKind::Text);
165 /// ```
166 pub fn kind(mut self, kind: EditorPaneTabKind) -> Self {
167 self.kind = kind;
168 self
169 }
170
171 /// Sets a leading tab icon.
172 ///
173 /// # Examples
174 ///
175 /// ```
176 /// use ailloli_ui_core::IconId;
177 /// use ailloli_ui_widgets::editor::EditorPaneTab;
178 /// let tab = EditorPaneTab::new("new", "New").icon(IconId::Plus);
179 /// assert_eq!(tab.icon, Some(IconId::Plus));
180 /// ```
181 pub fn icon(mut self, icon: IconId) -> Self {
182 self.icon = Some(icon);
183 self
184 }
185
186 /// Sets the leading icon tint.
187 ///
188 /// The tint is retained even when no icon is configured and becomes visible
189 /// if an icon is added later.
190 ///
191 /// # Examples
192 ///
193 /// ```
194 /// use ailloli_ui_core::Color;
195 /// use ailloli_ui_widgets::editor::EditorPaneTab;
196 /// let color = Color::rgba(255, 0, 0, 1.0);
197 /// assert_eq!(EditorPaneTab::new("a", "A").icon_tint(color).icon_tint, Some(color));
198 /// ```
199 pub fn icon_tint(mut self, color: Color) -> Self {
200 self.icon_tint = Some(color);
201 self
202 }
203}
204
205/// Semantic category used to decorate an editor tab.
206///
207/// # Examples
208///
209/// ```
210/// use ailloli_ui_widgets::editor::EditorPaneTabKind;
211/// assert_eq!(EditorPaneTabKind::default(), EditorPaneTabKind::Other);
212/// ```
213#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
214pub enum EditorPaneTabKind {
215 /// Plain-text document.
216 Text,
217 /// Source-code document.
218 Code,
219 /// Unclassified content and the default.
220 #[default]
221 Other,
222}
223
224/// High-level user action emitted by editor-pane tab chrome.
225///
226/// The contained string is the [`EditorPaneTab::id`]. A click on the close
227/// affordance emits only `CloseTab`; it does not first select the tab.
228///
229/// # Examples
230///
231/// ```
232/// use ailloli_ui_widgets::editor::EditorPaneAction;
233/// let action = EditorPaneAction::SelectTab("main".into());
234/// assert_eq!(action, EditorPaneAction::SelectTab("main".into()));
235/// ```
236#[derive(Clone, Debug, PartialEq, Eq)]
237pub enum EditorPaneAction {
238 /// The user selected the identified tab.
239 SelectTab(String),
240 /// The user requested closing the identified tab.
241 CloseTab(String),
242}
243
244/// Preset height for the tabs and metadata header rows.
245///
246/// # Examples
247///
248/// ```
249/// use ailloli_ui_widgets::editor::EditorPaneSize;
250/// assert_eq!(EditorPaneSize::default(), EditorPaneSize::Default);
251/// ```
252#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
253pub enum EditorPaneSize {
254 /// 32-logical-pixel tabs plus a 24-pixel header.
255 Compact,
256 /// 36-logical-pixel tabs plus a 28-pixel header.
257 #[default]
258 Default,
259}
260
261/// Colors and logical-pixel geometry for an [`EditorPane`].
262///
263/// No field is automatically clamped. Negative row heights or radius values
264/// are therefore forwarded to layout/painting and should be avoided.
265///
266/// # Examples
267///
268/// ```
269/// use ailloli_ui_widgets::editor::EditorPaneStyle;
270/// let style = EditorPaneStyle::default();
271/// assert_eq!(style.tabs_height, 36.0);
272/// assert_eq!(style.header_height, 28.0);
273/// ```
274#[derive(Clone, Debug)]
275pub struct EditorPaneStyle {
276 /// Content-frame fill color.
277 pub background: Color,
278 /// One-logical-pixel outer border color.
279 pub border: Color,
280 /// Metadata-header fill color.
281 pub header_bg: Color,
282 /// One-logical-pixel divider color below the header.
283 pub header_border: Color,
284 /// Active breadcrumb-segment color.
285 pub title_fg: Color,
286 /// Inactive breadcrumb/path and fallback icon color.
287 pub path_fg: Color,
288 /// Unsaved-change dot color.
289 pub dirty: Color,
290 /// Outer clip and border radius in logical pixels.
291 pub radius: f32,
292 /// Tab-row height in logical pixels.
293 pub tabs_height: f32,
294 /// Metadata-header height in logical pixels.
295 pub header_height: f32,
296 /// Nested tab-bar colors.
297 pub tabs: TabsStyle,
298}
299
300/// Builds default-sized chrome from the process-independent default theme.
301impl Default for EditorPaneStyle {
302 fn default() -> Self {
303 Self::from_theme(Theme::default(), EditorPaneSize::Default)
304 }
305}
306
307impl EditorPaneStyle {
308 /// Derives pane colors from `theme` and row heights from `size`.
309 ///
310 /// Compact rows are 32/24 logical pixels; default rows are 36/28. The
311 /// dirty indicator uses opaque amber and the radius uses `theme.radius().md`.
312 ///
313 /// # Examples
314 ///
315 /// ```
316 /// use ailloli_ui_core::Theme;
317 /// use ailloli_ui_widgets::editor::{EditorPaneSize, EditorPaneStyle};
318 /// let compact = EditorPaneStyle::from_theme(Theme::default(), EditorPaneSize::Compact);
319 /// assert_eq!((compact.tabs_height, compact.header_height), (32.0, 24.0));
320 /// ```
321 pub fn from_theme(theme: Theme, size: EditorPaneSize) -> Self {
322 let p = theme.palette();
323 let (tabs_height, header_height) = match size {
324 EditorPaneSize::Compact => (32.0, 24.0),
325 EditorPaneSize::Default => (36.0, 28.0),
326 };
327 Self {
328 background: p.surface,
329 border: p.border,
330 header_bg: p.surface_elevated.with_alpha(0.84),
331 header_border: p.border.with_alpha(0.72),
332 title_fg: p.text,
333 path_fg: p.text_muted,
334 dirty: Color::rgba(245, 158, 11, 1.0),
335 radius: theme.radius().md,
336 tabs_height,
337 header_height,
338 tabs: TabsStyle {
339 bar_bg: p.background,
340 tab_bg: p.surface,
341 tab_bg_selected: p.surface_elevated,
342 tab_border: p.border.with_alpha(0.72),
343 tab_border_selected: p.accent,
344 text_fg: p.text,
345 text_muted: p.text_muted,
346 unread_dot: Color::rgba(245, 158, 11, 1.0),
347 },
348 }
349 }
350}
351
352/// Framed editor view with tab and active-document chrome.
353///
354/// The pane has a 640×420 logical-pixel intrinsic size, then obeys the standard
355/// layout builders and incoming constraints. Its tabs and metadata header take
356/// their configured heights; a smaller constrained height gives the content a
357/// zero-height remainder. `A` is the application action type dispatched by
358/// callback adapters.
359///
360/// # Examples
361///
362/// ```
363/// use ailloli_ui_widgets::editor::{EditorPane, EditorPaneTab};
364/// use ailloli_ui_widgets::text::Text;
365/// let pane = EditorPane::<()>::new(Text::new("Preview"))
366/// .tabs([EditorPaneTab::text("preview", "Preview")])
367/// .active_tab("preview");
368/// let _ = pane;
369/// ```
370pub struct EditorPane<A = ()> {
371 /// Standard logical-pixel size and position constraints.
372 pub(crate) layout: LayoutStyle,
373 /// Standard flex-parent participation settings.
374 pub(crate) flex_item: FlexItemStyle,
375 /// Retained editor/content view painted below the chrome.
376 content: View<A>,
377 /// Read-only fallback tab list.
378 tabs: Vec<EditorPaneTab>,
379 /// Optional writable tab collection used by built-in close behavior.
380 bound_tabs: Option<Signal<Vec<EditorPaneTab>>>,
381 /// Optional readable active tab ID.
382 active_tab: Option<Binding<String>>,
383 /// Optional writable active tab ID.
384 bound_active_tab: Option<Signal<String>>,
385 /// Optional active-document title overriding tab metadata.
386 active_title: Option<Binding<String>>,
387 /// Optional active-document path used by breadcrumb projection.
388 active_path: Option<Binding<String>>,
389 /// Optional active-document dirty state overriding tab metadata.
390 dirty: Option<Binding<bool>>,
391 /// Optional active document whose metadata fills missing chrome values.
392 active_document: Option<Signal<Document>>,
393 /// Tab, breadcrumb, action, and frame styling.
394 style: EditorPaneStyle,
395 /// Optional callback receiving selected tab IDs.
396 on_select_tab: Option<TabHandler<A>>,
397 /// Optional callback receiving requested close tab IDs.
398 on_close_tab: Option<TabHandler<A>>,
399 /// Optional callback receiving pane-level actions.
400 on_action: Option<ActionHandler<A>>,
401}
402
403crate::impl_layout_builders!(EditorPane);
404
405impl<A: 'static> EditorPane<A> {
406 /// Wraps any view as pane content with empty tabs and default chrome.
407 ///
408 /// # Examples
409 ///
410 /// ```
411 /// use ailloli_ui_widgets::editor::EditorPane;
412 /// use ailloli_ui_widgets::text::Text;
413 /// let pane = EditorPane::<()>::new(Text::new("content"));
414 /// let _ = pane;
415 /// ```
416 pub fn new(child: impl IntoView<A>) -> Self {
417 Self {
418 layout: LayoutStyle::default(),
419 flex_item: FlexItemStyle::default(),
420 content: child.into_view(),
421 tabs: Vec::new(),
422 bound_tabs: None,
423 active_tab: None,
424 bound_active_tab: None,
425 active_title: None,
426 active_path: None,
427 dirty: None,
428 active_document: None,
429 style: EditorPaneStyle::default(),
430 on_select_tab: None,
431 on_close_tab: None,
432 on_action: None,
433 }
434 }
435
436 /// Creates a pane whose content is a fill-sized plain-text [`Editor`].
437 ///
438 /// Edits mutate the shared buffer signal. No tab is synthesized from the
439 /// buffer; configure tabs/title/path explicitly when chrome text is wanted.
440 ///
441 /// # Examples
442 ///
443 /// ```
444 /// use ailloli_ui_runtime::component::State;
445 /// use ailloli_ui_text::TextBuffer;
446 /// use ailloli_ui_widgets::editor::EditorPane;
447 /// let pane: EditorPane<()> = EditorPane::text(State::new(TextBuffer::from_string("notes")));
448 /// let _ = pane;
449 /// ```
450 pub fn text(buffer: impl Into<Signal<TextBuffer>>) -> Self {
451 Self::new(Editor::new(buffer).fill())
452 }
453
454 /// Creates a pane whose content is a fill-sized [`CodeEditor`].
455 ///
456 /// Document source metadata and dirty state become fallbacks for the pane
457 /// header. No visible tab is synthesized automatically.
458 ///
459 /// # Examples
460 ///
461 /// ```
462 /// use ailloli_ui_editor::{Document, DocumentId};
463 /// use ailloli_ui_runtime::component::State;
464 /// use ailloli_ui_text::TextBuffer;
465 /// use ailloli_ui_widgets::editor::EditorPane;
466 /// let document = Document::new(DocumentId(1), TextBuffer::new()).with_path("src/lib.rs");
467 /// let pane: EditorPane<()> = EditorPane::code(State::new(document));
468 /// let _ = pane;
469 /// ```
470 pub fn code(document: impl Into<Signal<Document>>) -> Self {
471 let document = document.into();
472 Self::new(CodeEditor::<A>::new(document.clone()).fill()).with_active_document(document)
473 }
474
475 /// Replaces static tabs and removes any previously bound tab signal.
476 ///
477 /// Iteration order is paint and hit-test order. An empty list suppresses
478 /// tabs; no implicit tab is derived from editor content.
479 ///
480 /// # Examples
481 ///
482 /// ```
483 /// use ailloli_ui_widgets::editor::{EditorPane, EditorPaneTab};
484 /// use ailloli_ui_widgets::text::Text;
485 /// let pane = EditorPane::<()>::new(Text::new("body"))
486 /// .tabs([EditorPaneTab::text("one", "One"), EditorPaneTab::text("two", "Two")]);
487 /// let _ = pane;
488 /// ```
489 pub fn tabs(mut self, tabs: impl IntoIterator<Item = EditorPaneTab>) -> Self {
490 self.tabs = tabs.into_iter().collect();
491 self.bound_tabs = None;
492 self
493 }
494
495 /// Binds the visible tabs to live shared state.
496 ///
497 /// Bound tabs take precedence over stored static tabs. Later calling
498 /// [`Self::tabs`] returns to static input by clearing this binding.
499 ///
500 /// # Examples
501 ///
502 /// ```
503 /// use ailloli_ui_runtime::component::State;
504 /// use ailloli_ui_widgets::editor::{EditorPane, EditorPaneTab};
505 /// use ailloli_ui_widgets::text::Text;
506 /// let tabs = State::new(vec![EditorPaneTab::code("lib", "lib.rs")]);
507 /// let pane = EditorPane::<()>::new(Text::new("body")).bind_tabs(tabs);
508 /// let _ = pane;
509 /// ```
510 pub fn bind_tabs(mut self, tabs: impl Into<Signal<Vec<EditorPaneTab>>>) -> Self {
511 self.bound_tabs = Some(tabs.into());
512 self
513 }
514
515 /// Sets a static or generic binding for the active tab identifier.
516 ///
517 /// Empty or unknown identifiers fall back to the first tab. This method
518 /// removes the special writable signal installed by [`Self::bind_active_tab`],
519 /// so user clicks no longer update active state automatically.
520 ///
521 /// # Examples
522 ///
523 /// ```
524 /// use ailloli_ui_widgets::editor::EditorPane;
525 /// use ailloli_ui_widgets::text::Text;
526 /// let pane = EditorPane::<()>::new(Text::new("body")).active_tab("main");
527 /// let _ = pane;
528 /// ```
529 pub fn active_tab(mut self, active_tab: impl Into<Binding<String>>) -> Self {
530 self.active_tab = Some(active_tab.into());
531 self.bound_active_tab = None;
532 self
533 }
534
535 /// Binds active-tab selection to writable shared state.
536 ///
537 /// A left click on a tab writes its identifier before invoking selection
538 /// and aggregate callbacks. Empty or unknown values display the first tab.
539 ///
540 /// # Examples
541 ///
542 /// ```
543 /// use ailloli_ui_runtime::component::State;
544 /// use ailloli_ui_widgets::editor::EditorPane;
545 /// use ailloli_ui_widgets::text::Text;
546 /// let active = State::new(String::from("main"));
547 /// let pane = EditorPane::<()>::new(Text::new("body")).bind_active_tab(active);
548 /// let _ = pane;
549 /// ```
550 pub fn bind_active_tab(mut self, active_tab: impl Into<Signal<String>>) -> Self {
551 let signal = active_tab.into();
552 self.active_tab = Some(Binding::Signal(signal.clone()));
553 self.bound_active_tab = Some(signal);
554 self
555 }
556
557 /// Overrides the selected tab or document title.
558 ///
559 /// An empty value is treated as no override. Resolution order is explicit
560 /// non-empty title, selected-tab title, document filename, then empty.
561 ///
562 /// # Examples
563 ///
564 /// ```
565 /// use ailloli_ui_widgets::editor::EditorPane;
566 /// use ailloli_ui_widgets::text::Text;
567 /// let pane = EditorPane::<()>::new(Text::new("body")).active_title("Untitled");
568 /// let _ = pane;
569 /// ```
570 pub fn active_title(mut self, title: impl Into<Binding<String>>) -> Self {
571 self.active_title = Some(title.into());
572 self
573 }
574
575 /// Overrides the selected tab or document path in the header.
576 ///
577 /// An empty value is treated as absent. Resolution order is explicit path,
578 /// selected-tab path, then document source path/URI.
579 ///
580 /// # Examples
581 ///
582 /// ```
583 /// use ailloli_ui_widgets::editor::EditorPane;
584 /// use ailloli_ui_widgets::text::Text;
585 /// let pane = EditorPane::<()>::new(Text::new("body")).active_path("src/main.rs");
586 /// let _ = pane;
587 /// ```
588 pub fn active_path(mut self, path: impl Into<Binding<String>>) -> Self {
589 self.active_path = Some(path.into());
590 self
591 }
592
593 /// Overrides active dirty state, including an explicit `false`.
594 ///
595 /// Without an override, the selected tab and active document are combined
596 /// with logical OR. The value controls the header dot and selected tab's
597 /// unread/dirty decoration only.
598 ///
599 /// # Examples
600 ///
601 /// ```
602 /// use ailloli_ui_widgets::editor::EditorPane;
603 /// use ailloli_ui_widgets::text::Text;
604 /// let pane = EditorPane::<()>::new(Text::new("body")).dirty(true);
605 /// let _ = pane;
606 /// ```
607 pub fn dirty(mut self, dirty: impl Into<Binding<bool>>) -> Self {
608 self.dirty = Some(dirty.into());
609 self
610 }
611
612 /// Replaces all pane and tab chrome styling.
613 ///
614 /// # Examples
615 ///
616 /// ```
617 /// use ailloli_ui_widgets::editor::{EditorPane, EditorPaneStyle};
618 /// use ailloli_ui_widgets::text::Text;
619 /// let pane = EditorPane::<()>::new(Text::new("body")).pane_style(EditorPaneStyle::default());
620 /// let _ = pane;
621 /// ```
622 pub fn pane_style(mut self, style: EditorPaneStyle) -> Self {
623 self.style = style;
624 self
625 }
626
627 /// Applies a size preset using the default theme.
628 ///
629 /// This replaces the entire existing [`EditorPaneStyle`], so call it before
630 /// [`Self::pane_style`] when combining a size preset with custom colors.
631 ///
632 /// # Examples
633 ///
634 /// ```
635 /// use ailloli_ui_widgets::editor::{EditorPane, EditorPaneSize};
636 /// use ailloli_ui_widgets::text::Text;
637 /// let pane = EditorPane::<()>::new(Text::new("body")).pane_size(EditorPaneSize::Compact);
638 /// let _ = pane;
639 /// ```
640 pub fn pane_size(mut self, size: EditorPaneSize) -> Self {
641 self.style = EditorPaneStyle::from_theme(Theme::default(), size);
642 self
643 }
644
645 /// Maps a selected tab identifier into an application action.
646 ///
647 /// The callback runs after a bound active-tab signal is updated and before
648 /// the optional aggregate action callback.
649 ///
650 /// # Examples
651 ///
652 /// ```
653 /// use ailloli_ui_widgets::editor::EditorPane;
654 /// use ailloli_ui_widgets::text::Text;
655 /// enum Action { Select(String) }
656 /// let pane = EditorPane::<Action>::new(Text::new("body")).on_select_tab(Action::Select);
657 /// let _ = pane;
658 /// ```
659 pub fn on_select_tab(mut self, f: impl Fn(String) -> A + 'static) -> Self {
660 self.on_select_tab = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
661 self
662 }
663
664 /// Handles selection with direct access to the event context.
665 ///
666 /// Use this form to dispatch zero or multiple actions or request additional
667 /// runtime work. Callback order matches [`Self::on_select_tab`].
668 ///
669 /// # Examples
670 ///
671 /// ```
672 /// use ailloli_ui_widgets::editor::EditorPane;
673 /// use ailloli_ui_widgets::text::Text;
674 /// let pane = EditorPane::<()>::new(Text::new("body"))
675 /// .on_select_tab_ctx(|_ctx, _id| {});
676 /// let _ = pane;
677 /// ```
678 pub fn on_select_tab_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String) + 'static) -> Self {
679 self.on_select_tab = Some(Rc::new(f));
680 self
681 }
682
683 /// Maps a close request identifier into an application action.
684 ///
685 /// Clicking a tab's trailing 22-logical-pixel close region takes priority
686 /// over selection, invokes this callback, then invokes the aggregate action
687 /// callback. The pane does not remove the tab itself.
688 ///
689 /// # Examples
690 ///
691 /// ```
692 /// use ailloli_ui_widgets::editor::EditorPane;
693 /// use ailloli_ui_widgets::text::Text;
694 /// enum Action { Close(String) }
695 /// let pane = EditorPane::<Action>::new(Text::new("body")).on_close_tab(Action::Close);
696 /// let _ = pane;
697 /// ```
698 pub fn on_close_tab(mut self, f: impl Fn(String) -> A + 'static) -> Self {
699 self.on_close_tab = Some(Rc::new(move |ctx, id| ctx.dispatch(f(id))));
700 self
701 }
702
703 /// Handles a close request with direct access to the event context.
704 ///
705 /// # Examples
706 ///
707 /// ```
708 /// use ailloli_ui_widgets::editor::EditorPane;
709 /// use ailloli_ui_widgets::text::Text;
710 /// let pane = EditorPane::<()>::new(Text::new("body"))
711 /// .on_close_tab_ctx(|_ctx, _id| {});
712 /// let _ = pane;
713 /// ```
714 pub fn on_close_tab_ctx(mut self, f: impl Fn(&mut EventCtx<A>, String) + 'static) -> Self {
715 self.on_close_tab = Some(Rc::new(f));
716 self
717 }
718
719 /// Maps every select/close event into one application action.
720 ///
721 /// A specialized selection or close callback, when installed, runs first;
722 /// both callbacks may therefore dispatch actions for one pointer event.
723 ///
724 /// # Examples
725 ///
726 /// ```
727 /// use ailloli_ui_widgets::editor::{EditorPane, EditorPaneAction};
728 /// use ailloli_ui_widgets::text::Text;
729 /// let pane = EditorPane::<EditorPaneAction>::new(Text::new("body")).on_action(|action| action);
730 /// let _ = pane;
731 /// ```
732 pub fn on_action(mut self, f: impl Fn(EditorPaneAction) -> A + 'static) -> Self {
733 self.on_action = Some(Rc::new(move |ctx, action| ctx.dispatch(f(action))));
734 self
735 }
736
737 /// Handles every select/close event with direct event-context access.
738 ///
739 /// # Examples
740 ///
741 /// ```
742 /// use ailloli_ui_widgets::editor::EditorPane;
743 /// use ailloli_ui_widgets::text::Text;
744 /// let pane = EditorPane::<()>::new(Text::new("body"))
745 /// .on_action_ctx(|_ctx, _action| {});
746 /// let _ = pane;
747 /// ```
748 pub fn on_action_ctx(
749 mut self,
750 f: impl Fn(&mut EventCtx<A>, EditorPaneAction) + 'static,
751 ) -> Self {
752 self.on_action = Some(Rc::new(f));
753 self
754 }
755
756 /// Retains code-document metadata as a title/path/dirty fallback.
757 fn with_active_document(mut self, document: Signal<Document>) -> Self {
758 self.active_document = Some(document);
759 self
760 }
761}
762
763/// Converts the pane builder into a clipped frame, chrome, and content tree.
764impl<A: 'static> IntoView<A> for EditorPane<A> {
765 fn into_view(self) -> View<A> {
766 finish_view_sized(
767 View::component(EditorPaneComponent {
768 layout: self.layout,
769 content: self.content,
770 tabs: self.tabs,
771 bound_tabs: self.bound_tabs,
772 active_tab: self.active_tab,
773 bound_active_tab: self.bound_active_tab,
774 active_title: self.active_title,
775 active_path: self.active_path,
776 dirty: self.dirty,
777 active_document: self.active_document,
778 style: self.style,
779 on_select_tab: self.on_select_tab,
780 on_close_tab: self.on_close_tab,
781 on_action: self.on_action,
782 }),
783 self.flex_item,
784 LayoutSizeHint::from_layout(self.layout),
785 )
786 }
787}
788
789/// Component boundary that expands the builder into frame/chrome/content nodes.
790struct EditorPaneComponent<A> {
791 /// Outer logical sizing policy.
792 layout: LayoutStyle,
793 /// Retained editor/content view painted below the chrome.
794 content: View<A>,
795 /// Read-only fallback tab list.
796 tabs: Vec<EditorPaneTab>,
797 /// Optional writable tab collection.
798 bound_tabs: Option<Signal<Vec<EditorPaneTab>>>,
799 /// Optional readable active tab ID.
800 active_tab: Option<Binding<String>>,
801 /// Optional writable active tab ID.
802 bound_active_tab: Option<Signal<String>>,
803 /// Optional active-document title override.
804 active_title: Option<Binding<String>>,
805 /// Optional active-document path override.
806 active_path: Option<Binding<String>>,
807 /// Optional active-document dirty-state override.
808 dirty: Option<Binding<bool>>,
809 /// Optional active document supplying fallback metadata.
810 active_document: Option<Signal<Document>>,
811 /// Tab, breadcrumb, action, and frame styling.
812 style: EditorPaneStyle,
813 /// Optional retained tab-selection callback.
814 on_select_tab: Option<TabHandler<A>>,
815 /// Optional retained tab-close callback.
816 on_close_tab: Option<TabHandler<A>>,
817 /// Optional retained pane-action callback.
818 on_action: Option<ActionHandler<A>>,
819}
820
821/// Rebuilds chrome children from the latest builder-held bindings.
822impl<A: 'static> ComponentNode<A> for EditorPaneComponent<A> {
823 fn build(&self, _context: &mut Context<A>) -> View<A> {
824 let chrome = EditorPaneChromeWidget {
825 tabs: self.tabs.clone(),
826 bound_tabs: self.bound_tabs.clone(),
827 active_tab: self.active_tab.clone(),
828 bound_active_tab: self.bound_active_tab.clone(),
829 active_title: self.active_title.clone(),
830 active_path: self.active_path.clone(),
831 dirty: self.dirty.clone(),
832 active_document: self.active_document.clone(),
833 style: self.style.clone(),
834 on_select_tab: self.on_select_tab.clone(),
835 on_close_tab: self.on_close_tab.clone(),
836 on_action: self.on_action.clone(),
837 };
838 let chrome_children = editor_pane_breadcrumb_children(
839 self.tabs.clone(),
840 self.bound_tabs.clone(),
841 self.active_tab.clone(),
842 self.active_path.clone(),
843 self.active_document.clone(),
844 self.style.clone(),
845 );
846
847 View::node(
848 EditorPaneFrameWidget {
849 layout: self.layout,
850 style: self.style.clone(),
851 },
852 vec![View::node(chrome, chrome_children), self.content.clone()],
853 )
854 }
855}
856
857/// Lays out and clips the two-row chrome above the editor content.
858struct EditorPaneFrameWidget {
859 /// Outer logical sizing policy.
860 layout: LayoutStyle,
861 /// Frame background, border, and logical-pixel geometry.
862 style: EditorPaneStyle,
863}
864
865/// Implements constrained 640x420 sizing, round clipping, fill, and border.
866impl<A: 'static> Widget<A> for EditorPaneFrameWidget {
867 fn debug_name(&self) -> &'static str {
868 "EditorPane"
869 }
870
871 fn layout(
872 &self,
873 engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
874 ctx: &mut LayoutCtx<'_>,
875 children: &mut [LayoutChild],
876 constraints: Constraints,
877 ) -> LayoutResult {
878 let intrinsic = Size::new(DEFAULT_PANE_WIDTH, DEFAULT_PANE_HEIGHT);
879 let size = apply_layout_size(intrinsic, self.layout, constraints);
880 let chrome_h = self.style.tabs_height + self.style.header_height;
881 let content_h = (size.h - chrome_h).max(0.0);
882
883 let mut child_layouts = Vec::with_capacity(children.len());
884 if let Some(chrome) = children.get_mut(0) {
885 let result = chrome.layout(engine, ctx, Constraints::tight(size.w, chrome_h));
886 child_layouts.push(ChildLayout {
887 offset: Offset::new(0.0, 0.0),
888 size: result.size,
889 paint_bounds: Rect::new(0.0, 0.0, result.size.w, result.size.h),
890 visual_bounds: result.visual_bounds,
891 });
892 }
893 if let Some(content) = children.get_mut(1) {
894 let result = content.layout(engine, ctx, Constraints::tight(size.w, content_h));
895 child_layouts.push(ChildLayout {
896 offset: Offset::new(0.0, chrome_h),
897 size: result.size,
898 paint_bounds: Rect::new(0.0, chrome_h, result.size.w, result.size.h),
899 visual_bounds: result.visual_bounds.translate(Offset::new(0.0, chrome_h)),
900 });
901 }
902
903 let bounds = Rect::new(0.0, 0.0, size.w, size.h);
904 LayoutResult {
905 size,
906 children: child_layouts,
907 paint_bounds: bounds,
908 visual_bounds: bounds,
909 overlay_hit_bounds: Vec::new(),
910 clip: Some(ClipShape::RoundRect {
911 rect: bounds,
912 radius: self.style.radius,
913 }),
914 is_window_root_clip: false,
915 artifact: None,
916 }
917 }
918
919 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
920 ctx.push(DrawCmd::RRect(DrawRRect {
921 rect: bounds,
922 radius: self.style.radius,
923 color: self.style.background,
924 }));
925 }
926
927 fn paint_overlay(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
928 ctx.push(DrawCmd::Border(DrawBorder {
929 rect: bounds,
930 radius: Radius::uniform(self.style.radius),
931 border: Border::new(1.0, self.style.border),
932 }));
933 }
934
935 fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
936 }
937}
938
939/// Resolves reactive tab metadata and paints/handles the two chrome rows.
940struct EditorPaneChromeWidget<A> {
941 /// Read-only fallback tab list.
942 tabs: Vec<EditorPaneTab>,
943 /// Optional writable tab collection.
944 bound_tabs: Option<Signal<Vec<EditorPaneTab>>>,
945 /// Optional readable active tab ID.
946 active_tab: Option<Binding<String>>,
947 /// Optional writable active tab ID.
948 bound_active_tab: Option<Signal<String>>,
949 /// Optional active-document title override.
950 active_title: Option<Binding<String>>,
951 /// Optional active-document path override.
952 active_path: Option<Binding<String>>,
953 /// Optional active-document dirty-state override.
954 dirty: Option<Binding<bool>>,
955 /// Optional active document supplying fallback metadata.
956 active_document: Option<Signal<Document>>,
957 /// Tab, breadcrumb, action, and frame styling.
958 style: EditorPaneStyle,
959 /// Optional retained tab-selection callback.
960 on_select_tab: Option<TabHandler<A>>,
961 /// Optional retained tab-close callback.
962 on_close_tab: Option<TabHandler<A>>,
963 /// Optional retained pane-action callback.
964 on_action: Option<ActionHandler<A>>,
965}
966
967/// Paints closeable tabs and routes left-clicks with close-before-row priority.
968impl<A: 'static> Widget<A> for EditorPaneChromeWidget<A> {
969 fn debug_name(&self) -> &'static str {
970 "EditorPaneChrome"
971 }
972
973 fn layout(
974 &self,
975 engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
976 ctx: &mut LayoutCtx<'_>,
977 children: &mut [LayoutChild],
978 constraints: Constraints,
979 ) -> LayoutResult {
980 let size = constraints.constrain(Size::new(
981 constraints.max_w,
982 self.style.tabs_height + self.style.header_height,
983 ));
984 let mut child_layouts = Vec::new();
985 if let Some(child) = children.get_mut(0) {
986 let model = self.model();
987 let header_text_x = self.header_text_x(size.w, model.active_icon.is_some());
988 let right_pad = if model.active_dirty { 30.0 } else { 12.0 };
989 let child_w = (size.w - header_text_x - right_pad).max(0.0);
990 let result = child.layout(
991 engine,
992 ctx,
993 Constraints::tight(child_w, self.style.header_height),
994 );
995 let offset = Offset::new(header_text_x, self.style.tabs_height);
996 child_layouts.push(ChildLayout {
997 offset,
998 size: result.size,
999 paint_bounds: Rect::new(offset.x, offset.y, result.size.w, result.size.h),
1000 visual_bounds: result.visual_bounds.translate(offset),
1001 });
1002 }
1003 LayoutResult {
1004 size,
1005 children: child_layouts,
1006 paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
1007 visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
1008 overlay_hit_bounds: Vec::new(),
1009 clip: None,
1010 is_window_root_clip: false,
1011 artifact: None,
1012 }
1013 }
1014
1015 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1016 let model = self.model();
1017 let tab_rect = Rect::new(bounds.x, bounds.y, bounds.w, self.style.tabs_height);
1018 if let Some(text) = ctx.text_system.as_deref_mut() {
1019 let (cmds, _) = draw_tabs_bar_with_options(
1020 tab_rect,
1021 &model.tabs,
1022 false,
1023 self.style.tabs,
1024 text,
1025 TabsBarOptions {
1026 show_trailing_actions: false,
1027 show_tab_close_affordance: true,
1028 show_scope_strip: true,
1029 },
1030 );
1031 for cmd in cmds {
1032 ctx.push(cmd);
1033 }
1034 } else {
1035 ctx.push(DrawCmd::Rect(DrawRect {
1036 rect: tab_rect,
1037 color: self.style.tabs.bar_bg,
1038 }));
1039 }
1040
1041 let header = Rect::new(
1042 bounds.x,
1043 bounds.y + self.style.tabs_height,
1044 bounds.w,
1045 self.style.header_height,
1046 );
1047 ctx.push(DrawCmd::Rect(DrawRect {
1048 rect: header,
1049 color: self.style.header_bg,
1050 }));
1051 ctx.push(DrawCmd::Rect(DrawRect {
1052 rect: Rect::new(header.x, header.bottom() - 1.0, header.w, 1.0),
1053 color: self.style.header_border,
1054 }));
1055
1056 let mut text_x = header.x + 14.0;
1057 if let Some(icon) = &model.active_icon {
1058 let size = 14.0;
1059 ctx.push(DrawCmd::Image(DrawImage {
1060 rect: Rect::new(
1061 header.x + 12.0,
1062 header.y + (header.h - size) * 0.5,
1063 size,
1064 size,
1065 ),
1066 icon: icon.clone(),
1067 tint: model.active_icon_tint.unwrap_or(self.style.path_fg),
1068 rotation_rad: 0.0,
1069 }));
1070 text_x += 20.0;
1071 }
1072
1073 let header_cmd = if !model_has_breadcrumb(&model) {
1074 ctx.text_system.as_deref_mut().and_then(|text| {
1075 let header_text = model
1076 .active_path
1077 .as_deref()
1078 .filter(|path| !path.is_empty())
1079 .unwrap_or(&model.active_title);
1080 (!header_text.is_empty()).then(|| {
1081 label_cmd(
1082 text,
1083 [text_x, header.y + 18.0],
1084 self.style.path_fg,
1085 12,
1086 header_text,
1087 )
1088 })
1089 })
1090 } else {
1091 None
1092 };
1093 if let Some(cmd) = header_cmd {
1094 ctx.push(cmd);
1095 }
1096
1097 if model.active_dirty {
1098 ctx.push(DrawCmd::RRect(DrawRRect {
1099 rect: Rect::new(
1100 header.right() - 18.0,
1101 header.y + (header.h - 8.0) * 0.5,
1102 8.0,
1103 8.0,
1104 ),
1105 radius: 4.0,
1106 color: self.style.dirty,
1107 }));
1108 }
1109 }
1110
1111 fn event(&self, ctx: &mut EventCtx<A>, event: &Event, bounds: Rect, _layout: &LayoutResult) {
1112 let Event::Pointer(PointerEvent::Button {
1113 pos,
1114 button: MouseButton::Left,
1115 pressed: true,
1116 ..
1117 }) = event
1118 else {
1119 return;
1120 };
1121 if !bounds.contains(pos.x, pos.y) {
1122 return;
1123 }
1124
1125 let model = self.model();
1126 let tab_rect = Rect::new(bounds.x, bounds.y, bounds.w, self.style.tabs_height);
1127 for (id, row, close) in tab_hit_layout(tab_rect, &model.tabs) {
1128 if close.contains(pos.x, pos.y) {
1129 self.emit_close(ctx, id);
1130 ctx.stop_propagation();
1131 return;
1132 }
1133 if row.contains(pos.x, pos.y) {
1134 self.emit_select(ctx, id);
1135 ctx.stop_propagation();
1136 return;
1137 }
1138 }
1139 }
1140}
1141
1142impl<A: 'static> EditorPaneChromeWidget<A> {
1143 /// Returns the bounded x origin for header text after optional icon space.
1144 fn header_text_x(&self, width: f32, has_icon: bool) -> f32 {
1145 let mut x: f32 = 14.0;
1146 if has_icon {
1147 x += 20.0;
1148 }
1149 x.min(width)
1150 }
1151}
1152
1153/// Builds one breadcrumb child when file integration is enabled, otherwise none.
1154fn editor_pane_breadcrumb_children<A: 'static>(
1155 tabs: Vec<EditorPaneTab>,
1156 bound_tabs: Option<Signal<Vec<EditorPaneTab>>>,
1157 active_tab: Option<Binding<String>>,
1158 active_path: Option<Binding<String>>,
1159 active_document: Option<Signal<Document>>,
1160 style: EditorPaneStyle,
1161) -> Vec<View<A>> {
1162 #[cfg(feature = "files")]
1163 {
1164 vec![View::leaf(EditorPaneBreadcrumbWidget {
1165 tabs,
1166 bound_tabs,
1167 active_tab,
1168 active_path,
1169 active_document,
1170 style: FileBreadcrumbStyle {
1171 text: TextStyle::new(FontId::Ui, 12, style.path_fg),
1172 active_text: TextStyle::new(FontId::Ui, 12, style.title_fg),
1173 separator: TextStyle::new(FontId::Ui, 12, style.path_fg.with_alpha(0.72)),
1174 gap: 6.0,
1175 },
1176 })]
1177 }
1178 #[cfg(not(feature = "files"))]
1179 {
1180 let _ = tabs;
1181 let _ = bound_tabs;
1182 let _ = active_tab;
1183 let _ = active_path;
1184 let _ = active_document;
1185 let _ = style;
1186 Vec::new()
1187 }
1188}
1189
1190#[cfg(feature = "files")]
1191/// Parses a URI or normalizes display-path separators into a local file URI.
1192///
1193/// Whitespace-only input and paths with no components return `None`. Native
1194/// backslashes and `parent > child` display paths become forward slashes.
1195fn breadcrumb_uri_from_path(path: &str) -> Option<FileUri> {
1196 let path = path.trim();
1197 if path.is_empty() {
1198 return None;
1199 }
1200 if let Ok(uri) = FileUri::parse(path) {
1201 return Some(uri);
1202 }
1203
1204 let normalized = if path.contains('>') {
1205 path.split('>')
1206 .map(str::trim)
1207 .filter(|part| !part.is_empty())
1208 .collect::<Vec<_>>()
1209 .join("/")
1210 } else {
1211 path.replace('\\', "/")
1212 };
1213 let normalized = normalized.trim_matches('/');
1214 if normalized.is_empty() {
1215 return None;
1216 }
1217 FileUri::new("file", None::<String>, format!("/{normalized}")).ok()
1218}
1219
1220impl<A: 'static> EditorPaneChromeWidget<A> {
1221 /// Resolves current signals and explicit metadata into one paint/hit model.
1222 ///
1223 /// Bound tabs override static tabs. Empty/unknown active identifiers select
1224 /// the first resolved tab. Explicit non-empty title/path values override tab
1225 /// values, which override document metadata; an explicit dirty boolean wins
1226 /// over the tab/document logical-OR fallback.
1227 fn model(&self) -> EditorPaneChromeModel {
1228 let document = self.active_document.as_ref().map(Signal::read);
1229 let document_meta = document.as_ref().and_then(document_title_path);
1230 let document_dirty = document.as_ref().is_some_and(|document| document.dirty);
1231
1232 let source_tabs = self
1233 .bound_tabs
1234 .as_ref()
1235 .map(Signal::read)
1236 .unwrap_or_else(|| self.tabs.clone());
1237
1238 let active_id = self
1239 .active_tab
1240 .as_ref()
1241 .map(Binding::read)
1242 .filter(|id| !id.is_empty())
1243 .or_else(|| source_tabs.first().map(|tab| tab.id.clone()));
1244
1245 let active_tab = active_id
1246 .as_ref()
1247 .and_then(|id| source_tabs.iter().find(|tab| &tab.id == id));
1248
1249 let explicit_title = self
1250 .active_title
1251 .as_ref()
1252 .map(Binding::read)
1253 .filter(|title| !title.is_empty());
1254 let explicit_path = self
1255 .active_path
1256 .as_ref()
1257 .map(Binding::read)
1258 .filter(|path| !path.is_empty());
1259 let explicit_dirty = self.dirty.as_ref().map(Binding::read);
1260
1261 let active_title = explicit_title
1262 .clone()
1263 .or_else(|| {
1264 active_tab
1265 .map(|tab| tab.title.clone())
1266 .filter(|title| !title.is_empty())
1267 })
1268 .or_else(|| document_meta.as_ref().map(|meta| meta.title.clone()))
1269 .unwrap_or_default();
1270 let active_path = explicit_path
1271 .or_else(|| active_tab.and_then(|tab| tab.path.clone()))
1272 .or_else(|| document_meta.as_ref().and_then(|meta| meta.path.clone()));
1273 let active_dirty = explicit_dirty
1274 .unwrap_or_else(|| active_tab.is_some_and(|tab| tab.dirty) || document_dirty);
1275 let active_icon = active_tab.and_then(|tab| tab.icon.clone());
1276 let active_icon_tint = active_tab.and_then(|tab| tab.icon_tint);
1277
1278 let mut tabs = if source_tabs.is_empty() {
1279 Vec::new()
1280 } else {
1281 source_tabs
1282 .iter()
1283 .map(|tab| {
1284 let selected = active_id.as_ref().is_some_and(|id| id == &tab.id);
1285 ResolvedEditorPaneTab {
1286 id: tab.id.clone(),
1287 title: if selected {
1288 explicit_title.clone().unwrap_or_else(|| tab.title.clone())
1289 } else {
1290 tab.title.clone()
1291 },
1292 selected,
1293 dirty: if selected {
1294 explicit_dirty.unwrap_or(tab.dirty || document_dirty)
1295 } else {
1296 tab.dirty
1297 },
1298 kind: tab.kind,
1299 icon: tab.icon.clone(),
1300 icon_tint: tab.icon_tint,
1301 }
1302 })
1303 .collect()
1304 };
1305
1306 if !tabs.iter().any(|tab| tab.selected) {
1307 if let Some(first) = tabs.first_mut() {
1308 first.selected = true;
1309 }
1310 }
1311
1312 EditorPaneChromeModel {
1313 tabs,
1314 active_title,
1315 #[cfg(feature = "files")]
1316 breadcrumb_uri: active_path.as_deref().and_then(breadcrumb_uri_from_path),
1317 active_path,
1318 active_dirty,
1319 active_icon,
1320 active_icon_tint,
1321 }
1322 }
1323
1324 /// Commits bound selection, invokes callbacks in order, and requests paint.
1325 fn emit_select(&self, ctx: &mut EventCtx<A>, id: String) {
1326 if let Some(active) = &self.bound_active_tab {
1327 active.set(id.clone());
1328 }
1329 if let Some(handler) = &self.on_select_tab {
1330 handler(ctx, id.clone());
1331 }
1332 if let Some(handler) = &self.on_action {
1333 handler(ctx, EditorPaneAction::SelectTab(id));
1334 }
1335 ctx.request_repaint();
1336 }
1337
1338 /// Invokes specialized then aggregate close callbacks and requests paint.
1339 fn emit_close(&self, ctx: &mut EventCtx<A>, id: String) {
1340 if let Some(handler) = &self.on_close_tab {
1341 handler(ctx, id.clone());
1342 }
1343 if let Some(handler) = &self.on_action {
1344 handler(ctx, EditorPaneAction::CloseTab(id));
1345 }
1346 ctx.request_repaint();
1347 }
1348}
1349
1350#[cfg(feature = "files")]
1351/// Paint-only breadcrumb whose URI follows pane title/path precedence.
1352struct EditorPaneBreadcrumbWidget {
1353 /// Read-only fallback tab list used to resolve active metadata.
1354 tabs: Vec<EditorPaneTab>,
1355 /// Optional writable tab collection, read as the authoritative list.
1356 bound_tabs: Option<Signal<Vec<EditorPaneTab>>>,
1357 /// Optional readable active tab ID.
1358 active_tab: Option<Binding<String>>,
1359 /// Optional active-document path override.
1360 active_path: Option<Binding<String>>,
1361 /// Optional active document supplying fallback path metadata.
1362 active_document: Option<Signal<Document>>,
1363 /// Breadcrumb colors and logical-pixel geometry.
1364 style: FileBreadcrumbStyle,
1365}
1366
1367#[cfg(feature = "files")]
1368impl EditorPaneBreadcrumbWidget {
1369 /// Resolves the active path and converts it to a breadcrumb-compatible URI.
1370 fn breadcrumb_uri(&self) -> Option<FileUri> {
1371 let document = self.active_document.as_ref().map(Signal::read);
1372 let document_meta = document.as_ref().and_then(document_title_path);
1373 let source_tabs = self
1374 .bound_tabs
1375 .as_ref()
1376 .map(Signal::read)
1377 .unwrap_or_else(|| self.tabs.clone());
1378 let active_id = self
1379 .active_tab
1380 .as_ref()
1381 .map(Binding::read)
1382 .filter(|id| !id.is_empty())
1383 .or_else(|| source_tabs.first().map(|tab| tab.id.clone()));
1384 let active_tab = active_id
1385 .as_ref()
1386 .and_then(|id| source_tabs.iter().find(|tab| &tab.id == id));
1387 let active_path = self
1388 .active_path
1389 .as_ref()
1390 .map(Binding::read)
1391 .filter(|path| !path.is_empty())
1392 .or_else(|| active_tab.and_then(|tab| tab.path.clone()))
1393 .or_else(|| document_meta.as_ref().and_then(|meta| meta.path.clone()));
1394 active_path.as_deref().and_then(breadcrumb_uri_from_path)
1395 }
1396}
1397
1398#[cfg(feature = "files")]
1399impl<A: 'static> Widget<A> for EditorPaneBreadcrumbWidget {
1400 fn debug_name(&self) -> &'static str {
1401 "EditorPaneBreadcrumb"
1402 }
1403
1404 fn layout(
1405 &self,
1406 _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
1407 _ctx: &mut LayoutCtx<'_>,
1408 _children: &mut [LayoutChild],
1409 constraints: Constraints,
1410 ) -> LayoutResult {
1411 let size = constraints.constrain(Size::new(constraints.max_w, constraints.max_h));
1412 LayoutResult {
1413 size,
1414 children: Vec::new(),
1415 paint_bounds: Rect::new(0.0, 0.0, size.w, size.h),
1416 visual_bounds: Rect::new(0.0, 0.0, size.w, size.h),
1417 overlay_hit_bounds: Vec::new(),
1418 clip: None,
1419 is_window_root_clip: false,
1420 artifact: None,
1421 }
1422 }
1423
1424 fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout: &LayoutResult) {
1425 let Some(uri) = self.breadcrumb_uri() else {
1426 return;
1427 };
1428 let segments = breadcrumb_segments(&uri, None, None);
1429 let mut x = bounds.x;
1430 let baseline = bounds.y + (bounds.h * 0.5 + 4.0).min(bounds.h);
1431 let mut cmds = Vec::new();
1432 {
1433 let Some(text_system) = ctx.text_system.as_deref_mut() else {
1434 return;
1435 };
1436 for (idx, segment) in segments.into_iter().enumerate() {
1437 if idx > 0 {
1438 let (cmd, separator_w) =
1439 breadcrumb_text_cmd(text_system, x, baseline, self.style.separator, ">");
1440 cmds.push(cmd);
1441 x += separator_w + self.style.gap;
1442 }
1443 let text_style = if segment.last {
1444 self.style.active_text
1445 } else {
1446 self.style.text
1447 };
1448 let (cmd, label_w) =
1449 breadcrumb_text_cmd(text_system, x, baseline, text_style, &segment.label);
1450 cmds.push(cmd);
1451 x += label_w + self.style.gap;
1452 }
1453 }
1454 for cmd in cmds {
1455 ctx.push(cmd);
1456 }
1457 }
1458
1459 fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
1460 }
1461}
1462
1463#[cfg(feature = "files")]
1464/// Measures and builds one no-wrap breadcrumb label draw command.
1465fn breadcrumb_text_cmd(
1466 text_system: &mut TextSystem,
1467 x: f32,
1468 baseline: f32,
1469 style: TextStyle,
1470 value: &str,
1471) -> (DrawCmd, f32) {
1472 let layout = text_system.layout_cached(TextLayoutParams {
1473 text: value,
1474 style,
1475 max_width: None,
1476 wrap_mode: WrapMode::NoWrap,
1477 });
1478 let width = layout.metrics.width;
1479 (
1480 DrawCmd::Text(DrawText {
1481 pos: [x, baseline],
1482 color: style.color,
1483 decoration: ailloli_ui_core::TextDecoration::None,
1484 layout,
1485 }),
1486 width,
1487 )
1488}
1489
1490/// Reports whether file-enabled chrome will paint a breadcrumb child.
1491fn model_has_breadcrumb(model: &EditorPaneChromeModel) -> bool {
1492 #[cfg(feature = "files")]
1493 {
1494 model.breadcrumb_uri.is_some()
1495 }
1496 #[cfg(not(feature = "files"))]
1497 {
1498 let _ = model;
1499 false
1500 }
1501}
1502
1503/// Header title and optional display path derived from a document source.
1504struct DocumentMeta {
1505 /// User-visible document title derived from editor metadata.
1506 title: String,
1507 /// Optional provider path or URI text.
1508 path: Option<String>,
1509}
1510
1511/// Resolves legacy `path` first, then local/URI source; memory-only gives none.
1512fn document_title_path(document: &Document) -> Option<DocumentMeta> {
1513 if let Some(path) = document.path.as_deref() {
1514 return Some(DocumentMeta {
1515 title: path_file_name(path).unwrap_or_else(|| "Untitled".to_string()),
1516 path: Some(path.display().to_string()),
1517 });
1518 }
1519 match &document.source {
1520 DocumentSource::Memory => None,
1521 DocumentSource::LocalPath(path) => Some(DocumentMeta {
1522 title: path_file_name(path).unwrap_or_else(|| "Untitled".to_string()),
1523 path: Some(path.display().to_string()),
1524 }),
1525 DocumentSource::Uri(uri) => Some(DocumentMeta {
1526 title: uri.file_name().unwrap_or("Untitled").to_string(),
1527 path: Some(uri.to_string()),
1528 }),
1529 }
1530}
1531
1532/// Returns an owned UTF-8 filename, or `None` for missing/non-UTF-8 names.
1533fn path_file_name(path: &Path) -> Option<String> {
1534 path.file_name()
1535 .and_then(|name| name.to_str())
1536 .map(ToOwned::to_owned)
1537}
1538
1539#[derive(Clone)]
1540/// Internal tab projection consumed by the shared tab-bar renderer.
1541struct ResolvedEditorPaneTab {
1542 /// Stable tab identity used by selection and close actions.
1543 id: String,
1544 /// User-visible tab title after active-document overrides.
1545 title: String,
1546 /// Whether this tab is the resolved active selection.
1547 selected: bool,
1548 /// Whether this tab has unsaved changes.
1549 dirty: bool,
1550 /// Preview or pinned tab behavior.
1551 kind: EditorPaneTabKind,
1552 /// Optional resolved tab icon.
1553 icon: Option<IconId>,
1554 /// Optional resolved icon tint.
1555 icon_tint: Option<Color>,
1556}
1557
1558impl TabsItem for ResolvedEditorPaneTab {
1559 fn id(&self) -> &str {
1560 &self.id
1561 }
1562
1563 fn title(&self) -> &str {
1564 &self.title
1565 }
1566
1567 fn selected(&self) -> bool {
1568 self.selected
1569 }
1570
1571 fn leading_icon(&self) -> Option<&IconId> {
1572 self.icon.as_ref()
1573 }
1574
1575 fn leading_icon_tint(&self) -> Option<Color> {
1576 self.icon_tint
1577 }
1578
1579 fn scope_kind(&self) -> &str {
1580 match self.kind {
1581 EditorPaneTabKind::Text => "task",
1582 EditorPaneTabKind::Code => "file",
1583 EditorPaneTabKind::Other => "",
1584 }
1585 }
1586
1587 fn unread(&self) -> bool {
1588 self.dirty
1589 }
1590}
1591
1592/// Immutable per-frame chrome values resolved from all static/reactive inputs.
1593struct EditorPaneChromeModel {
1594 /// Fully resolved tabs in paint and hit-test order.
1595 tabs: Vec<ResolvedEditorPaneTab>,
1596 /// User-visible title for the active document.
1597 active_title: String,
1598 #[cfg(feature = "files")]
1599 /// Parsed active file URI used to build breadcrumb segments.
1600 breadcrumb_uri: Option<FileUri>,
1601 /// Raw active path retained when URI parsing is unavailable.
1602 active_path: Option<String>,
1603 /// Whether the active document has unsaved changes.
1604 active_dirty: bool,
1605 /// Optional active document icon.
1606 active_icon: Option<IconId>,
1607 /// Optional active icon tint.
1608 active_icon_tint: Option<Color>,
1609}
1610
1611/// Reconstructs tab and close hit rectangles used by the shared painter.
1612///
1613/// Horizontal padding is 8 logical pixels, gaps are 6, visible tabs are
1614/// 120..=220 pixels wide, and each trailing close target is 22 pixels. Tabs
1615/// that cannot fit their 120-pixel minimum are omitted from hit testing.
1616fn tab_hit_layout(rect: Rect, tabs: &[ResolvedEditorPaneTab]) -> Vec<(String, Rect, Rect)> {
1617 let pad_x = 8.0;
1618 let pad_y = 4.0;
1619 let gap = 6.0;
1620 let mut x = rect.x + pad_x;
1621 let y = rect.y + pad_y;
1622 let h = rect.h - pad_y * 2.0;
1623 let x_end = x + (rect.w - pad_x * 2.0).max(0.0);
1624 let mut out = Vec::new();
1625 for tab in tabs {
1626 if x + 120.0 > x_end {
1627 break;
1628 }
1629 let w = 220.0_f32.min((x_end - x).max(120.0));
1630 let tab_r = Rect::new(x, y, w, h);
1631 out.push((
1632 tab.id.clone(),
1633 tab_r,
1634 Rect::new(tab_r.x + tab_r.w - 22.0, tab_r.y, 22.0, tab_r.h),
1635 ));
1636 x += w + gap;
1637 }
1638 out
1639}
1640
1641/// Creates an unbounded no-wrap UI-font label in logical-pixel coordinates.
1642fn label_cmd(
1643 text: &mut TextSystem,
1644 pos: [f32; 2],
1645 color: Color,
1646 px_size: u16,
1647 value: &str,
1648) -> DrawCmd {
1649 DrawCmd::Text(DrawText {
1650 pos,
1651 color,
1652 decoration: ailloli_ui_core::TextDecoration::None,
1653 layout: text.layout_cached(TextLayoutParams {
1654 text: value,
1655 style: TextStyle::new(FontId::Ui, px_size, color),
1656 max_width: None,
1657 wrap_mode: WrapMode::NoWrap,
1658 }),
1659 })
1660}