jdtcn / BlazorDateRangePicker

A Blazor component for choosing date ranges and dates
MIT License
186 stars 34 forks source link

Feature Request - Select Date Range in any direction #53

Closed aditya119 closed 3 years ago

aditya119 commented 3 years ago

Hi Sergey. Before I begin, let me thank you for an awesome Blazor component.

I have a requirement that date range should be selected from either left or right side. If I select a date, the component should allow me to select the second date from either left or right to the first date.

I wonder if this is possible to configure using the CustomClickHandler (I could not figure out would that be), or would it require changes in the codebase? Please consider this as a feature request, if so.

Thanks in advance.

jdtcn commented 3 years ago

Hi,

It should be something like this:

<DateRangePicker @ref="Picker" OnMonthChanged="MonthChanged" CustomDateFunction="CustomHover" />

@code {
    DateRangePicker Picker { get; set; }

    private void MonthChanged()
    {
        UpdateClickHandlers();
    }

    private string CustomHover(DateTimeOffset dt)
    {
        if (dt >= Picker?.HoverDate && dt < Picker?.TStartDate)
        {
            return "in-range";
        }
        return string.Empty;
    }

    private void UpdateClickHandlers()
    {
        var days = Enumerable
            .Concat(Picker.LeftCalendar.Calendar, Picker.RightCalendar.Calendar)
            .SelectMany(d => d);

        foreach (var day in days)
        {
            var dayClick = day.Click;

            day.Click = async () =>
            {
                if (Picker.TStartDate.HasValue && !Picker.TEndDate.HasValue && day.Day < Picker.TStartDate)
                {
                    Picker.TEndDate = Picker.TStartDate;
                    Picker.TStartDate = day.Day;
                    await Picker.LeftCalendar.CalculateCalendar();
                    await Picker.RightCalendar.CalculateCalendar();
                    StateHasChanged();
                }
                else
                {
                    dayClick.Invoke();
                }
            };
        }
    }
}
aditya119 commented 3 years ago

Thank you very much. This helps.