woocraft 0.4.5

GPUI components lib for Woocraft design system.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
//! Date picker component with popup calendar and optional presets.
//!
//! DatePicker wraps the Calendar component in a Popover, providing a text input
//! that displays the Calendar on click or keyboard activation. Supports single
//! date or date range selection with optional preset buttons (e.g., "Today",
//! "Last 7 Days"). Formats selected dates for display, validates against
//! disabled date rules, and emits change events.
//!
//! # Modes
//! - **Single Date**: Pick one specific date (default)
//! - **Date Range**: Pick start and end dates for a range (via `.range()`)
//!
//! # Features
//! - **Popup Calendar**: Click input to open calendar picker
//! - **Keyboard Support**: Enter/Escape to confirm/cancel, arrow keys in
//!   calendar
//! - **Date Presets**: Quick-select buttons for common ranges ("Today", "Last
//!   30 Days", etc.)
//! - **Disabled Dates**: Block specific dates via custom matcher (e.g.,
//!   weekends)
//! - **Format Control**: Customize date display format
//! - **Clear Button**: Delete button to unset the date
//!
//! # Example
//! ```rust,ignore
//! let date_picker = cx.new(|cx| DatePickerState::new(window, cx));
//! let date_range_picker = cx.new(|cx| DatePickerState::range(window, cx));
//! ```

use std::rc::Rc;

use chrono::NaiveDate;
use gpui::{
  AnyElement, App, AppContext, ClickEvent, Context, ElementId, Empty, Entity, EventEmitter,
  FocusHandle, Focusable, InteractiveElement as _, IntoElement, KeyBinding, MouseButton,
  ParentElement as _, Render, RenderOnce, SharedString, StyleRefinement, Styled, Subscription,
  Window, div, prelude::FluentBuilder as _, px,
};

use crate::{
  ActiveTheme, Anchor, Button, ButtonVariants as _, Calendar, CalendarEvent, CalendarState, Date,
  Delete, Disableable, Icon, IconName, Matcher, Popover, Selectable, Sizable, Size, StyledExt as _,
  actions::{Cancel, Confirm},
  h_flex, translate_woocraft, v_flex,
};

const CONTEXT: &str = "DatePicker";

pub(crate) fn init(cx: &mut App) {
  cx.bind_keys([
    KeyBinding::new("enter", Confirm { secondary: false }, Some(CONTEXT)),
    KeyBinding::new("escape", Cancel, Some(CONTEXT)),
    KeyBinding::new("delete", Delete, Some(CONTEXT)),
    KeyBinding::new("backspace", Delete, Some(CONTEXT)),
  ]);
}

/// Events emitted by the DatePicker.
///
/// Currently emits `Change` event when the user selects a date or date range.
#[derive(Clone)]
pub enum DatePickerEvent {
  /// Emitted when user selects a date or closes the calendar with a selection.
  Change(Date),
}

/// Preset value for date range selection.
///
/// Represents either a single date or a date range that can be applied via a
/// quick-select button.
#[derive(Clone)]
pub enum DateRangePresetValue {
  /// Single date preset.
  Single(NaiveDate),
  /// Date range preset (start, end).
  Range(NaiveDate, NaiveDate),
}

/// Quick-select preset button for date picker.
///
/// Provides a label and corresponding date(s) that users can click to quickly
/// populate the date picker without manually selecting from the calendar.
/// Useful for common ranges like "Today", "Last 7 Days", "This Month", etc.
#[derive(Clone)]
pub struct DateRangePreset {
  label: SharedString,
  value: DateRangePresetValue,
}

impl DateRangePreset {
  /// Create a preset with a single date.
  ///
  /// # Arguments
  /// * `label` - Display text for the preset button
  /// * `date` - The date to apply
  pub fn single(label: impl Into<SharedString>, date: NaiveDate) -> Self {
    Self {
      label: label.into(),
      value: DateRangePresetValue::Single(date),
    }
  }

  /// Create a preset with a date range.
  ///
  /// # Arguments
  /// * `label` - Display text for the preset button
  /// * `start` - Start date of the range
  /// * `end` - End date of the range
  pub fn range(label: impl Into<SharedString>, start: NaiveDate, end: NaiveDate) -> Self {
    Self {
      label: label.into(),
      value: DateRangePresetValue::Range(start, end),
    }
  }
}

