Fix add-on buttons not working in the editor (#3941)

* Fix add-on buttons not working in the editor

* Ensure old listeners are cleaned up

Thanks to iamllama: https://github.com/ankitects/anki/pull/3941#discussion_r2057066283

(cherry picked from commit 1e74e8e86e)
This commit is contained in:
Damien Elmes 2025-04-24 15:26:46 +10:00 committed by Damien Elmes
parent e249b92e48
commit 9cfd8af34e
2 changed files with 38 additions and 5 deletions

View file

@ -320,7 +320,6 @@ require("anki/ui").loaded.then(() => require("anki/NoteEditor").instances[0].too
label_element = cmd
title_attribute = shortcut(title_attribute)
cmd_to_toggle_button = "toggleEditorButton(this);" if toggleable else ""
id_attribute_assignment = f"id={id}" if id else ""
class_attribute = "linkb" if rightside else "rounded"
if not disables:
@ -328,11 +327,11 @@ require("anki/ui").loaded.then(() => require("anki/NoteEditor").instances[0].too
return f"""<button tabindex=-1
{id_attribute_assignment}
class="{class_attribute}"
class="anki-addon-button {class_attribute}"
type="button"
title="{title_attribute}"
onclick="pycmd('{cmd}');{cmd_to_toggle_button}return false;"
onmousedown="window.event.preventDefault();"
data-cantoggle="{int(toggleable)}"
data-command="{cmd}"
>
{image_element}
{label_element}

View file

@ -4,8 +4,42 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
-->
<script lang="ts">
import ButtonGroup from "$lib/components/ButtonGroup.svelte";
import { bridgeCommand } from "@tslib/bridgecommand";
import { toggleEditorButton } from "../old-editor-adapter";
import { singleCallback } from "@tslib/typing";
import { on } from "@tslib/events";
export let buttons: string[];
const { buttons } = $props<{ buttons: string[] }>();
$effect(() => {
// Each time the buttons are changed...
buttons;
// Add event handlers to each button
const addonButtons = document.querySelectorAll(".anki-addon-button");
const cbs = [...addonButtons].map((button) =>
singleCallback(
on(button, "click", () => {
const command = button.getAttribute("data-command");
if (command) {
bridgeCommand(command);
}
const toggleable = button.getAttribute("data-cantoggle");
if (toggleable === "1") {
toggleEditorButton(button as HTMLButtonElement);
}
return false;
}),
on(button as HTMLButtonElement, "mousedown", (evt) => {
evt.preventDefault();
evt.stopPropagation();
}),
),
);
return singleCallback(...cbs);
});
const radius = "5px";
function getBorderRadius(index: number, length: number): string {