Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix attribute adding to avoid duplicates #157

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

cgm616
Copy link

@cgm616 cgm616 commented Aug 24, 2024

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.

Previously, the plugin would add a new attribute to the relevant
markdown-it token for each that it encountered. However, if the
attribute already existed, this duplicated the attribute. Because of the
way that markdown-it reads attributes, the duplicate is essentially
ignored. By using `Token.attrSet` instead of `Token.attrPush`,
markdown-it will automatically de-duplicate attributes for us.

See https://markdown-it.github.io/markdown-it/#Token.attrSet.
@cgm616
Copy link
Author

cgm616 commented Aug 24, 2024

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant