Add hook to load custom css into the editor

Since Anki allows toggling between night mode and regular mode it’s useful to chose css over inline styling. Also it’s pretty useful for add-ons to load custom css into the editor so that you have consistent styling between the reviewer and the editor, e.g. for the custom styles add-on, the syntax highlighting add-ons, or add-ons that insert content for language learning etc.

For add-on authors it would be very useful to have a hook like editor_will_apply_this_css(my_css_string). Without such a hook at the moment you need to know a lot about the internals of the editor, e.g. for .55 the addon custom styles uses this code:

def append_css_to_Editor(js, note, editor) -> str:
    return (
        js
        + f"""
require("anki/RichTextInput").lifecycle.onMount(async ({{ customStyles }}) => {{
    const {{ addStyleTag }} = await customStyles;
    const {{ element: styleTag }} = await addStyleTag('customStyles');
    styleTag.textContent = `{my_css_string}`
}});
"""
    )
editor_will_load_note.append(append_css_to_Editor)

The code for 2.1.50-54 = the add-on CSS injector is even more complicated.

with a dedicated editor css hook add-on authors wouldn’t have to worry about changes to the editor.

@hengiesel @kleinerpirat

1 Like