arve0 / markdown-it-attrs

Add classes, identifiers and attributes to your markdown with {} curly brackets, similar to pandoc's header attributes
MIT License
300 stars 58 forks source link

Fix attribute adding to avoid duplicates #157

Open cgm616 opened 2 months ago

cgm616 commented 2 months ago

Right now, the plugin adds attributes to tokens in a way that causes duplicates if those attributes already exist. This pull request fixes the problem.

For example, suppose someone wants to use this plugin to add the alt attribute to an image:

![An image of a bird](bird.jpg){alt="A green bird sitting on a fence"}

markdown-it already adds the alt attribute to Markdown image tokens. (For whatever reason, this attribute is empty.) When markdown-it-attrs adds the alt attribute because of the curly braces, it will duplicate the attribute. The attributes of the above token are:

[
    ["alt", ""],
    ["src", "bird.jpg"],
    ["alt", "A green bird sitting on a fence"]
]

Due to the way that markdown-it provides attributes when using token.attrGet, only the first instance of any duplicated attribute will be accessible. In other words, it's as if the plugin has done nothing at all.

This pull request makes a single line change—from token.attrPush to token.attrSet—to fix the issue of duplicate attributes. The latter avoids adding duplicates and instead updates attributes that already exist. See the docs.

cgm616 commented 2 months ago

Just updated the pull request with more clear information about this change and its rationale. The change shouldn't alter anything about how markdown-it-attrs works.