/
editor_page_contents.js
81 lines (69 loc) · 2.14 KB
/
editor_page_contents.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
//= require "trix"
(function() {
$(document).on('trix-before-initialize', () => {
Trix.config.blockAttributes.heading1.tagName = 'h2';
Trix.config.attachments.preview.caption = { name: false, size: false }
});
function listenForEditorChange() {
var $editorContents = $('.js-contents')
, originalContents = $editorContents.val()
, $title = $('.js-title-input')
, originalTitle = $title.val()
;
document.addEventListener('trix-change', changeHandler($editorContents, originalContents));
$title.on('input', changeHandler($title, originalTitle));
}
function changeHandler($elmt, original) {
return function() {
if ($elmt.val() != original) {
$('.js-save').attr('disabled', false);
$('.js-post-save-button').attr('disabled', true);
} else {
$('.js-save').attr('disabled', true);
$('.js-post-save-button').attr('disabled', false);
}
}
}
function listenForAttachments() {
document.addEventListener('trix-attachment-add', (e) => {
var attachment = e.attachment;
if (attachment.file) {
uploadImage(e.attachment.file, setProgress, setAttributes);
}
function setProgress(progress) {
attachment.setUploadProgress(progress);
}
function setAttributes(attributes) {
attachment.setAttributes(attributes);
}
});
}
function uploadImage(file, onProgress, onSuccess) {
var data = new FormData();
data.append('image', file);
$.ajax({
xhr: () => {
var xhr = new window.XMLHttpRequest();
// upload progress
xhr.upload.addEventListener("progress", function(event) {
var progress = event.loaded / event.total * 100
onProgress(progress)
}, false);
return xhr;
},
url: 'upload_image',
type: 'POST',
data: data,
processData: false,
contentType: false,
success: onSuccess,
error: (jqXHR, textStatus, errorThrown) => {
alert(`Failed to upload image.\nError:${errorThrown}`);
}
})
}
$(function() {
listenForAttachments();
listenForEditorChange();
});
})();