My custom editor buttons don't work anymore

I’m updating my addon for 2.1.50, but it seems now when i click my custom added editor buttons the editor field text is deselected, preventing the editing of the selected text by the function associated with button press.

The added editor buttons were made by injecting javascript that basically just clones existing buttons.

I realize anki_new_format_pack exists, but it seems like too much of a hassle.

Is there a quick-fix to prevent the clicking of new buttons from deselecting editor field text?

You might have to prevent the button from getting focused on mousedown with an EventListener:

button.addEventListener("mousedown", (event) => { 
        event.preventDefault();
});

… that’s actually how Anki itself does it:

1 Like

Any reason for not using the Python API if you don’t want to deal with Svelte?

from aqt.gui_hooks import editor_did_init_buttons

def add_button(buttons, editor):
    button = editor.addButton(
        icon=None,
        cmd="your_cmd",
        func=your_python_function,
        tip="My awesome button!",
        label="your_label",
        id="your_button_id",
        keys=QKeySequence("Ctrl+Whatever")
    )
    buttons.append(button)

    return buttons

editor_did_init_buttons.append(add_button)
1 Like

can’t use python hook for one button because its a dropdown button

yeah, i noticed the default buttons had an e.preventDefault() on mousedown, but that didn’t seem to fix it. fiddling around with it some more, it seems to work on “normal” buttons but not buttons that have a dropdown when pressed. (before i only tried it on the dropdown button)

perhaps the appearance of the dropdown div itself is what causes the loss of focus?

minimum reproduction (type in web inspector console of editor screen):

const dropdownBtn = document.querySelector("#blockFormatting > div > div").lastElementChild;
const newBtn = dropdownBtn.cloneNode(true);
const newBtnButton = newBtn.querySelector("div > div > button");
newBtnButton.disabled = false;
newBtnButton.addEventListener("mousedown", e => e.preventDefault());
dropdownBtn.parentNode.appendChild(newBtn);