iconfu/svg-inject

makeIdsUnique does not replace IDs for <path> references

bfollington opened this issue · 3 comments

I'm making use of this library in when dealing with SVG's exported directly from Sketch. We've had trouble with this in the past since Sketch uses very predictable ID names. I was really happy to see that you already support making IDs unique, but this (currently) does not apply to path elements.

SVGs exported from sketch often contain definition for a path in the <defs> section:

<defs>
  <path d="..." id="path-1"></path>
</defs>

These are then referenced later:

<mask id="mask-1" fill="white">
  <use xlink:href="#path-1"></use>
</mask>

I've modified the library to support this case and I'll submit a PR to accompany this issue shortly. Happy to discuss the best way to achieve this but I believe this would add to the already massive value of this project!

Thanks for the feedback. This is basically a duplicate of issue #28, which also sees some IDs not being replaced.

While your pull request will work for your specific case, I would prefer a more general approach, that will also work if <g>, <rect>, <symbol> etc. elements have an ID. The concept for this approach is already in the drawer, here is the pseudo code:

collect all elements with an "id" attribute (idElements)
IF idElements is not empty THEN
  FOR EACH element IN idElements
    add ID to a set (idSet)
    IF type of element is property referenceable THEN
      add referenceable properties to a set (referencingPropertiesSet)
    ENDIF
    add suffix to element's ID
  ENDFOR

  FOR EACH element IN all elements
    IF element has attributes THEN
    
      IF element has a `href` or `xlink:href` attribute THEN
        IF referenced ID is in idSet THEN
          add suffix to referenced ID
        ENDIF
      ENDIF
    
      FOR EACH property IN referencingPropertiesSet
        IF element's attribute value for property is url with ID THEN
          add suffix to ID in url
        ENDIF
      ENDFOR
    
    ENDIF
  ENDFOR  
 
ENDIF

Also, we will probably add an option to select if all IDs, no IDs, or only IDs that are referenced within the SVG will be made unique.

I hope this will be available in a new version at the beginning of next week.

Awesome! Thanks for responding so fast. That psuedocode approach seems like the right way to go given the broader context, keen for the new release. I'll keep an eye on things :)

Fixed in version 1.2.3. All IDs in the SVG are now made unique by default.