Stimulus controller to show/hide toolbox yet allow click

158 Views Asked by At

I have a content editable block that has a toolbox. When you focus on the content editable block the toolbox will appear (it is a collapse button for the actual toolbar). If you clock on the toolbox, need to add the Bootstrap class "active" to it. If we focus completely out of the content block, that toolbox should disappear (and a new one appear on a different content block).

Because of the need to click on the toolbox, I can't get the third event listener to work as expected.

The HTML:

.border.border-dark.p-4
        .position-relative.w-100{data: {controller: "content", content:{block:{value: true}}}}
            .position-absolute.bg-white{style: "right: 101%"}
                %button.d-none.btn.btn-outline-dark{type: "button", data: {content_target: "toolbox", bs:{toggle: "collapse", target: "#toolbar1"}}}
                    %i.bi.bi-hammer
            
            #toolbar1.collapse.position-absolute.bottom-100.bg-white.btn-toolbar{role: "toolbar", aria:{label: "Toolbar with button groups"}}
                .btn-group.me-2{role: "group", aria:{label: "First group"}}
                    %button.btn.btn-outline-dark.active{type: "button"} H2
                    %button.btn.btn-outline-dark{type: "button"} H3
                    %button.btn.btn-outline-dark{type: "button"} H4
                    %button.btn.btn-outline-dark{type: "button"} H5
                    %button.btn.btn-outline-dark{type: "button"} H6
                    %button.btn.btn-outline-dark{type: "button"}
                        %i.bi.bi-paragraph
                    
            %p{contenteditable: true, data: {content_target: "contentBlock"}} This is some text

and the Stimulus

this.contentBlockTarget.addEventListener("focus", (event) => {
    this.toolboxTarget.classList.remove("d-none")
})
this.toolboxTarget.addEventListener("click", (event) => {
    this.toolboxTarget.classList.add("active")
    this.toolboxTarget.classList.remove("active")
})  
this.contentBlockTarget.addEventListener("focusout", (event) => {
    this.toolboxTarget.classList.add("d-none")
})

Here's my requirements:

  1. If user focuses on the contentBlock (in this HTML it's a

    ), toolbox should appear (remove class "d-none"). (first event listener does this fine)

  2. If user clicks on the toolbox, add class "active". (if third event listener is commented out, this works fine). If third listener is active, clicking the toolbox makes it disappear, so the toolbar won't actually appear.
  3. If user clicks anywhere that is NOT the toolbox, or the cursor is no longer in this area (like maintaining the cursor in there), then need to add "d-none" back.
0

There are 0 best solutions below