WYSIWYG Editor with Trix

#28 WYSIWYG Editor with Trix
5/9/2016

Summary

Compose beautifully formatted text in your web application. Trix is a WYSIWYG editor for writing messages, comments, articles, and lists.
7
rails wysiwyg view ajax javascript 4:16 min

Summary

Gemfilegem 'trix'
application.js//= require trix
application.css.scss *= require trix
_form.html.erb<%= f.trix_editor :summary %>
articles.coffee$ ->
  document.addEventListener 'trix-attachment-add', (event) ->
    attachment = event.attachment
    if attachment.file
      return sendFile(attachment)
    return

  document.addEventListener 'trix-attachment-remove', (event) ->
    attachment = event.attachment
    deleteFile attachment

  sendFile = (attachment) ->
    file = attachment.file
    form = new FormData
    form.append 'Content-Type', file.type
    form.append 'image[image]', file
    xhr = new XMLHttpRequest
    xhr.open 'POST', '/images', true

    xhr.upload.onprogress = (event) ->
      progress = undefined
      progress = event.loaded / event.total * 100
      attachment.setUploadProgress progress

    xhr.onload = ->
      response = JSON.parse(@responseText)
      attachment.setAttributes
        url: response.url
        image_id: response.image_id
        href: response.url

    xhr.send form

  deleteFile = (n) ->
    $.ajax
      type: 'DELETE'
      url: '/images/' + n.attachment.attributes.values.image_id
      cache: false
      contentType: false
      processData: false

  return

522375?v=3&s=64
Patrik Bóna said 6 months ago:

Hey, nice screencast!


It was really useful, but I've noticed one thing. There is no CSRF protection for file uploads and deletes. This could be really dangerous and I think that it should be fixed.


Btw. commenting is painful. I had to sign up, confirm my email, etc. I had to take a lot of different steps in order to write this comment. It would be great if you could simplify this process.

Photo
Pablo Bello said 3 months ago:

To add CSRF:

xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
xhr.setRequestHeader 'X-CSRF-Token', $('meta[name="csrf-token"]').attr('content')

16906469?v=3&s=64
chunkster29 said about 1 month ago:

Could  it be integrated with the aws-s3 gem

Login to Comment