WYSIWYG Editor with Trix

Episode #28 by Teacher's Avatar David Kimura

Summary

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

Resources

Summary

# Gemfile
gem '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