/// Internal state management for the date picker component.
///
/// Manages the open/closed state of the popup calendar, the selected date(s),
/// date format, disabled date rules, and subscriptions to calendar selection
/// events. Use `DatePickerState::new()` for single-date mode or `.range()` for
/// date range mode.
pub struct DatePickerState {
  focus_handle: FocusHandle,
  date: Date,
  open: bool,
  calendar: Entity<CalendarState>,
  date_format: SharedString,
  number_of_months: usize,
  disabled_matcher: Option<Rc<Matcher>>,
  _subscriptions: Vec<Subscription>,
}

impl Focusable for DatePickerState {
  fn focus_handle(&self, _: &App) -> FocusHandle {
    self.focus_handle.clone()
  }
}

impl EventEmitter<DatePickerEvent> for DatePickerState {}

impl DatePickerState {
  /// Create a date picker for selecting a single date.
  ///
  /// Starts with no date selected. User can click the input or press Enter to
  /// open the calendar.
  pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
    Self::new_with_range(false, window, cx)
  }

  /// Create a date picker for selecting a date range.
  ///
  /// Starts with no range selected. User can click the input or press Enter to
  /// open the calendar. Calendar will display 2 months to make range
  /// selection easier.
  pub fn range(window: &mut Window, cx: &mut Context<Self>) -> Self {
    Self::new_with_range(true, window, cx)
  }

  fn new_with_range(is_range: bool, window: &mut Window, cx: &mut Context<Self>) -> Self {
    let date = if is_range {
      Date::Range(None, None)
    } else {
      Date::Single(None)
    };

    let calendar = cx.new(|cx| {
      let mut this = CalendarState::new(window, cx);
      this.set_date(date, window, cx);
      this
    });

    let subscriptions = vec![cx.subscribe_in(
      &calendar,
      window,
      |this, _, event: &CalendarEvent, window, cx| match event {
        CalendarEvent::Selected(date) => {
          this.update_date(*date, true, window, cx);
          this.focus_handle.focus(window);
        }
      },
    )];

    Self {
      focus_handle: cx.focus_handle(),
      date,
      calendar,
      open: false,
      date_format: "%Y/%m/%d".into(),
      number_of_months: 1,
      disabled_matcher: None,
      _subscriptions: subscriptions,
    }
  }

  /// Set display format, default: `%Y/%m/%d`.
  pub fn date_format(mut self, format: impl Into<SharedString>) -> Self {
    self.date_format = format.into();
    self
  }

  /// Set number of months in calendar view, default is 1.
  pub fn number_of_months(mut self, number_of_months: usize) -> Self {
    self.number_of_months = number_of_months;
    self
  }

  /// Get current date value.
  pub fn date(&self) -> Date {
    self.date
  }

  /// Set date value.
  pub fn set_date(&mut self, date: impl Into<Date>, window: &mut Window, cx: &mut Context<Self>) {
    self.update_date(date.into(), false, window, cx);
  }

  /// Set disabled matcher for the calendar.
  pub fn disabled_matcher(mut self, disabled: impl Into<Matcher>) -> Self {
    self.disabled_matcher = Some(Rc::new(disabled.into()));
    self
  }

  fn update_date(&mut self, date: Date, emit: bool, window: &mut Window, cx: &mut Context<Self>) {
    self.date = date;
    self.calendar.update(cx, |calendar, cx| {
      calendar.set_date(date, window, cx);
    });
    self.open = false;
    if emit {
      cx.emit(DatePickerEvent::Change(date));
    }
    cx.notify();
  }

  fn set_calendar_disabled_matcher(&mut self, _: &mut Window, cx: &mut Context<Self>) {
    let matcher = self.disabled_matcher.clone();
    self.calendar.update(cx, |state, _| {
      state.disabled_matcher = matcher;
    });
  }

  fn on_escape(&mut self, _: &Cancel, window: &mut Window, cx: &mut Context<Self>) {
    if !self.open {
      cx.propagate();
      return;
    }

    self.open = false;
    self.focus_back_if_need(window, cx);
    cx.notify();
  }

  fn on_enter(&mut self, _: &Confirm, _: &mut Window, cx: &mut Context<Self>) {
    if !self.open {
      self.open = true;
      cx.notify();
    }
  }

  fn on_delete(&mut self, _: &Delete, window: &mut Window, cx: &mut Context<Self>) {
    self.clean(&ClickEvent::default(), window, cx);
  }

  // If focus stays inside date picker when closing popover, focus back to input.
  fn focus_back_if_need(&mut self, window: &mut Window, cx: &mut Context<Self>) {
    if self.focus_handle.contains_focused(window, cx) {
      self.focus_handle.focus(window);
    }
  }

  fn set_open(&mut self, open: bool, window: &mut Window, cx: &mut Context<Self>) {
    if self.open == open {
      return;
    }

    self.open = open;
    if !open {
      self.focus_back_if_need(window, cx);
    }
    cx.notify();
  }

  fn clean(&mut self, _: &ClickEvent, window: &mut Window, cx: &mut Context<Self>) {
    cx.stop_propagation();
    match self.date {
      Date::Single(_) => self.update_date(Date::Single(None), true, window, cx),
      Date::Range(..) => self.update_date(Date::Range(None, None), true, window, cx),
    }
  }

  fn select_preset(
    &mut self, preset: &DateRangePreset, window: &mut Window, cx: &mut Context<Self>,
  ) {
    match preset.value {
      DateRangePresetValue::Single(single) => {
        self.update_date(Date::Single(Some(single)), true, window, cx)
      }
      DateRangePresetValue::Range(start, end) => {
        self.update_date(Date::Range(Some(start), Some(end)), true, window, cx)
      }
    }
  }
}

