basecamp / trix

A rich text editor for everyday writing
https://trix-editor.org/
MIT License
19.09k stars 1.12k forks source link

Custom Attachments Issues with ActionText/Rails - Youtube Video Embeds #1062

Open CsalazarGH opened 1 year ago

CsalazarGH commented 1 year ago

Im using trix in rails 7+ for context.

This has been talked about before, but i'm still struggling. I'm trying to attach a YT video into my Trix Editor/ActionText rich content.

let embed = '<iframe width="560" height="315" src="https://www.youtube.com/embed/abcdef"></iframe>'
let attachment = new trixInst.Attachment({ content: embed, contentType: 'text/html' })
trixEdtior.editor.insertAttachment(attachment);

This doesn't work for some reason. It attaches the video into the editor. But after saving it doesn't seem to convert/save to an ActionTextAttachment?

I thought based on this commit (https://github.com/rails/rails/commit/4499a3cdd0c), we can just set the html as the content as long as we set the contentType something custom with HTML?

Do we need to create a partial that matches the contentType? Im not sure. I was able to get something working with SGID's, but I'd really prefer to not have to persist every youtube video into a table record if possible.

I have also whitelisted the Iframe Tag.

Do we still need to do this with SGIDS? and ActionText::Attachable?

colmexdev commented 1 year ago

Hi there.

I used to have a similar situation when embedding content into Trix. If you're using ActionText, You can resolve it creating a non-ActiveRecord model that requires ActionText::Attachable and GlobalID::Indentification, tweaking also the find method so it can instead (re)create the embed content.

For the associated partial, you can create the template wherever inside views folder you choose and specify the relative route inside the to_attachable_partial_path method. That way, it will always be called upon rendering and you avoid persisting an extra model in database.

Next thing, you will need an endpoint to show that embedded content. It must return a JSON object with the SGID and the partial in string format as the content.

That's, very widely, what I did to solve the same situation but applied to some other social networks' content. If you want to explore this alternative, I'll let the material I consulted: