Only show editor button for specific notetype

I’m trying to make it so that my buttons will only show up if they can be used with the notetype of the note being loaded into the editor. However, the buttons are created before the note is loaded. So when the editor_did_init_buttons hook fires, the given editor.note is still null and I can’t check for the notetype.

def add_audio(editor: Editor):
    (...)

def add_audio_btn(buttons: List[str], editor: Editor):
    if not has_fields(editor.note.note_type()): # <- doesnt work because its always null
        return
    buttons += [editor.addButton("", "add_audio", add_audio, "", "Add Audio")]

gui_hooks.editor_did_init_buttons.append(add_audio_btn)

Does anyone have an idea on how to solve this?

Try adding the button unconditionally in the editor_did_init_buttons hook, but hide it conditionally via JavaScript in the add_cards_did_change_note_type and editor_did_load_note hooks. Maybe try the CSS selector button[title="Add Audio"] to get the button in JavaScript and hide/show it.

Sounds like a good approach! I don’t know where/how I would be adding the JavaScript though… Could you give me a simple example?

Here is an example adapted from an add-on I wrote that does something similar:

from anki.models import NoteType
from aqt import dialogs, gui_hooks, mw
from aqt.addcards import AddCards
from aqt.editor import Editor


def update_button_visibility(editor: Editor, notetype: NoteType) -> None:
    if is_target_notetype(notetype):
        editor.web.eval("showAddonButton()")
    else:
        editor.web.eval("hideAddonButton()")


def on_notetype_changed(old: NoteType, new: NoteType) -> None:
    addcards: AddCards = dialogs.open("AddCards")
    update_button_visibility(addcards.editor, new)


def on_editor_did_load_note(editor: Editor) -> None:
    mw.progress.timer(
        50,
        lambda: update_button_visibility(editor, editor.note.note_type()),
        repeat=False,
    )


gui_hooks.add_cards_did_change_note_type.append(on_notetype_changed)
gui_hooks.editor_did_load_note.append(on_editor_did_load_note)

This works perfectly, thank you very much!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.