dropzone_input.js.coffee 8.67 KB
Newer Older
1 2 3 4 5 6 7 8
class @DropzoneInput
  constructor: (form) ->
    Dropzone.autoDiscover = false
    alertClass = "alert alert-danger alert-dismissable div-dropzone-alert"
    alertAttr = "class=\"close\" data-dismiss=\"alert\"" + "aria-hidden=\"true\""
    divHover = "<div class=\"div-dropzone-hover\"></div>"
    divSpinner = "<div class=\"div-dropzone-spinner\"></div>"
    divAlert = "<div class=\"" + alertClass + "\"></div>"
9
    iconPaperclip = "<i class=\"fa fa-paperclip div-dropzone-icon\"></i>"
10
    iconSpinner = "<i class=\"fa fa-spinner fa-spin div-dropzone-icon\"></i>"
11
    uploadProgress = $("<div class=\"div-dropzone-progress\"></div>")
12
    btnAlert = "<button type=\"button\"" + alertAttr + ">&times;</button>"
Douwe Maan's avatar
Douwe Maan committed
13
    project_uploads_path = window.project_uploads_path or null
14
    markdown_preview_path = window.markdown_preview_path or null
15
    max_file_size = gon.max_file_size or 10
16 17 18

    form_textarea = $(form).find("textarea.markdown-area")
    form_textarea.wrap "<div class=\"div-dropzone\"></div>"
19
    form_textarea.on 'paste', (event) =>
20
      handlePaste(event)
21
    form_textarea.on "input", ->
22
      hideReferencedUsers()
23
    form_textarea.on "blur", ->
24
      renderMarkdown()
25 26 27 28

    form_dropzone = $(form).find('.div-dropzone')
    form_dropzone.parent().addClass "div-dropzone-wrapper"
    form_dropzone.append divHover
29
    form_dropzone.find(".div-dropzone-hover").append iconPaperclip
30
    form_dropzone.append divSpinner
31
    form_dropzone.find(".div-dropzone-spinner").append iconSpinner
32
    form_dropzone.find(".div-dropzone-spinner").append uploadProgress
33
    form_dropzone.find(".div-dropzone-spinner").css
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
      "opacity": 0
      "display": "none"

    # Preview button
    $(document).off "click", ".js-md-preview-button"
    $(document).on "click", ".js-md-preview-button", (e) ->
      ###
      Shows the Markdown preview.

      Lets the server render GFM into Html and displays it.
      ###
      e.preventDefault()
      form = $(this).closest("form")
      # toggle tabs
      form.find(".js-md-write-button").parent().removeClass "active"
      form.find(".js-md-preview-button").parent().addClass "active"

      # toggle content
      form.find(".md-write-holder").hide()
      form.find(".md-preview-holder").show()

55
      renderMarkdown()
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73

    # Write button
    $(document).off "click", ".js-md-write-button"
    $(document).on "click", ".js-md-write-button", (e) ->
      ###
      Shows the Markdown textarea.
      ###
      e.preventDefault()
      form = $(this).closest("form")
      # toggle tabs
      form.find(".js-md-write-button").parent().addClass "active"
      form.find(".js-md-preview-button").parent().removeClass "active"

      # toggle content
      form.find(".md-write-holder").show()
      form.find(".md-preview-holder").hide()

    dropzone = form_dropzone.dropzone(
Douwe Maan's avatar
Douwe Maan committed
74
      url: project_uploads_path
75 76
      dictDefaultMessage: ""
      clickable: true
Douwe Maan's avatar
Douwe Maan committed
77
      paramName: "file"
78
      maxFilesize: max_file_size
79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
      uploadMultiple: false
      headers:
        "X-CSRF-Token": $("meta[name=\"csrf-token\"]").attr("content")

      previewContainer: false

      processing: ->
        $(".div-dropzone-alert").alert "close"

      dragover: ->
        form_textarea.addClass "div-dropzone-focus"
        form.find(".div-dropzone-hover").css "opacity", 0.7
        return

      dragleave: ->
        form_textarea.removeClass "div-dropzone-focus"
        form.find(".div-dropzone-hover").css "opacity", 0
        return

      drop: ->
        form_textarea.removeClass "div-dropzone-focus"
        form.find(".div-dropzone-hover").css "opacity", 0
        form_textarea.focus()
        return

      success: (header, response) ->
        child = $(dropzone[0]).children("textarea")
        $(child).val $(child).val() + formatLink(response.link) + "\n"
        return

      error: (temp, errorMessage) ->
110 111
        errorAlert = $(form).find('.error-alert')
        checkIfMsgExists = errorAlert.children().length
112
        if checkIfMsgExists is 0
113
          errorAlert.append divAlert
114 115 116
          $(".div-dropzone-alert").append btnAlert + errorMessage
        return

117 118 119 120
      totaluploadprogress: (totalUploadProgress) ->
        uploadProgress.text Math.round(totalUploadProgress) + "%"
        return

121 122 123 124 125 126
      sending: ->
        form_dropzone.find(".div-dropzone-spinner").css
          "opacity": 0.7
          "display": "inherit"
        return

127 128
      queuecomplete: ->
        uploadProgress.text ""
129 130 131 132 133 134 135 136 137 138
        $(".dz-preview").remove()
        $(".markdown-area").trigger "input"
        $(".div-dropzone-spinner").css
          "opacity": 0
          "display": "none"
        return
    )

    child = $(dropzone[0]).children("textarea")

