Source: shellfish-ui/ui/Calendar.shui

shellfish-ui/ui/Calendar.shui

/*******************************************************************************
This file is part of the Shellfish UI toolkit.
Copyright (c) 2021 - 2023 Martin Grimme <martin.grimme@gmail.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*******************************************************************************/

require "shellfish/low" as low;
require "shellfish/ui";

/**
 * Element representing a calendar view with customizable day panels.
 *
 * @memberof ui
 * @name Calendar
 * @class
 * @extends html.MouseBox
 *
 * @property {number} firstDay - (default: `0`) The first day of the week. A value between `0` (Sunday) and `6` (Saturday).
 * @property {number[]} date - (default: *today*) A tuple of `[year, month, date]` for the currently selected date.
 * @property {fengshui.Template} dayDelegate - A custom day panel delegate.
 */
MouseBox {
    id: cal

    property firstDay: 0
    property date: (() =>
                   {
                       const d = new Date();
                       return [d.getFullYear(), d.getMonth(), d.getDate()];
                   })()

    property dayDelegate: template Button {
        id: dayButton

        labelProfile: Object {
            property horizontalAlignment: "right"
            property fontSize: theme.fontSizeSmall
            property bold: priv.isToday(dayButton.modelData.value.year,
                                        dayButton.modelData.value.month,
                                        dayButton.modelData.value.day)
        }

        visible: modelData.value.day !== 0
        opacity: modelData.value.month === cal.date[1] ? 1.0 : 0.4

        flat: true
        text: "" + modelData.value.day

        onClick: (ev) =>
        {
            cal.dateSelected(modelData.value.year,
                             modelData.value.month,
                             modelData.value.day);
            ev.accepted = true;
        }
    }

    /**
     * Goes to the previous month.
     *
     * @memberof ui.Calendar.prototype
     * @name toPreviousMonth
     * @method
     */
    function toPreviousMonth()
    {
        let y = cal.date[0];
        let m = cal.date[1];
        let d = cal.date[2];
        if (m === 0)
        {
            --y;
            m= 11;
        }
        else
        {
            --m;
        }
        cal.date = [y, m, d];
    }

    /**
     * Goes to the next month.
     *
     * @memberof ui.Calendar.prototype
     * @name toNextMonth
     * @method
     */
    function toNextMonth()
    {
        let y = cal.date[0];
        let m = cal.date[1];
        let d = cal.date[2];
        if (m === 11)
        {
            ++y;
            m = 0;
        }
        else
        {
            ++m;
        }
        cal.date = [y, m, d];
    }

    /**
     * Goes to the current day.
     *
     * @memberof ui.Calendar.prototype
     * @name toToday
     * @method
     */
    function toToday()
    {
        const d = new Date();
        cal.date = [d.getFullYear(), d.getMonth(), d.getDate()];
        priv.mode = 0;
    }

    /**
     * Goes to the month picker.
     *
     * @memberof ui.Calendar.prototype
     * @name pickMonth
     * @method
     */
    function pickMonth()
    {
        priv.mode = 1;
    }

    /**
     * Goes to the year picker.
     *
     * @memberof ui.Calendar.prototype
     * @name pickYear
     * @method
     */
    function pickYear()
    {
        priv.mode = 2;
    }

    /**
     * Is triggered when the user selected a date.
     *
     * @memberof ui.Calendar.prototype
     * @name dateSelected
     * @event
     * @param {number[]} date - A `[year, month, day]` tuple of the selected date.
     */
    event dateSelected

    width: theme.itemWidthMedium * 7
    height: theme.itemHeightSmall * 7

    onInitialization: () =>
    {
        daysModel.setMonth(date[0], date[1]);
    }

    onPointerDown: (ev) =>
    {
        ev.accepted = true;
    }

    onWheel: (ev) =>
    {
        if (priv.mode === 0)
        {
            if (ev.deltaY < 0)
            {
                toPreviousMonth();
            }
            else if (ev.deltaY > 0)
            {
                toNextMonth();
            }
            ev.accepted = true;
        }
    }

    onFirstDayChanged: () => { daysModel.setMonth(date[0], date[1]); }
    onDateChanged: () => { daysModel.setMonth(date[0], date[1]); }

    Object {
        id: priv

        property mode: 0

        function isToday(year, month, day)
        {
            const now = new Date();
            return now.getFullYear() === year &&
                now.getMonth() === month &&
                now.getDate() === day;
        }
    }

    ListModel {
        id: daysModel

        function setMonth(year, month)
        {
            if (size === 0)
            {
                // initialize
                const d = [];
                for (let i = 0; i < 6 * 7; ++i)
                {
                    d.push({ year: 0, month: 0, day: 0, dayOfWeek: 0 });
                }
                reset(d);
            }

            // last day of prev month
            const prevDate = new Date(year, month, 0);
            // first day of this month
            const date = new Date(year, month, 1);

            // month and year of the previous and next month
            const lastPrevDay = prevDate.getDate();
            const prevMonth = month === 0 ? 11 : month - 1;
            const nextMonth = (month + 1) % 12;
            const prevYear = month === 0 ? year - 1 : year;
            const nextYear = month === 11 ? year + 1 : year;

            const offset = (date.getDay() + (7 - cal.firstDay)) % 7;

            // last day of month
            date.setMonth(month + 1, 0);
            const lastDay = date.getDate();

            for (let i = 0; i < 6 * 7; ++i)
            {
                replace(i, {
                    year: i < offset ? prevYear 
                                     : i >= offset + lastDay ? nextYear
                                                             : year,
                    month: i < offset ? prevMonth
                                      : i >= offset + lastDay ? nextMonth
                                                              : month,
                    day: i < offset ? lastPrevDay - (offset - i) + 1
                                    : i >= offset + lastDay ? i - (offset + lastDay) + 1
                                                            : i - offset + 1,
                    dayOfWeek: (i + cal.firstDay) % 7
                });
            }
        }
    }

    Box {
        id: box

        fillWidth: true
        fillHeight: true

        // day picker
        ListView {
            id: daysView

            visible: priv.mode === 0

            position: "free"
            fillWidth: true
            fillHeight: true

            model: daysModel

            cellWidth: box.bboxWidth / 7
            cellHeight: box.bboxHeight / 6

            delegate: cal.dayDelegate
        }

        // month picker
        ListView {
            id: monthPicker

            visible: priv.mode === 1

            position: "free"
            fillWidth: true
            fillHeight: true

            model: ListModel {
                data: monthPicker.visible ?
                    ["Jan", "Feb", "Mar",
                     "Apr", "May", "Jun",
                     "Jul", "Aug", "Sep",
                     "Oct", "Nov", "Dec"] : []
            }
            cellWidth: box.bboxWidth / 3
            cellHeight: box.bboxHeight / 4

            delegate: template Button {
                flat: true
                checked: modelData.index === cal.date[1]
                text: modelData.value

                onClick: (ev) =>
                {
                    cal.date = [cal.date[0], modelData.index, cal.date[2]];
                    priv.mode = 0;
                    ev.accepted = true;
                }
            }
        }

        // year picker
        ListView {
            id: yearPicker

            visible: priv.mode === 2

            position: "free"
            fillWidth: true
            fillHeight: true

            model: ListModel {
                data: sequence(1900, 200)
            }

            cellWidth: box.bboxWidth / 4
            cellHeight: box.bboxHeight / 6

            delegate: template Button {
                flat: true
                checked: modelData.value === cal.date[0]
                text: "" + modelData.value

                onClick: (ev) =>
                {
                    cal.date = [modelData.value, cal.date[1], cal.date[2]];
                    priv.mode = 0;
                    ev.accepted = true;
                }
            }

            onVisibleChanged: () =>
            {
                if (visible)
                {
                    positionViewAt(cal.date[0] - 1900);
                }
            }

            ScrollIndicator { size: theme.paddingSmall }
        }

    }
}