GetmeUK / ContentTools

A JS library for building WYSIWYG editors for HTML content.
http://getcontenttools.com
MIT License
3.95k stars 395 forks source link

How to keep attributes after changing link? #483

Open laurobecker opened 6 years ago

laurobecker commented 6 years ago

Hi!

Thanks for this awesome plugin. 👏

So, I have an tag with some classes and I want to allow changing it's href attribute. But after the user change it, basically the tag looses all attributes except href and target.

How can I keep theses attributes?

Many thanks!

anthonyjb commented 6 years ago

Hey @laurobecker - I think you found a bug here. At the moment I suspect the code is just switching out the existing link with a new one and not taking into account the existing link - I need to look into. Thanks for reporting this.

laurobecker commented 6 years ago

Hi @anthonyjb!

Thanks for your fast answear!

laurobecker commented 6 years ago

BTW, if you have any idea of a workaround, I'd be very thankful!

scmccoy commented 6 years ago

You could save your attributes right before you change/update the link. I don't have that tool in my repo but from what I can see, in Link.apply function add all your attributes into an array:

  attrs = Array.prototype.slice.call(element._domElement.attributes) 

Then at the end of the function before return, add them back to the element:

   for(let i = 0; i < attrs.length; i++) {
    element._domElement.setAttribute(attrs[i].name, attrs[i].value);
  } 

This isn't tested w/ the Link function but might be a work around for now. You can add as coffeescript in tools.coffee as well, it might look like this: (not 100%, coffee script is not familiar)

   attrs = Array.prototype.slice.call(element._domElement.attributes) 

before return:

    for i in attrs.length 
    element._domElement.setAttribute(attrs[i].name, attrs[i].value) 
laurobecker commented 6 years ago

Hi @scmccoy!

I tried to prototype the apply method, but it doesnt seems to work. Take a look:

        var _superApply = ContentTools.Tools.Link.prototype.apply;
        ContentTools.Tools.Link.prototype.apply = function(element, selection, callback) {  
          // Never get here...
          var attrs = Array.prototype.slice.call(element._domElement.attributes)
          var link = _superApply.call(this);
          for(let i = 0; i < attrs.length; i++) {
            element._domElement.setAttribute(attrs[i].name, attrs[i].value);
          }

          return link;
        };

Any idea?

Thanks!