Source: shellfish-ui/ui/IndexScroller.shui

shellfish-ui/ui/IndexScroller.shui

/*******************************************************************************
This file is part of the Shellfish UI toolkit.
Copyright (c) 2022 - 2024 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/ui";

/**
 * Element representing a (non-proportional) scrollbar with an index for a list view.
 *
 * @memberof ui
 * @name IndexScroller
 * @class
 * @extends html.MouseBox
 *
 * @property {function} getLabel - A function for returning the index label for the nth item.
 * @property {number} labelSize - (default: `theme.itemHeightMedium`) The minimum size of an index label.
 * @property {string} orientation - The scrolling orientation. One of: `horizontal|vertical`
 * @property {template} styleOfBackground - The background style template.
 * @property {template} styleOfItem - The item style template.
 * @property {html.ListView} target - (default: `parent`) The scrolling target.
 *
 */
MouseBox {
    id: indexScroller

    property target: parent
    property getLabel: (idx) => { return ""; }
    property orientation: "vertical"
    property labelSize: theme.itemHeightMedium

    property styleOfBackground: template Box {
        fillWidth: true
        fillHeight: true

        color: theme.secondaryBackgroundColor
    }

    property styleOfItem: template Box {

        property highlighted: parent.inView || parent.containsMouse

        fillWidth: true
        fillHeight: true

        color: highlighted ? theme.highlightBackgroundColor
                           : "transparent"

        layout: "center"

        Label {
            fontSize: theme.fontSizeSmall
            color: parent.highlighted ? theme.highlightColor
                                      : theme.primaryColor
            bold: true
            text: parent.parent.text
        }
    }

    layout: orientation === "vertical" ? "center-column"
                                       : "center-row"

    Object {
        id: priv
        property setup: ""
    }

    function update()
    {
        defer(() =>
        {
            doUpdate();
        }, "update");
    }

    function doUpdate()
    {
        if (! target)
        {
            return;
        }

        let itemsPerRow = 1;
        let cellSize = 0;
        if (target.orientation === "vertical")
        {
            itemsPerRow = Math.floor(target.bboxWidth / target.cellWidth);
            cellSize = target.cellHeight;
        }
        else
        {
            itemsPerRow = Math.floor(target.bboxHeight / target.cellHeight);
            cellSize = target.cellWidth;
        }

        if (itemsPerRow <= 0)
        {
            return;
        }

        let maxItems = 0;
        if (orientation === "vertical")
        {
            maxItems = Math.floor(bboxHeight / labelSize);
        }
        else
        {
            maxItems = Math.floor(bboxWidth / labelSize);
        }

        //console.log("per row: " + itemsPerRow);

        let m = [];
        let pos = 0;
        let prevLabel = "";

        const targetCount = target.count;
        const getLabel = indexScroller.getLabel;
        
        unresolved
        {
            for (let i = 0; i < targetCount; i += itemsPerRow)
            {
                const itemIdx = i < targetCount - itemsPerRow ? (i === 0 ? 0 : i + itemsPerRow - 1)
                                                              : targetCount - 1;
                const label = getLabel(itemIdx);

                if (m.length > 0)
                {
                    m[m.length - 1].until = pos - 1;
                }
                if (label !== prevLabel)
                {
                    m.push({ position: pos, until: pos + cellSize - 1, label: label, index: itemIdx });
                    prevLabel = label;
                }
                pos += cellSize;
            }

            const decimateEvenly = (l, toN) =>
            {
                if (l.length <= toN)
                {
                    return l;
                }
                else if (toN === 0)
                {
                    return [];
                }

                const stepSize = l.length / toN;
                const result = [];
                result.push(l[0]);
                for (let i = 1; i < toN - 1; ++i)
                {
                    const idx = Math.floor(stepSize * i);
                    result.push(l[idx]);
                }
                result.push(l[l.length - 1]);

                return result;
            };

            // remove exceeding items, but not the first or the last
            m = decimateEvenly(m, maxItems);
        }

        const newSetup = JSON.stringify(m);
        if (newSetup !== priv.setup)
        {
            priv.setup = newSetup;
            labelRepeater.model.reset(m);
        }
    }

    onBboxChanged: () => { update(); }
    onLabelSizeChanged: () => { update(); }
    onGetLabelChanged: () => { update(); }
    target.onNewLayout: () => { update(); }

    onWheel: ev =>
    {
        ev.accepted = true;
        if (labelRepeater.count === 0)
        {
            return;
        }

        if (orientation === "horizontal")
        {
            const stepSize = target.contentWidth / labelRepeater.count;
            if (ev.deltaY < 0)
            {
                target.contentX = target.contentX - stepSize;
            }
            else if (ev.deltaY > 0)
            {
                target.contentX = target.contentX + stepSize;
            }
        }
        else
        {
            const stepSize = target.contentHeight / labelRepeater.count;
            if (ev.deltaY < 0)
            {
                target.contentY = target.contentY - stepSize;
            }
            else if (ev.deltaY > 0)
            {
                target.contentY = target.contentY + stepSize;
            }
        }
    }

    Loader {
        position: "free"
        fillWidth: true
        fillHeight: true

        sourceTemplate: indexScroller.styleOfBackground
    }

    Repeater {
        id: labelRepeater

        model: ListModel { }

        delegate: template MouseBox {
            fillWidth: true
            fillHeight: true

            onClick: ev =>
            {
                if (indexScroller.orientation === "horizontal")
                {
                    indexScroller.target.contentX = modelData.value.position;
                }
                else
                {
                    indexScroller.target.contentY = modelData.value.position;
                }
                ev.accepted = true;
            }

            Loader {
                property containsMouse: parent.containsMouse
                property inView: indexScroller.orientation === "horizontal" ? indexScroller.target.contentX < parent.modelData.value.until &&
                                                                              indexScroller.target.contentX + indexScroller.target.bboxWidth > parent.modelData.value.position
                                                                            : indexScroller.target.contentY < parent.modelData.value.until &&
                                                                              indexScroller.target.contentY + indexScroller.target.bboxHeight > parent.modelData.value.position
                property text: parent.modelData.value.label

                fillWidth: true
                fillHeight: true
                sourceTemplate: indexScroller.styleOfItem
            }
        }
    }

}