tweakpane / plugin-essentials

Essential components for Tweakpane
https://cocopon.github.io/tweakpane/plugins/#essentials
MIT License
74 stars 6 forks source link

How can I set the id of each button in ButtonGrid? #24

Closed aniongithub closed 1 month ago

aniongithub commented 1 month ago

I need to set the ids of each item in a button grid to create some custom styling for each button. How can I set these ids?

Thanks in advance!

aniongithub commented 1 month ago

While there's no way from the public API itself, we can assume the hierarchy that the view produces and write the following functions

    function getButtonGridButton(toolbar: EssentialsPlugin.ButtonGridApi, y: number, x: number) {
        const size = toolbar.controller.valueController.size;
        if ((x < 0) || (x >= size[0]) || (y < 0) || (y >= size[1]))
            return null;
        const parent = toolbar.controller.view.valueElement.children[0];
        if (!parent)
            return null;

        // Note: Can use the commented line below if you want the Button element
        // instead of the inner div
        // return parent.children[y * size[0] + x].children[0]

        // Note: This returns the inner div element of the Button element, 
        // use the commented line above if you want the Button element instead
        return parent.children[y * size[0] + x].children[0]?.children[0] as HTMLElement;
    }

and

    private setButtonGridButtonIds(toolbar: EssentialsPlugin.ButtonGridApi, ids: string[][]) {
        const size = toolbar.controller.valueController.size;
        if (!size)
            return;
        if ((size[0] == ids[0].length) && (size[1] == ids.length))
            for (let y = 0; y < size[1]; y++) {
                for (let x = 0; x < size[0]; x++) {
                    const btn = getButtonGridButton(toolbar, y, x);
                    if (btn)
                        btn.id = ids[y][x];
                }
            }
    }

Now, assuming we have an Essentials.ButtonGridApi instance called toolbar, we can set all the ids like so:

this.setToolbarButtonIds(toolbar, [[ "move_up_btn", "move_down_btn", "delete_btn", "animate_btn" ]]);

As you can tell, I'm trying to create toolbars using tweakpane's ButtonGrid.