|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require "securerandom" |
| 4 | + |
| 5 | +module RubyUI |
| 6 | + class DatePicker < Base |
| 7 | + def initialize( |
| 8 | + id: nil, |
| 9 | + name: nil, |
| 10 | + label: "Select a date", |
| 11 | + value: nil, |
| 12 | + placeholder: "Select a date", |
| 13 | + selected_date: value, |
| 14 | + date_format: "yyyy-MM-dd", |
| 15 | + popover_options: {}, |
| 16 | + input_attrs: {}, |
| 17 | + calendar_attrs: {}, |
| 18 | + trigger_attrs: {}, |
| 19 | + content_attrs: {}, |
| 20 | + **attrs |
| 21 | + ) |
| 22 | + @id = id || "date-picker-#{SecureRandom.hex(4)}" |
| 23 | + @name = name |
| 24 | + @label = label |
| 25 | + @value = value || selected_date&.to_s |
| 26 | + @placeholder = placeholder |
| 27 | + @selected_date = selected_date |
| 28 | + @date_format = date_format |
| 29 | + @popover_options = {trigger: "click"}.merge(popover_options) |
| 30 | + @input_attrs = input_attrs |
| 31 | + @calendar_attrs = calendar_attrs |
| 32 | + @trigger_attrs = trigger_attrs |
| 33 | + @content_attrs = content_attrs |
| 34 | + super(**attrs) |
| 35 | + end |
| 36 | + |
| 37 | + def view_template |
| 38 | + div(**attrs) do |
| 39 | + RubyUI.Popover(options: @popover_options) do |
| 40 | + RubyUI.PopoverTrigger(**trigger_attrs) do |
| 41 | + div(class: "grid w-full max-w-sm items-center gap-1.5") do |
| 42 | + label(for: @id) { @label } if @label |
| 43 | + RubyUI.Input(**input_attrs) |
| 44 | + end |
| 45 | + end |
| 46 | + RubyUI.PopoverContent(**content_attrs) do |
| 47 | + RubyUI.Calendar(input_id: "##{@id}", selected_date: @selected_date, date_format: @date_format, **calendar_attrs) |
| 48 | + end |
| 49 | + end |
| 50 | + end |
| 51 | + end |
| 52 | + |
| 53 | + private |
| 54 | + |
| 55 | + def default_attrs |
| 56 | + { |
| 57 | + class: "space-y-4 w-[260px]" |
| 58 | + } |
| 59 | + end |
| 60 | + |
| 61 | + def trigger_attrs |
| 62 | + mix({class: "w-full"}, @trigger_attrs) |
| 63 | + end |
| 64 | + |
| 65 | + def input_attrs |
| 66 | + mix({ |
| 67 | + type: "string", |
| 68 | + placeholder: @placeholder, |
| 69 | + id: @id, |
| 70 | + name: @name, |
| 71 | + value: @value, |
| 72 | + data_controller: "ruby-ui--calendar-input", |
| 73 | + class: "rounded-md border shadow" |
| 74 | + }.compact, @input_attrs) |
| 75 | + end |
| 76 | + |
| 77 | + def calendar_attrs |
| 78 | + mix({}, @calendar_attrs) |
| 79 | + end |
| 80 | + |
| 81 | + def content_attrs |
| 82 | + mix({}, @content_attrs) |
| 83 | + end |
| 84 | + end |
| 85 | +end |
0 commit comments