/// A DatePicker element.
#[derive(IntoElement)]
pub struct DatePicker {
  id: ElementId,
  style: StyleRefinement,
  state: Entity<DatePickerState>,
  cleanable: bool,
  placeholder: Option<SharedString>,
  size: Size,
  number_of_months: usize,
  presets: Option<Vec<DateRangePreset>>,
  appearance: bool,
  disabled: bool,
}

impl_sizable!(DatePicker);

impl Focusable for DatePicker {
  fn focus_handle(&self, cx: &App) -> FocusHandle {
    self.state.focus_handle(cx)
  }
}

impl_styled!(DatePicker);
impl_disableable!(DatePicker);

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

impl DatePicker {
  /// Create a new DatePicker with the given [`DatePickerState`].
  pub fn new(state: &Entity<DatePickerState>) -> Self {
    Self {
      id: ("date-picker", state.entity_id()).into(),
      state: state.clone(),
      cleanable: false,
      placeholder: None,
      size: Size::default(),
      style: StyleRefinement::default(),
      number_of_months: 2,
      presets: None,
      appearance: true,
      disabled: false,
    }
  }

  /// Set placeholder.
  pub fn placeholder(mut self, placeholder: impl Into<SharedString>) -> Self {
    self.placeholder = Some(placeholder.into());
    self
  }

  /// Set whether clear button should be shown when value exists.
  pub fn cleanable(mut self, cleanable: bool) -> Self {
    self.cleanable = cleanable;
    self
  }

  /// Set preset ranges for date selection.
  pub fn presets(mut self, presets: Vec<DateRangePreset>) -> Self {
    self.presets = Some(presets);
    self
  }

  /// Set number of months to display in calendar.
  pub fn number_of_months(mut self, number_of_months: usize) -> Self {
    self.number_of_months = number_of_months;
    self
  }

  /// Set appearance style.
  pub fn appearance(mut self, appearance: bool) -> Self {
    self.appearance = appearance;
    self
  }
}

fn clear_button(id: impl Into<ElementId>, cx: &App) -> Button {
  Button::new(id)
    .icon(Icon::new(IconName::DismissCircle))
    .flat()
    .small()
    .tab_stop(false)
    .text_color(cx.theme().muted_foreground)
}