139
    hideReferencedUsers = ->
140
      referencedUsers = form.find(".referenced-users")
141 142 143
      referencedUsers.hide()

    renderReferencedUsers = (users) ->
144
      referencedUsers = form.find(".referenced-users")
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172

      if referencedUsers.length
        if users.length >= 10
          referencedUsers.show()
          referencedUsers.find(".js-referenced-users-count").text users.length
        else
          referencedUsers.hide()

    renderMarkdown = ->
      preview = form.find(".js-md-preview")
      mdText = form.find(".markdown-area").val()
      if mdText.trim().length is 0
        preview.text "Nothing to preview."
        hideReferencedUsers()
      else
        preview.text "Loading..."
        $.ajax(
          type: "POST",
          url: markdown_preview_path,
          data: {
            text: mdText
          },
          dataType: "json"
        ).success (data) ->
          preview.html data.body

          renderReferencedUsers data.references.users

Douwe Maan's avatar
Douwe Maan committed
173 174 175
    formatLink = (link) ->
      text = "[#{link.alt}](#{link.url})"
      text = "!#{text}" if link.is_image
176
      text
177

178 179 180 181 182 183 184 185 186 187 188
    handlePaste = (event) ->
      pasteEvent = event.originalEvent
      if pasteEvent.clipboardData and pasteEvent.clipboardData.items
        image = isImage(pasteEvent)
        if image
          event.preventDefault()

          filename = getFilename(pasteEvent) or "image.png"
          text = "{{" + filename + "}}"
          pasteText(text)
          uploadFile image.getAsFile(), filename
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219

    isImage = (data) ->
      i = 0
      while i < data.clipboardData.items.length
        item = data.clipboardData.items[i]
        if item.type.indexOf("image") isnt -1
          return item
        i++
      return false

    pasteText = (text) ->
      caretStart = $(child)[0].selectionStart
      caretEnd = $(child)[0].selectionEnd
      textEnd = $(child).val().length

      beforeSelection = $(child).val().substring 0, caretStart
      afterSelection = $(child).val().substring caretEnd, textEnd
      $(child).val beforeSelection + text + afterSelection
      form_textarea.trigger "input"

    getFilename = (e) ->
      if window.clipboardData and window.clipboardData.getData
        value = window.clipboardData.getData("Text")
      else if e.clipboardData and e.clipboardData.getData
        value = e.clipboardData.getData("text/plain")

      value = value.split("\r")
      value.first()

    uploadFile = (item, filename) ->
      formData = new FormData()
Douwe Maan's avatar
Douwe Maan committed
220
      formData.append "file", item, filename
221
      $.ajax
Douwe Maan's avatar
Douwe Maan committed
222
        url: project_uploads_path
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262
        type: "POST"
        data: formData
        dataType: "json"
        processData: false
        contentType: false
        headers:
          "X-CSRF-Token": $("meta[name=\"csrf-token\"]").attr("content")

        beforeSend: ->
          showSpinner()
          closeAlertMessage()

        success: (e, textStatus, response) ->
          insertToTextArea(filename, formatLink(response.responseJSON.link))

        error: (response) ->
          showError(response.responseJSON.message)

        complete: ->
          closeSpinner()

    insertToTextArea = (filename, url) ->
      $(child).val (index, val) ->
        val.replace("{{" + filename + "}}", url + "\n")

    appendToTextArea = (url) ->
      $(child).val (index, val) ->
        val + url + "\n"

    showSpinner = (e) ->
      form.find(".div-dropzone-spinner").css
        "opacity": 0.7
        "display": "inherit"

    closeSpinner = ->
      form.find(".div-dropzone-spinner").css
        "opacity": 0
        "display": "none"

    showError = (message) ->
263 264
      errorAlert = $(form).find('.error-alert')
      checkIfMsgExists = errorAlert.children().length
265
      if checkIfMsgExists is 0
266
        errorAlert.append divAlert
267 268 269 270 271 272 273 274 275 276
        $(".div-dropzone-alert").append btnAlert + message

    closeAlertMessage = ->
      form.find(".div-dropzone-alert").alert "close"

    form.find(".markdown-selector").click (e) ->
      e.preventDefault()
      $(@).closest('.gfm-form').find('.div-dropzone').click()
      return

Douwe Maan's avatar
Douwe Maan committed
277 278 279
  formatLink: (link) ->
    text = "[#{link.alt}](#{link.url})"
    text = "!#{text}" if link.is_image
280
    text