ailloli_ui_widgets/files/breadcrumb.rs
1//! File URI breadcrumb builder and pure segment derivation helpers.
2
3use std::path::{Path, PathBuf};
4use std::rc::Rc;
5
6use ailloli_ui_core::style::{AlignItems, FlexItemStyle, LayoutSizeHint, LayoutStyle};
7use ailloli_ui_core::{FontId, TextStyle, Theme};
8use ailloli_ui_fs::{FileError, FileUri};
9use ailloli_ui_runtime::component::{IntoView, View};
10use ailloli_ui_runtime::input::EventCtx;
11
12use crate::controls::{Button, ButtonStyle};
13use crate::layout::layout_ext::finish_view_sized;
14use crate::layout::Row;
15use crate::text::Text;
16
17use super::tree::dedupe_file_uris;
18
19/// Shared retained callback for one activated breadcrumb segment.
20type SegmentHandler<A> = Rc<dyn Fn(&mut EventCtx<A>, FileBreadcrumbSegment)>;
21
22/// One cumulative location displayed by [`FileBreadcrumb`].
23///
24/// # Examples
25///
26/// ```
27/// use ailloli_ui_fs::FileUri;
28/// use ailloli_ui_widgets::files::FileBreadcrumbSegment;
29/// let segment = FileBreadcrumbSegment {
30/// uri: FileUri::parse("file:///repo")?, label: "repo".into(), index: 0, last: true,
31/// };
32/// assert_eq!((segment.index, segment.last), (0, true));
33/// # Ok::<(), ailloli_ui_fs::FileError>(())
34/// ```
35#[derive(Clone, Debug, PartialEq, Eq)]
36pub struct FileBreadcrumbSegment {
37 /// Cumulative URI activated by this segment.
38 pub uri: FileUri,
39 /// Visible URI filename or caller-provided root label.
40 pub label: String,
41 /// Zero-based position in the returned segment vector.
42 pub index: usize,
43 /// Whether this is the final/active segment.
44 pub last: bool,
45}
46
47/// Text and spacing styles for a [`FileBreadcrumb`].
48///
49/// All sizes and `gap` are logical pixels. `gap` is forwarded without clamping,
50/// including negative or non-finite values.
51///
52/// # Examples
53///
54/// ```
55/// use ailloli_ui_widgets::files::FileBreadcrumbStyle;
56/// let style = FileBreadcrumbStyle::default();
57/// assert_eq!(style.gap, 6.0);
58/// assert_eq!(style.text.px_size, 12);
59/// ```
60#[derive(Clone, Debug, PartialEq)]
61pub struct FileBreadcrumbStyle {
62 /// Inactive segment text style.
63 pub text: TextStyle,
64 /// Final active segment text style.
65 pub active_text: TextStyle,
66 /// `>` separator text style.
67 pub separator: TextStyle,
68 /// Space between every segment/separator child in logical pixels.
69 pub gap: f32,
70}
71
72/// Uses 12-pixel UI text, default-theme colors, and a six-pixel gap.
73impl Default for FileBreadcrumbStyle {
74 fn default() -> Self {
75 let palette = Theme::default().palette();
76 Self {
77 text: TextStyle::new(FontId::Ui, 12, palette.text_muted),
78 active_text: TextStyle::new(FontId::Ui, 12, palette.text),
79 separator: TextStyle::new(FontId::Ui, 12, palette.text_muted.with_alpha(0.72)),
80 gap: 6.0,
81 }
82 }
83}
84
85/// Horizontal cumulative-path breadcrumb for a file URI.
86///
87/// Without an activation handler segments are plain text. With one, each
88/// segment becomes a text-only button; separators remain non-interactive. `A`
89/// is the surrounding application's action type.
90///
91/// # Examples
92///
93/// ```
94/// use ailloli_ui_fs::FileUri;
95/// use ailloli_ui_widgets::files::FileBreadcrumb;
96/// let breadcrumb = FileBreadcrumb::<()>::new(FileUri::parse("file:///repo/src/lib.rs")?)
97/// .root_label("workspace");
98/// let _ = breadcrumb;
99/// # Ok::<(), ailloli_ui_fs::FileError>(())
100/// ```
101pub struct FileBreadcrumb<A = ()> {
102 /// Standard logical-pixel size and position constraints.
103 pub(crate) layout: LayoutStyle,
104 /// Standard flex-parent participation settings.
105 pub(crate) flex_item: FlexItemStyle,
106 /// Current file or directory URI expanded into segments.
107 uri: FileUri,
108 /// Optional ancestor URI that limits visible segments.
109 base: Option<FileUri>,
110 /// Optional display label replacing the base/root segment.
111 root_label: Option<String>,
112 /// Segment colors and logical-pixel geometry.
113 style: FileBreadcrumbStyle,
114 /// Optional callback receiving an activated ancestor URI.
115 on_activate: Option<SegmentHandler<A>>,
116}
117
118crate::impl_layout_builders!(FileBreadcrumb);
119
120impl<A: 'static> FileBreadcrumb<A> {
121 /// Creates a breadcrumb for `uri` with no base, root label, or callback.
122 ///
123 /// # Examples
124 ///
125 /// ```
126 /// use ailloli_ui_fs::FileUri;
127 /// use ailloli_ui_widgets::files::FileBreadcrumb;
128 /// let breadcrumb = FileBreadcrumb::<()>::new(FileUri::parse("file:///repo/main.rs")?);
129 /// let _ = breadcrumb;
130 /// # Ok::<(), ailloli_ui_fs::FileError>(())
131 /// ```
132 pub fn new(uri: FileUri) -> Self {
133 Self {
134 layout: LayoutStyle::default(),
135 flex_item: FlexItemStyle::default(),
136 uri,
137 base: None,
138 root_label: None,
139 style: FileBreadcrumbStyle::default(),
140 on_activate: None,
141 }
142 }
143
144 /// Creates a breadcrumb from an absolute or working-directory-relative path.
145 ///
146 /// Existing paths are canonicalized; nonexistent paths retain their joined
147 /// lexical form. Relative-path resolution falls back to `/` only if querying
148 /// the current directory fails.
149 ///
150 /// # Errors
151 ///
152 /// Returns [`FileError`] when the resulting native path cannot be represented
153 /// as a local file URI, for example because a component is not valid UTF-8.
154 ///
155 /// # Examples
156 ///
157 /// ```
158 /// use ailloli_ui_widgets::files::FileBreadcrumb;
159 /// let breadcrumb = FileBreadcrumb::<()>::local_path(".")?;
160 /// let _ = breadcrumb;
161 /// # Ok::<(), ailloli_ui_fs::FileError>(())
162 /// ```
163 pub fn local_path(path: impl Into<PathBuf>) -> Result<Self, FileError> {
164 Ok(Self::new(FileUri::local(make_absolute(path.into()))?))
165 }
166
167 /// Sets the first URI shown when it matches the target location/prefix.
168 ///
169 /// The base is used only when scheme and authority match and the target path
170 /// starts with the base path. Otherwise the absolute URI is segmented.
171 ///
172 /// # Examples
173 ///
174 /// ```
175 /// use ailloli_ui_fs::FileUri;
176 /// use ailloli_ui_widgets::files::FileBreadcrumb;
177 /// let target = FileUri::parse("file:///repo/src/lib.rs")?;
178 /// let breadcrumb = FileBreadcrumb::<()>::new(target)
179 /// .base_uri(FileUri::parse("file:///repo")?);
180 /// let _ = breadcrumb;
181 /// # Ok::<(), ailloli_ui_fs::FileError>(())
182 /// ```
183 pub fn base_uri(mut self, base: FileUri) -> Self {
184 self.base = Some(base);
185 self
186 }
187
188 /// Resolves a local path and sets it as the breadcrumb base URI.
189 ///
190 /// Resolution and failure semantics match [`Self::local_path`].
191 ///
192 /// # Errors
193 ///
194 /// Returns [`FileError`] if the native base cannot be converted to a URI.
195 ///
196 /// # Examples
197 ///
198 /// ```
199 /// use ailloli_ui_widgets::files::FileBreadcrumb;
200 /// let breadcrumb = FileBreadcrumb::<()>::local_path(".")?.base_path(".")?;
201 /// let _ = breadcrumb;
202 /// # Ok::<(), ailloli_ui_fs::FileError>(())
203 /// ```
204 pub fn base_path(mut self, path: impl Into<PathBuf>) -> Result<Self, FileError> {
205 self.base = Some(FileUri::local(make_absolute(path.into()))?);
206 Ok(self)
207 }
208
209 /// Overrides the first visible segment label.
210 ///
211 /// The label is stored verbatim, including an empty string. It does not
212 /// change the segment URI or labels after index zero.
213 ///
214 /// # Examples
215 ///
216 /// ```
217 /// use ailloli_ui_fs::FileUri;
218 /// use ailloli_ui_widgets::files::FileBreadcrumb;
219 /// let breadcrumb = FileBreadcrumb::<()>::new(FileUri::parse("file:///repo/src")?)
220 /// .root_label("workspace");
221 /// let _ = breadcrumb;
222 /// # Ok::<(), ailloli_ui_fs::FileError>(())
223 /// ```
224 pub fn root_label(mut self, label: impl Into<String>) -> Self {
225 self.root_label = Some(label.into());
226 self
227 }
228
229 /// Replaces text styles and logical-pixel child spacing.
230 ///
231 /// # Examples
232 ///
233 /// ```
234 /// use ailloli_ui_fs::FileUri;
235 /// use ailloli_ui_widgets::files::{FileBreadcrumb, FileBreadcrumbStyle};
236 /// let breadcrumb = FileBreadcrumb::<()>::new(FileUri::parse("file:///repo")?)
237 /// .breadcrumb_style(FileBreadcrumbStyle::default());
238 /// let _ = breadcrumb;
239 /// # Ok::<(), ailloli_ui_fs::FileError>(())
240 /// ```
241 pub fn breadcrumb_style(mut self, style: FileBreadcrumbStyle) -> Self {
242 self.style = style;
243 self
244 }
245
246 /// Maps an activated segment into an application action.
247 ///
248 /// Installing this callback also changes every segment from static text to
249 /// a text-only button.
250 ///
251 /// # Examples
252 ///
253 /// ```
254 /// use ailloli_ui_fs::FileUri;
255 /// use ailloli_ui_widgets::files::{FileBreadcrumb, FileBreadcrumbSegment};
256 /// enum Action { Open(FileBreadcrumbSegment) }
257 /// let breadcrumb = FileBreadcrumb::<Action>::new(FileUri::parse("file:///repo")?)
258 /// .on_activate(Action::Open);
259 /// let _ = breadcrumb;
260 /// # Ok::<(), ailloli_ui_fs::FileError>(())
261 /// ```
262 pub fn on_activate(mut self, f: impl Fn(FileBreadcrumbSegment) -> A + 'static) -> Self {
263 self.on_activate = Some(Rc::new(move |ctx, segment| ctx.dispatch(f(segment))));
264 self
265 }
266
267 /// Handles activation with direct access to the event context.
268 ///
269 /// Use this form to dispatch zero or multiple actions or request additional
270 /// runtime work.
271 ///
272 /// # Examples
273 ///
274 /// ```
275 /// use ailloli_ui_fs::FileUri;
276 /// use ailloli_ui_widgets::files::FileBreadcrumb;
277 /// let breadcrumb = FileBreadcrumb::<()>::new(FileUri::parse("file:///repo")?)
278 /// .on_activate_ctx(|_ctx, _segment| {});
279 /// let _ = breadcrumb;
280 /// # Ok::<(), ailloli_ui_fs::FileError>(())
281 /// ```
282 pub fn on_activate_ctx(
283 mut self,
284 f: impl Fn(&mut EventCtx<A>, FileBreadcrumbSegment) + 'static,
285 ) -> Self {
286 self.on_activate = Some(Rc::new(f));
287 self
288 }
289}
290
291/// Converts segments into a nowrap, vertically centered row of text/buttons.
292impl<A: 'static> IntoView<A> for FileBreadcrumb<A> {
293 fn into_view(self) -> View<A> {
294 let mut row = Row::new()
295 .gap(self.style.gap)
296 .align_items(AlignItems::Center);
297 row.layout = self.layout;
298
299 let segments =
300 breadcrumb_segments(&self.uri, self.base.as_ref(), self.root_label.as_deref());
301 for (idx, segment) in segments.iter().cloned().enumerate() {
302 if idx > 0 {
303 row = row.child(Text::new(">").style(self.style.separator).nowrap());
304 }
305
306 let text_style = if segment.last {
307 self.style.active_text
308 } else {
309 self.style.text
310 };
311 if let Some(handler) = &self.on_activate {
312 let handler = handler.clone();
313 let segment_for_click = segment.clone();
314 row = row.child(
315 Button::new()
316 .button_style(ButtonStyle::text_only(text_style.color))
317 .child(Text::new(segment.label).style(text_style).nowrap())
318 .on_click_ctx(move |ctx| handler(ctx, segment_for_click.clone())),
319 );
320 } else {
321 row = row.child(Text::new(segment.label).style(text_style).nowrap());
322 }
323 }
324
325 finish_view_sized(
326 row.into_view(),
327 self.flex_item,
328 LayoutSizeHint::from_layout(self.layout),
329 )
330 }
331}
332
333/// Builds cumulative breadcrumb segments for a URI and optional base.
334///
335/// A base applies only when scheme/authority match and the target path has the
336/// base's byte prefix. Duplicate URIs are removed. A root-only URI may yield an
337/// empty vector because it has no non-empty path component.
338///
339/// # Examples
340///
341/// ```
342/// use ailloli_ui_fs::FileUri;
343/// use ailloli_ui_widgets::files::breadcrumb_segments;
344/// let base = FileUri::parse("file:///repo")?;
345/// let target = FileUri::parse("file:///repo/src/lib.rs")?;
346/// let labels: Vec<_> = breadcrumb_segments(&target, Some(&base), Some("workspace"))
347/// .into_iter().map(|segment| segment.label).collect();
348/// assert_eq!(labels, ["workspace", "src", "lib.rs"]);
349/// # Ok::<(), ailloli_ui_fs::FileError>(())
350/// ```
351pub fn breadcrumb_segments(
352 uri: &FileUri,
353 base: Option<&FileUri>,
354 root_label: Option<&str>,
355) -> Vec<FileBreadcrumbSegment> {
356 let Some(base) =
357 base.filter(|base| same_location(base, uri) && uri.path().starts_with(base.path()))
358 else {
359 return segments_from_absolute(uri, root_label);
360 };
361
362 let mut uris = vec![base.clone()];
363 let mut current_path = base.path().trim_end_matches('/').to_string();
364 let relative = uri
365 .path()
366 .trim_start_matches(base.path().trim_end_matches('/'))
367 .trim_start_matches('/');
368 for part in relative.split('/').filter(|part| !part.is_empty()) {
369 current_path = if current_path == "/" {
370 format!("/{part}")
371 } else {
372 format!("{current_path}/{part}")
373 };
374 if let Ok(next) = FileUri::new(
375 uri.scheme().to_string(),
376 uri.authority().map(str::to_string),
377 current_path.clone(),
378 ) {
379 uris.push(next);
380 }
381 }
382 make_segments(dedupe_file_uris(uris), root_label)
383}
384
385/// Expands every non-empty absolute path component into a cumulative URI.
386fn segments_from_absolute(uri: &FileUri, root_label: Option<&str>) -> Vec<FileBreadcrumbSegment> {
387 let mut current = String::new();
388 let mut uris = Vec::new();
389 for part in uri.path().split('/').filter(|part| !part.is_empty()) {
390 current.push('/');
391 current.push_str(part);
392 if let Ok(next) = FileUri::new(
393 uri.scheme().to_string(),
394 uri.authority().map(str::to_string),
395 current.clone(),
396 ) {
397 uris.push(next);
398 }
399 }
400 make_segments(uris, root_label)
401}
402
403/// Assigns labels, contiguous indices, and exactly one final marker when nonempty.
404fn make_segments(uris: Vec<FileUri>, root_label: Option<&str>) -> Vec<FileBreadcrumbSegment> {
405 let last_index = uris.len().saturating_sub(1);
406 uris.into_iter()
407 .enumerate()
408 .map(|(index, uri)| {
409 let label = if index == 0 {
410 root_label
411 .map(str::to_string)
412 .or_else(|| uri.file_name().map(str::to_string))
413 .unwrap_or_else(|| uri.path().to_string())
414 } else {
415 uri.file_name()
416 .map(str::to_string)
417 .unwrap_or_else(|| uri.path().to_string())
418 };
419 FileBreadcrumbSegment {
420 uri,
421 label,
422 index,
423 last: index == last_index,
424 }
425 })
426 .collect()
427}
428
429/// Compares scheme and optional authority without considering path.
430fn same_location(a: &FileUri, b: &FileUri) -> bool {
431 a.scheme() == b.scheme() && a.authority() == b.authority()
432}
433
434/// Makes a path absolute and canonicalizes it when the target exists.
435fn make_absolute(path: PathBuf) -> PathBuf {
436 let path = if path.is_absolute() {
437 path
438 } else {
439 std::env::current_dir()
440 .unwrap_or_else(|_| Path::new("/").to_path_buf())
441 .join(path)
442 };
443 path.canonicalize().unwrap_or(path)
444}
445
446#[cfg(test)]
447/// Verifies base trimming, custom root labels, order, and final-segment marking.
448mod tests {
449 use super::*;
450
451 #[test]
452 fn breadcrumb_segments_trim_base_path_and_use_root_label() {
453 let base = uri("/repo");
454 let file = uri("/repo/sample_app/src/view/panes/left.rs");
455
456 let labels = breadcrumb_segments(&file, Some(&base), Some("ailloli_ui"))
457 .into_iter()
458 .map(|segment| (segment.label, segment.last))
459 .collect::<Vec<_>>();
460
461 assert_eq!(
462 labels,
463 [
464 ("ailloli_ui".to_string(), false),
465 ("sample_app".to_string(), false),
466 ("src".to_string(), false),
467 ("view".to_string(), false),
468 ("panes".to_string(), false),
469 ("left.rs".to_string(), true),
470 ]
471 );
472 }
473
474 /// Creates a local file URI fixture from an absolute path.
475 fn uri(path: &str) -> FileUri {
476 FileUri::parse(format!("file://{path}")).expect("file uri")
477 }
478}