impl RenderOnce for DatePicker {
  fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement {
    self.state.update(cx, |state, cx| {
      state.set_calendar_disabled_matcher(window, cx);
      state.number_of_months = self.number_of_months.max(1);
    });

    let state_view = self.state.read(cx);
    let show_clean = self.cleanable && state_view.date.is_some() && !self.disabled;
    let placeholder = self
      .placeholder
      .clone()
      .unwrap_or_else(|| SharedString::from(translate_woocraft("date_picker.placeholder")));
    let display_title = state_view
      .date
      .format(&state_view.date_format)
      .unwrap_or_else(|| placeholder.clone());
    let open = state_view.open;
    let is_focused = state_view.focus_handle.is_focused(window) && !self.disabled;
    let number_of_months = state_view.number_of_months;
    let _ = state_view;

    let trigger_state = self.state.clone();
    let trigger = Button::new(("date-picker-trigger", self.state.entity_id()))
      .with_size(self.size)
      .map(|this| {
        if self.appearance {
          this.default()
        } else {
          this.flat()
        }
      })
      .selected(open || is_focused)
      .disabled(self.disabled)
      .expand(true)
      .child(
        h_flex()
          .w_full()
          .items_center()
          .justify_between()
          .min_w_0()
          .child(
            div()
              .min_w_0()
              .overflow_hidden()
              .when(!trigger_state.read(cx).date.is_some(), |this| {
                this.text_color(cx.theme().muted_foreground)
              })
              .child(display_title),
          )
          .child(
            h_flex()
              .items_center()
              .gap_1()
              .when(show_clean, |this| {
                this.child(
                  div()
                    .on_mouse_down(MouseButton::Left, |_, _, cx| {
                      cx.stop_propagation();
                    })
                    .child(
                      clear_button(("date-picker-clean", self.state.entity_id()), cx).on_click({
                        let state = self.state.clone();
                        move |_, window, cx| {
                          state.update(cx, |state, cx| {
                            state.clean(&ClickEvent::default(), window, cx);
                            state.focus_handle.focus(window);
                          });
                        }
                      }),
                    ),
                )
              })
              .when(!show_clean, |this| {
                this.child(
                  Icon::new(IconName::Calendar)
                    .with_size(self.size.smaller())
                    .text_color(cx.theme().muted_foreground),
                )
              }),
          ),
      );

    let state_for_popover = self.state.clone();
    let presets = self.presets.clone();
    let size = self.size;

    let field: AnyElement = if self.disabled {
      trigger.into_any_element()
    } else {
      Popover::new(("date-picker-popover", self.state.entity_id()))
        .anchor(Anchor::TopLeft)
        .open(open)
        .track_focus(&self.focus_handle(cx))
        .overlay_closable(true)
        .on_open_change({
          let state = self.state.clone();
          move |open, window, cx| {
            state.update(cx, |state, cx| {
              state.set_open(*open, window, cx);
            });
          }
        })
        .trigger(trigger)
        .content(move |_, _window, cx| {
          h_flex()
            .gap_3()
            .items_start()
            .when_some(presets.clone(), |this, presets| {
              this.child(v_flex().my_1().gap_2().justify_end().children(
                presets.into_iter().enumerate().map(|(ix, preset)| {
                  Button::new(("preset", ix))
                    .small()
                    .flat()
                    .tab_stop(false)
                    .label(preset.label.clone())
                    .on_click({
                      let state = state_for_popover.clone();
                      move |_, window, cx| {
                        state.update(cx, |state, cx| {
                          state.select_preset(&preset, window, cx);
                        });
                      }
                    })
                }),
              ))
            })
            .child(
              Calendar::new(&state_for_popover.read(cx).calendar)
                .number_of_months(number_of_months)
                .border_0()
                .rounded(px(0.0))
                .p_0()
                .with_size(size),
            )
        })
        .into_any_element()
    };

    div()
      .id(self.id.clone())
      .w_full()
      .key_context(CONTEXT)
      .track_focus(&self.focus_handle(cx).tab_stop(true))
      .when(!self.disabled, |this| {
        this
          .on_action(window.listener_for(&self.state, DatePickerState::on_enter))
          .on_action(window.listener_for(&self.state, DatePickerState::on_delete))
      })
      .when(open && !self.disabled, |this| {
        this.on_action(window.listener_for(&self.state, DatePickerState::on_escape))
      })
      .refine_style(&self.style)
      .child(field)
  }
}