Source: shellfish-ui/ui/MenuItemBase.shui

shellfish-ui/ui/MenuItemBase.shui

/*******************************************************************************
This file is part of the Shellfish UI toolkit.
Copyright (c) 2020 - 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 the base class for menu items.
 *
 * @memberof ui
 * @name MenuItemBase
 * @class
 * @extends html.MouseBox
 *
 * @property {bool} selected - [readonly] Whether the menu item is currently selected.
 * @property {bool} highlighted - [readonly] Whether the menu item is currently highlighted (not necessarily selected).
 * @property {fengshui.Template} menu - (default: `null`) A template for a submenu.
 * @property {bool} menuOpened - [readonly] Whether the submenu is currently opened.
 */
MouseBox {
    id: item

    property selected: false
    property highlighted: false

    property menu: null
    property menuOpened: false

    property _menu: null

    function _createMenu()
    {
        if (! menu)
        {
            return;
        }

        _menu = menu();

        // unhighlight when menu clicked away
        _menu.get().onVisibleChanged = () =>
        {
            if (! _menu.visible)
            {
                menuOpened = false;
            }
        };

        _menu.get().onPointerMove = (ev) =>
        {
            let onItem = false;
            // test the sibling menu items on the menu bar
            parent.children()
            .filter((c) => { return c.enabled && c.visible; })
            .forEach((child) =>
            {
                const cBox = child.bbox;
                if (ev.x >= cBox.x && ev.x < cBox.x + cBox.width &&
                    ev.y >= cBox.y && ev.y < cBox.y + cBox.height)
                {
                    if (child !== self && child.selectItem)
                    {
                        child.selectItem(true);
                    }
                    onItem = true;
                }
            });

            if (! onItem && !! thisMenu)
            {
                thisMenu.pointerMove(ev);
            }
        };

        _menu.get().onKeyDown = (ev) =>
        {
            if (thisMenu)
            {
                if (ev.key === "ArrowLeft")
                {
                    // cursor-left close the submenu
                    _menu.visible = false;
                    ev.accepted = true;
                }
            }
            else
            {
                if (ev.key === "ArrowLeft")
                {
                    // cursor-left opens the previous menu
                    toSibling(-1, (sibling) =>
                    {
                        sibling.selectItem(true);
                    });
                    ev.accepted = true;
                }
                else if (ev.key === "ArrowRight")
                {
                    // cursor-right opens the next menu
                    toSibling(1, (sibling) =>
                    {
                        sibling.selectItem(true);
                    });
                    ev.accepted = true;
                }
            }
        };

        _menu.get().onCascadingClose = () =>
        {
            menuOpened = false;
            if (thisMenu)
            {
                thisMenu.cascadingClose();
                thisMenu.close();
            }
        };
    }

    /**
     * Shows the submenu if there is one.
     *
     * @memberof ui.MenuItemBase.prototype
     * @name showMenu
     * @method
     */
    function showMenu()
    {
        if (! menu)
        {
            return;
        }

        if (! _menu)
        {
            _createMenu();
        }

        if (!! thisMenu)
        {
            _menu.popup(self, { horizontal: true });
        }
        else
        {
            _menu.popup(self, { horizontal: false });
        }

        menuOpened = true;
    }

    /**
     * Closes the submenu.
     *
     * @memberof ui.MenuItemBase.prototype
     * @name closeMenu
     * @method
     */
    function closeMenu()
    {
        _menu.visible = false;
    }

    /**
     * Unselects all sibling menu items.
     *
     * @memberof ui.MenuItemBase.prototype
     * @name unselectSiblings
     * @method
     */
    function unselectSiblings()
    {
        // unhighlight siblings and close menu
        parent.children()
        .filter((c) => { return c !== self && c.selectItem; })
        .forEach((c) =>
        {
            //console.log("unselect " + c.text);
            c.selected = false;
            if (c.menuOpened)
            {
                c.closeMenu();
            }
        });
    }

    /**
     * Selects this menu item.
     *
     * @memberof ui.MenuItemBase.prototype
     * @name selectItem
     * @method
     *
     * @param {bool} activate - Whether the item should be activated to open its submenu.
     */
    function selectItem(activate)
    {
        //console.log("select " + text);
        selected = true;

        if (! parent)
        {
            return;
        }
        unselectSiblings();

        if (menu && activate)
        {
            if (! menuOpened)
            {
                showMenu();
            }
        }
        else
        {
            selected = true;
        }
    }

    /**
     * Returns whether one of the sibling menu items has a submenu opened.
     *
     * @memberof ui.MenuItemBase.prototype
     * @name hasSiblingMenuOpen
     * @method
     *
     * @return {bool} Whether a sibling menu item has a submenu opened.
     */
    function hasSiblingMenuOpen()
    {
        return parent.children()
               .filter((c) => { return c !== self && c.menuOpened; })
               .length > 0;
    }

    /**
     * Directs a function to the previous or next sibling.
     *
     * @memberof ui.MenuItemBase.prototype
     * @name toSibling
     * @method
     *
     * @param {number} direction - If `-1`, targets the previous sibling. If `1`, targets the next sibling.
     * @param {function} f - The function to execute. Takes the sibling instance as parameter.
     */
    function toSibling(direction, f)
    {
        const siblings = parent.children().filter((c) => { return c.selectItem && c.enabled; });
        let selfPos = -1;
        for (let i = 0; i < siblings.length; ++i)
        {
            if (siblings[i] === self)
            {
                selfPos = i;
                break;
            }
        }

        if (selfPos !== -1)
        {
            if (direction === -1)
            {
                f(siblings[(siblings.length + selfPos - 1) % siblings.length]);
            }
            else if (direction === 1)
            {
                f(siblings[(selfPos + 1) % siblings.length]);
            }
        }
    }


    onAncestorsVisibleChanged: () =>
    {
        if (! ancestorsVisible)
        {
            if (menuOpened)
            {
                _menu.visible = false;
            }
            selected = false;
        }
    }

    onSelectedChanged: () =>
    {
        if (selected && thisMenu)
        {
            focus = true;

            const thisY = bboxY - thisMenu.menu.bboxY + thisMenu.menu.contentY;
            if (thisY < thisMenu.menu.contentY)
            {
                thisMenu.menu.contentY = thisY;
            }
            else if (thisY > thisMenu.menu.contentY + thisMenu.menu.bboxHeight - bboxHeight)
            {
                thisMenu.menu.contentY = thisY - thisMenu.menu.bboxHeight + bboxHeight;
            }
        }
    }

    onFocusChanged: () =>
    {
        if (! thisMenu)
        {
            if (focus)
            {
                selectItem(false);
            }
            else
            {
                selected = false;
            }
        }
    }

    onContainsMouseChanged: () =>
    {
        if (containsMouse)
        {
            if (thisMenu)
            {
                selectItem(true);
            }
            else
            {
                if (hasSiblingMenuOpen())
                {
                    selectItem(true);
                }
                else
                {
                    selectItem(false);
                }
            }
        }
        else
        {
            selected = false;
        }
    }

    onPointerDown: (ev) =>
    {
        if (thisMenu)
        {
            if (menu)
            {
                ev.accepted = true;
            }
        }
        else
        {
            // standalone menu item with menu
            if (menu && ! menuOpened)
            {
                showMenu();
                ev.accepted = true;
            }
            else if (menuOpened)
            {
                ev.accepted = true;
            }
        }
    }

    onKeyDown: (ev) =>
    {
        if (thisMenu)
        {
            if (selected && ev.key === "ArrowRight" && menu)
            {
                // cursor-right opens the submenu
                showMenu();
                ev.accepted = true;
            }
            else if (ev.key === " " || ev.key === "Enter")
            {
                if (selected)
                {
                    item.click(ev);
                }
                else
                {
                    ev.accepted = true;
                }
            }
        }
        else
        {
            // parent is not a menu

            if (ev.key === " " || ev.key === "Enter" || ev.key === "ArrowDown")
            {
                if (selected)
                {
                    item.click(ev);
                }
                ev.accepted = true;
            }
        }

    }

    canFocus: !! thisMenu

    fillWidth: !! thisMenu
    height: theme.itemHeightMedium

    highlighted: selected || menuOpened

    color: highlighted ? theme.highlightBackgroundColor
                       : "transparent"
}