Skip to content

Commit

Permalink
ensure button status is correctly set when editor opens
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
kieranlblack committed Nov 12, 2023
1 parent 1d60535 commit aa8fcc9
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions chinese/edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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='<b>汉字</b>',
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
Expand Down

0 comments on commit aa8fcc9

Please sign in to comment.