from markdown_it import MarkdownIt
from markdown_it.renderer import RendererProtocol
from markdown_it.token import Token
from markdown_it.utils import EnvType, OptionsDict
from typing import Sequence


def img_lazyload_plugin(md: MarkdownIt) -> None:
    """Plugin ported from
    `mdit/plug-img-lazyload <https://github.com/mdit-plugins/mdit-plugins/blob/main/packages/img-lazyload`__.

    It adds the lazy loading attribute to images.
    """

    def render(
        self: RendererProtocol,
        tokens: Sequence[Token],
        idx: int,
        options: OptionsDict,
        env: EnvType,
    ) -> str:
        tokens[idx].attrSet("loading", "lazy")

        return self.renderToken(tokens, idx, options, env)

    md.add_render_rule("image", render)
