Skip to main content

fc_ui/capabilities/media/
image_viewer.rs

1//! ImageViewer/Lightbox component for displaying images in a fullscreen overlay.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use std::rc::Rc;
5
6use crate::capabilities::foundation::theme::use_theme;
7use crate::capabilities::primitives::button::{Button, ButtonSize, ButtonVariant};
8
9actions!(
10    image_viewer,
11    [
12        ImageViewerClose,
13        ImageViewerNext,
14        ImageViewerPrev,
15        ImageViewerZoomIn,
16        ImageViewerZoomOut,
17        ImageViewerResetZoom
18    ]
19);
20
21#[derive(Clone)]
22pub struct ImageItem {
23    pub src: SharedString,
24    pub alt: Option<SharedString>,
25    pub caption: Option<SharedString>,
26}
27
28impl ImageItem {
29    pub fn new(src: impl Into<SharedString>) -> Self {
30        Self {
31            src: src.into(),
32            alt: None,
33            caption: None,
34        }
35    }
36
37    pub fn alt(mut self, alt: impl Into<SharedString>) -> Self {
38        self.alt = Some(alt.into());
39        self
40    }
41
42    pub fn caption(mut self, caption: impl Into<SharedString>) -> Self {
43        self.caption = Some(caption.into());
44        self
45    }
46}
47
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub enum ImageViewerSize {
50    Auto,
51    Contain,
52    Cover,
53    Custom(f32),
54}
55
56impl Default for ImageViewerSize {
57    fn default() -> Self {
58        Self::Contain
59    }
60}
61
62const MIN_ZOOM: f32 = 0.1;
63const MAX_ZOOM: f32 = 5.0;
64const ZOOM_STEP: f32 = 0.25;
65
66type CloseCallback = Rc<dyn Fn(&mut Window, &mut App)>;
67
68pub struct ImageViewerState {
69    images: Vec<ImageItem>,
70    current_index: usize,
71    zoom: f32,
72    pan_offset: Point<Pixels>,
73    _is_panning: bool,
74    _last_mouse_pos: Point<Pixels>,
75    _loading: bool,
76    show_thumbnails: bool,
77    _fit_mode: ImageViewerSize,
78}
79
80impl ImageViewerState {
81    pub fn new(images: Vec<ImageItem>) -> Self {
82        Self {
83            images,
84            current_index: 0,
85            zoom: 1.0,
86            pan_offset: point(px(0.0), px(0.0)),
87            _is_panning: false,
88            _last_mouse_pos: point(px(0.0), px(0.0)),
89            _loading: false,
90            show_thumbnails: true,
91            _fit_mode: ImageViewerSize::default(),
92        }
93    }
94
95    pub fn set_images(&mut self, images: Vec<ImageItem>, cx: &mut Context<Self>) {
96        self.images = images;
97        self.current_index = 0;
98        self.reset_view();
99        cx.notify();
100    }
101
102    pub fn go_to(&mut self, index: usize, cx: &mut Context<Self>) {
103        if index < self.images.len() {
104            self.current_index = index;
105            self.reset_view();
106            cx.notify();
107        }
108    }
109
110    pub fn next(&mut self, cx: &mut Context<Self>) {
111        if self.current_index < self.images.len().saturating_sub(1) {
112            self.current_index += 1;
113            self.reset_view();
114            cx.notify();
115        }
116    }
117
118    pub fn prev(&mut self, cx: &mut Context<Self>) {
119        if self.current_index > 0 {
120            self.current_index -= 1;
121            self.reset_view();
122            cx.notify();
123        }
124    }
125
126    pub fn zoom_in(&mut self, cx: &mut Context<Self>) {
127        self.zoom = (self.zoom + ZOOM_STEP).min(MAX_ZOOM);
128        cx.notify();
129    }
130
131    pub fn zoom_out(&mut self, cx: &mut Context<Self>) {
132        self.zoom = (self.zoom - ZOOM_STEP).max(MIN_ZOOM);
133        cx.notify();
134    }
135
136    pub fn reset_zoom(&mut self, cx: &mut Context<Self>) {
137        self.zoom = 1.0;
138        self.pan_offset = point(px(0.0), px(0.0));
139        cx.notify();
140    }
141
142    pub fn set_zoom(&mut self, zoom: f32, cx: &mut Context<Self>) {
143        self.zoom = zoom.clamp(MIN_ZOOM, MAX_ZOOM);
144        cx.notify();
145    }
146
147    pub fn toggle_thumbnails(&mut self, cx: &mut Context<Self>) {
148        self.show_thumbnails = !self.show_thumbnails;
149        cx.notify();
150    }
151
152    fn reset_view(&mut self) {
153        self.zoom = 1.0;
154        self.pan_offset = point(px(0.0), px(0.0));
155    }
156
157    pub fn current_image(&self) -> Option<&ImageItem> {
158        self.images.get(self.current_index)
159    }
160
161    pub fn has_next(&self) -> bool {
162        self.current_index < self.images.len().saturating_sub(1)
163    }
164
165    pub fn has_prev(&self) -> bool {
166        self.current_index > 0
167    }
168
169    pub fn image_count(&self) -> usize {
170        self.images.len()
171    }
172
173    pub fn current_index(&self) -> usize {
174        self.current_index
175    }
176
177    pub fn zoom(&self) -> f32 {
178        self.zoom
179    }
180
181    pub fn is_zoomed(&self) -> bool {
182        (self.zoom - 1.0).abs() > 0.01
183    }
184}
185
186pub struct ImageViewer {
187    focus_handle: FocusHandle,
188    has_focused: bool,
189    state: Entity<ImageViewerState>,
190    on_close: Option<CloseCallback>,
191    close_on_backdrop_click: bool,
192    close_on_escape: bool,
193    show_controls: bool,
194    show_counter: bool,
195    show_thumbnails: bool,
196    style: StyleRefinement,
197}
198
199impl ImageViewer {
200    pub fn new(state: Entity<ImageViewerState>, cx: &mut Context<Self>) -> Self {
201        Self {
202            focus_handle: cx.focus_handle(),
203            has_focused: false,
204            state,
205            on_close: None,
206            close_on_backdrop_click: true,
207            close_on_escape: true,
208            show_controls: true,
209            show_counter: true,
210            show_thumbnails: true,
211            style: StyleRefinement::default(),
212        }
213    }
214
215    pub fn on_close(mut self, handler: impl Fn(&mut Window, &mut App) + 'static) -> Self {
216        self.on_close = Some(Rc::new(handler));
217        self
218    }
219
220    pub fn close_on_backdrop_click(mut self, close: bool) -> Self {
221        self.close_on_backdrop_click = close;
222        self
223    }
224
225    pub fn close_on_escape(mut self, close: bool) -> Self {
226        self.close_on_escape = close;
227        self
228    }
229
230    pub fn show_controls(mut self, show: bool) -> Self {
231        self.show_controls = show;
232        self
233    }
234
235    pub fn show_counter(mut self, show: bool) -> Self {
236        self.show_counter = show;
237        self
238    }
239
240    pub fn show_thumbnails(mut self, show: bool) -> Self {
241        self.show_thumbnails = show;
242        self
243    }
244
245    fn handle_close(&self, window: &mut Window, cx: &mut App) {
246        if let Some(handler) = &self.on_close {
247            (handler)(window, cx);
248        }
249    }
250}
251
252impl Styled for ImageViewer {
253    fn style(&mut self) -> &mut StyleRefinement {
254        &mut self.style
255    }
256}
257
258impl Focusable for ImageViewer {
259    fn focus_handle(&self, _: &App) -> FocusHandle {
260        self.focus_handle.clone()
261    }
262}
263
264impl EventEmitter<()> for ImageViewer {}
265
266impl Render for ImageViewer {
267    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
268        let theme = use_theme(cx);
269        let state = self.state.read(cx);
270        let current_image = state.current_image().cloned();
271        let current_index = state.current_index();
272        let image_count = state.image_count();
273        let zoom = state.zoom();
274        let has_prev = state.has_prev();
275        let has_next = state.has_next();
276        let images = state.images.clone();
277        let _pan_offset = state.pan_offset;
278        let show_thumbs = self.show_thumbnails && state.show_thumbnails && image_count > 1;
279
280        let viewer_entity = cx.entity().clone();
281        let state_entity = self.state.clone();
282
283        if !self.has_focused {
284            window.focus(&self.focus_handle);
285            self.has_focused = true;
286        }
287
288        let close_handler = self.on_close.clone();
289        let close_on_escape = self.close_on_escape;
290        let close_on_backdrop = self.close_on_backdrop_click;
291
292        div()
293            .id("image-viewer-overlay")
294            .key_context("ImageViewer")
295            .track_focus(&self.focus_handle)
296            .absolute()
297            .inset_0()
298            .flex()
299            .flex_col()
300            .bg(gpui::black().opacity(0.9))
301            .on_action({
302                let viewer_entity = viewer_entity.clone();
303                move |_: &ImageViewerClose, window, cx| {
304                    if close_on_escape {
305                        cx.update_entity(&viewer_entity, |viewer, cx| {
306                            viewer.handle_close(window, cx);
307                        });
308                    }
309                }
310            })
311            .on_action({
312                let state_entity = state_entity.clone();
313                move |_: &ImageViewerNext, _, cx| {
314                    cx.update_entity(&state_entity, |state, cx| state.next(cx));
315                }
316            })
317            .on_action({
318                let state_entity = state_entity.clone();
319                move |_: &ImageViewerPrev, _, cx| {
320                    cx.update_entity(&state_entity, |state, cx| state.prev(cx));
321                }
322            })
323            .on_action({
324                let state_entity = state_entity.clone();
325                move |_: &ImageViewerZoomIn, _, cx| {
326                    cx.update_entity(&state_entity, |state, cx| state.zoom_in(cx));
327                }
328            })
329            .on_action({
330                let state_entity = state_entity.clone();
331                move |_: &ImageViewerZoomOut, _, cx| {
332                    cx.update_entity(&state_entity, |state, cx| state.zoom_out(cx));
333                }
334            })
335            .on_action({
336                let state_entity = state_entity.clone();
337                move |_: &ImageViewerResetZoom, _, cx| {
338                    cx.update_entity(&state_entity, |state, cx| state.reset_zoom(cx));
339                }
340            })
341            .child(
342                div()
343                    .id("image-viewer-header")
344                    .flex()
345                    .items_center()
346                    .justify_between()
347                    .px(px(16.0))
348                    .py(px(12.0))
349                    .child(div().flex().items_center().gap(px(8.0)).when(
350                        self.show_counter && image_count > 1,
351                        |this| {
352                            this.child(
353                                div()
354                                    .text_size(px(14.0))
355                                    .text_color(gpui::white())
356                                    .font_family(theme.tokens.font_family.clone())
357                                    .child(format!("{} of {}", current_index + 1, image_count)),
358                            )
359                        },
360                    ))
361                    .child(div().flex().items_center().gap(px(4.0)).when(
362                        self.show_controls,
363                        |this| {
364                            let state_entity = state_entity.clone();
365                            let state_entity2 = state_entity.clone();
366                            let state_entity3 = state_entity.clone();
367
368                            this.child(
369                                Button::new("zoom-out", "")
370                                    .variant(ButtonVariant::Ghost)
371                                    .size(ButtonSize::Icon)
372                                    .icon("zoom-out")
373                                    .on_click(move |_, _, cx| {
374                                        cx.update_entity(&state_entity, |state, cx| {
375                                            state.zoom_out(cx)
376                                        });
377                                    }),
378                            )
379                            .child(
380                                div()
381                                    .min_w(px(50.0))
382                                    .text_size(px(13.0))
383                                    .text_color(gpui::white())
384                                    .font_family(theme.tokens.font_family.clone())
385                                    .text_center()
386                                    .child(format!("{}%", (zoom * 100.0) as i32)),
387                            )
388                            .child(
389                                Button::new("zoom-in", "")
390                                    .variant(ButtonVariant::Ghost)
391                                    .size(ButtonSize::Icon)
392                                    .icon("zoom-in")
393                                    .on_click(move |_, _, cx| {
394                                        cx.update_entity(&state_entity2, |state, cx| {
395                                            state.zoom_in(cx)
396                                        });
397                                    }),
398                            )
399                            .child(
400                                div()
401                                    .w(px(1.0))
402                                    .h(px(20.0))
403                                    .bg(gpui::white().opacity(0.2))
404                                    .mx(px(8.0)),
405                            )
406                            .child(
407                                Button::new("reset-zoom", "Reset")
408                                    .variant(ButtonVariant::Ghost)
409                                    .size(ButtonSize::Sm)
410                                    .on_click(move |_, _, cx| {
411                                        cx.update_entity(&state_entity3, |state, cx| {
412                                            state.reset_zoom(cx)
413                                        });
414                                    }),
415                            )
416                        },
417                    ))
418                    .child({
419                        let viewer_entity = viewer_entity.clone();
420                        Button::new("close-viewer", "")
421                            .variant(ButtonVariant::Ghost)
422                            .size(ButtonSize::Icon)
423                            .icon("x")
424                            .on_click(move |_, window, cx| {
425                                cx.update_entity(&viewer_entity, |viewer, cx| {
426                                    viewer.handle_close(window, cx);
427                                });
428                            })
429                    }),
430            )
431            .child(
432                div()
433                    .id("image-viewer-content")
434                    .flex_1()
435                    .flex()
436                    .items_center()
437                    .justify_center()
438                    .relative()
439                    .overflow_hidden()
440                    .when(close_on_backdrop, |this| {
441                        let close_handler = close_handler.clone();
442                        this.on_mouse_down(MouseButton::Left, move |_, window, cx| {
443                            if let Some(handler) = &close_handler {
444                                (handler)(window, cx);
445                            }
446                        })
447                    })
448                    .when(has_prev, |this| {
449                        let state_entity = state_entity.clone();
450                        this.child(
451                            div()
452                                .id("prev-button")
453                                .absolute()
454                                .left(px(16.0))
455                                .top_0()
456                                .bottom_0()
457                                .flex()
458                                .items_center()
459                                .child(
460                                    Button::new("prev-image", "")
461                                        .variant(ButtonVariant::Secondary)
462                                        .size(ButtonSize::Icon)
463                                        .icon("arrow-left")
464                                        .on_click(move |_, _, cx| {
465                                            cx.update_entity(&state_entity, |state, cx| {
466                                                state.prev(cx)
467                                            });
468                                        }),
469                                ),
470                        )
471                    })
472                    .when(has_next, |this| {
473                        let state_entity = state_entity.clone();
474                        this.child(
475                            div()
476                                .id("next-button")
477                                .absolute()
478                                .right(px(16.0))
479                                .top_0()
480                                .bottom_0()
481                                .flex()
482                                .items_center()
483                                .child(
484                                    Button::new("next-image", "")
485                                        .variant(ButtonVariant::Secondary)
486                                        .size(ButtonSize::Icon)
487                                        .icon("arrow-right")
488                                        .on_click(move |_, _, cx| {
489                                            cx.update_entity(&state_entity, |state, cx| {
490                                                state.next(cx)
491                                            });
492                                        }),
493                                ),
494                        )
495                    })
496                    .when_some(current_image.clone(), |this, image| {
497                        this.child(
498                            div()
499                                .id("image-container")
500                                .flex()
501                                .items_center()
502                                .justify_center()
503                                .on_mouse_down(MouseButton::Left, |_, _, cx| {
504                                    cx.stop_propagation();
505                                })
506                                .child(
507                                    img(image.src.clone())
508                                        .max_w(relative(0.9 * zoom))
509                                        .max_h(relative(0.8 * zoom))
510                                        .object_fit(ObjectFit::Contain),
511                                ),
512                        )
513                    }),
514            )
515            .when_some(current_image.as_ref().and_then(|i| i.caption.clone()), {
516                |this, caption| {
517                    this.child(
518                        div()
519                            .id("image-caption")
520                            .px(px(16.0))
521                            .py(px(8.0))
522                            .text_size(px(14.0))
523                            .text_color(gpui::white().opacity(0.8))
524                            .font_family(theme.tokens.font_family.clone())
525                            .text_center()
526                            .child(caption),
527                    )
528                }
529            })
530            .when(show_thumbs, |this| {
531                this.child(
532                    div()
533                        .id("thumbnail-strip")
534                        .flex()
535                        .items_center()
536                        .justify_center()
537                        .gap(px(8.0))
538                        .px(px(16.0))
539                        .py(px(12.0))
540                        .bg(gpui::black().opacity(0.5))
541                        .children(images.iter().enumerate().map(|(idx, image)| {
542                            let is_current = idx == current_index;
543                            let state_entity = state_entity.clone();
544
545                            div()
546                                .id(ElementId::Name(format!("thumb-{}", idx).into()))
547                                .size(px(60.0))
548                                .rounded(px(4.0))
549                                .overflow_hidden()
550                                .border_2()
551                                .border_color(if is_current {
552                                    theme.tokens.primary
553                                } else {
554                                    gpui::transparent_black()
555                                })
556                                .cursor(CursorStyle::PointingHand)
557                                .hover(|style| style.opacity(0.8))
558                                .on_mouse_down(MouseButton::Left, move |_, _window, cx| {
559                                    cx.stop_propagation();
560                                    cx.update_entity(&state_entity, |state, cx| {
561                                        state.go_to(idx, cx)
562                                    });
563                                })
564                                .child(
565                                    img(image.src.clone())
566                                        .size_full()
567                                        .object_fit(ObjectFit::Cover),
568                                )
569                        })),
570                )
571            })
572    }
573}
574
575pub fn init_image_viewer(cx: &mut App) {
576    if !crate::capabilities::foundation::initialization::begin(cx, "image-viewer") {
577        return;
578    }
579    cx.bind_keys([
580        KeyBinding::new("escape", ImageViewerClose, Some("ImageViewer")),
581        KeyBinding::new("left", ImageViewerPrev, Some("ImageViewer")),
582        KeyBinding::new("right", ImageViewerNext, Some("ImageViewer")),
583        KeyBinding::new("up", ImageViewerZoomIn, Some("ImageViewer")),
584        KeyBinding::new("down", ImageViewerZoomOut, Some("ImageViewer")),
585        KeyBinding::new("0", ImageViewerResetZoom, Some("ImageViewer")),
586        KeyBinding::new("+", ImageViewerZoomIn, Some("ImageViewer")),
587        KeyBinding::new("-", ImageViewerZoomOut, Some("ImageViewer")),
588        KeyBinding::new("=", ImageViewerZoomIn, Some("ImageViewer")),
589    ]);
590}