From aa8fcc9d37aa305854d368523cb83ddee2cbff0e Mon Sep 17 00:00:00 2001 From: Kieran Black Date: Sun, 12 Nov 2023 00:35:09 -0500 Subject: [PATCH] ensure button status is correctly set when editor opens The `loadNote` / `editor_did_load_note` hooks run as soon as a note is loaded, but not necesarrily after the ui component has been mounted to the DOM. By adding a delay of 50 ms before setting button state, this should help alleviate the race condition. --- chinese/edit.py | 36 ++++++++++++++++++++++-------------- 1 file changed, 22 insertions(+), 14 deletions(-) diff --git a/chinese/edit.py b/chinese/edit.py index f9a4c02..d7d4b96 100644 --- a/chinese/edit.py +++ b/chinese/edit.py @@ -33,40 +33,48 @@ def __init__(self): addHook('editFocusLost', self.onFocusLost) def setupButton(self, buttons: list[str], editor: aqt.editor.Editor): - self.buttonOn = False - editor._links['chineseSupport'] = self.onToggle + # the button starts as toggled off + self.ui_button_toggled_on = False - button = editor._addButton( + button = editor.addButton( icon=None, cmd='chineseSupport', + func=self.onToggle, tip='Chinese Support', label='汉字', id='chineseSupport', - toggleable=True) + toggleable=True + ) return buttons + [button] - def onToggle(self, editor): - self.buttonOn = not self.buttonOn + def onToggle(self, editor: aqt.editor.Editor): + self.ui_button_toggled_on = not self.ui_button_toggled_on mid = str(editor.note.note_type()['id']) - if self.buttonOn and mid not in config['enabledModels']: + if self.ui_button_toggled_on and mid not in config['enabledModels']: config['enabledModels'].append(mid) - elif not self.buttonOn and mid in config['enabledModels']: + elif not self.ui_button_toggled_on and mid in config['enabledModels']: config['enabledModels'].remove(mid) config.save() - def updateButton(self, editor): - enabled = str(editor.note.note_type()['id']) in config['enabledModels'] + def updateButton(self, editor: aqt.editor.Editor): + should_be_enabled = str(editor.note.note_type()['id']) in config['enabledModels'] - if (enabled and not self.buttonOn) or (not enabled and self.buttonOn): - editor.web.eval('toggleEditorButton(chineseSupport);') - self.buttonOn = not self.buttonOn + # if the ui button does not match the state it should be in, then bring it into sync + if should_be_enabled != self.ui_button_toggled_on: + + def toggle_button_status(): + editor.web.eval('toggleEditorButton(document.getElementById("chineseSupport"));') + self.ui_button_toggled_on = should_be_enabled + + # give NoteEditor component time to mount to the DOM to sure that toggleEditorButton has been injected + mw.progress.single_shot(50, toggle_button_status) def onFocusLost(self, changed: bool, note: anki.notes.Note, index: int): - if not self.buttonOn: + if not self.ui_button_toggled_on: return changed we_changed = False