forked from codidact/qpixel
/
posts.js
353 lines (302 loc) · 10.9 KB
/
posts.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
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
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
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
220
221
222
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
// IF YOU CHANGE THESE VALUES YOU MUST ALSO CHANGE app/helpers/posts_helper.rb
const ALLOWED_TAGS = ['a', 'p', 'span', 'b', 'i', 'em', 'strong', 'hr', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'blockquote', 'img', 'strike', 'del', 'code', 'pre', 'br', 'ul', 'ol', 'li', 'sup', 'sub', 'section', 'details',
'summary', 'ins', 'table', 'thead', 'tbody', 'tr', 'th', 'td', 's'];
const ALLOWED_ATTR = ['id', 'class', 'href', 'title', 'src', 'height', 'width', 'alt', 'rowspan', 'colspan', 'lang',
'start', 'dir'];
$(() => {
DOMPurify.addHook("uponSanitizeAttribute", (node, event) => {
const rowspan = node.getAttribute("rowspan");
const colspan = node.getAttribute("colspan");
if (rowspan && Number.isNaN(+rowspan)) {
event.keepAttr = false;
}
if (colspan && Number.isNaN(+colspan)) {
event.keepAttr = false;
}
});
const $uploadForm = $('.js-upload-form');
const stringInsert = (str, idx, insert) => str.slice(0, idx) + insert + str.slice(idx);
const placeholder = "![Uploading, please wait...]()";
$uploadForm.find('input[type="file"]').on('change', async evt => {
const $postField = $('.js-post-field');
const postText = $postField.val();
const cursorPos = $postField[0].selectionStart;
$postField.val(stringInsert(postText, cursorPos, placeholder));
const $tgt = $(evt.target);
const $form = $tgt.parents('form');
$form.submit();
});
$uploadForm.on('submit', async evt => {
evt.preventDefault();
const $tgt = $(evt.target);
const $fileInput = $tgt.find('input[type="file"]');
const files = $fileInput[0].files;
if (files.length > 0 && files[0].size >= 2000000) {
$tgt.find('.js-max-size').addClass('has-color-red-700 error-shake');
const postField = $('.js-post-field');
postField.val(postField.val().replace(placeholder, ''));
setTimeout(() => {
$tgt.find('.js-max-size').removeClass('error-shake');
}, 1000);
return;
}
else {
$tgt.find('.js-max-size').removeClass('has-color-red-700');
}
const resp = await fetch($tgt.attr('action'), {
method: $tgt.attr('method'),
body: new FormData($tgt[0])
});
const data = await resp.json();
if (resp.status === 200) {
$tgt.trigger('ajax:success', data);
}
else {
$tgt.trigger('ajax:failure', data);
}
});
$uploadForm.on('ajax:success', async (evt, data) => {
const $tgt = $(evt.target);
$tgt[0].reset();
const $postField = $('.js-post-field');
const postText = $postField.val();
$postField.val(postText.replace(placeholder, `![Image_alt_text](${data.link})`));
$tgt.parents('.modal').removeClass('is-active');
});
$uploadForm.on('ajax:failure', async (evt, data) => {
const $tgt = $(evt.target);
const $postField = $('.js-post-field');
const error = data['error'];
QPixel.createNotification('danger', error);
$tgt.parents('.modal').removeClass('is-active');
$postField.val($postField.val().replace(placeholder, ''));
});
$('.js-category-select').select2({
tags: true
});
const saveDraft = async (postText, $field, manual = false) => {
const autosavePref = await QPixel.preference('autosave', true);
if (autosavePref !== 'on' && !manual) {
return;
}
const resp = await fetch('/posts/save-draft', {
method: 'POST',
credentials: 'include',
headers: {
'X-CSRF-Token': QPixel.csrfToken(),
'Content-Type': 'application/json'
},
body: JSON.stringify({
post: postText,
path: location.pathname
})
});
if (resp.status === 200) {
const $el = $(`<span>· <span class="has-color-green-600">draft saved</span></span>`);
$field.parents('.widget').find('.js-post-field-footer').append($el);
$el.fadeOut(1500, function () { $(this).remove() });
}
};
$('.js-save-draft').on('click', async ev => {
const $tgt = $(ev.target);
const $field = $tgt.parents('.widget').find('.js-post-field');
const postText = $field.val();
await saveDraft(postText, $field, true);
});
let featureTimeout = null;
let draftTimeout = null;
const postFields = $('.post-field');
postFields.on('paste', async evt => {
if (evt.originalEvent.clipboardData.files.length > 0) {
const $fileInput = $uploadForm.find('input[type="file"]');
$fileInput[0].files = evt.originalEvent.clipboardData.files;
$fileInput.trigger('change');
}
});
postFields.on('focus keyup paste change markdown', (() => {
let previous = null;
return evt => {
const $tgt = $(evt.target);
const text = $(evt.target).val();
// Don't bother re-rendering if nothing's changed
if (text === previous) { return; }
previous = text;
if (!window.converter) {
window.converter = window.markdownit({
html: true,
breaks: false,
linkify: true
});
window.converter.use(window.markdownitFootnote);
window.converter.use(window.latexEscape);
}
window.setTimeout(() => {
const converter = window.converter;
const unsafe_html = converter.render(text);
const html = DOMPurify.sanitize(unsafe_html, {
ALLOWED_TAGS,
ALLOWED_ATTR
});
const removedElements = [...new Set(DOMPurify.removed
.filter(entry => entry.element && !(entry.element instanceof HTMLBodyElement))
.map(entry => entry.element.localName))];
const removedAttributes = [...new Set(DOMPurify.removed
.filter(entry => entry.attribute)
.map(entry => [
entry.attribute.name + (entry.attribute.value ? `='${entry.attribute.value}'` : ''),
entry.from.localName
]))]
$tgt.parents('form')
.find('.rejected-elements')
.toggleClass('hide', removedElements.length === 0 && removedAttributes.length === 0)
.find('ul')
.empty()
.append(
removedElements.map(name => $(`<li><code><${name}></code></li>`)),
removedAttributes.map(([attr, elName]) => $(`<li><code>${attr}</code> (in <code><${elName}></code>)</li>`)));
$tgt.parents('.form-group').siblings('.post-preview').html(html);
$tgt.parents('form').find('.js-post-html[name="__html"]').val(html + '<!-- g: js, mdit -->');
}, 0);
if (featureTimeout) {
clearTimeout(featureTimeout);
}
featureTimeout = setTimeout(() => {
if (window['MathJax']) {
MathJax.typeset();
}
if (window['hljs']) {
hljs.highlightAll();
}
}, 1000);
};
})()).on('keyup', ev => {
clearTimeout(draftTimeout);
const text = $(ev.target).val();
draftTimeout = setTimeout(() => {
saveDraft(text, $(ev.target));
}, 3000);
}).trigger('markdown');
postFields.parents('form').on('submit', async ev => {
const $tgt = $(ev.target);
const field = $tgt.find('.post-field');
const draftDeleted = $tgt.attr('data-draft-deleted') === 'true';
const isValidated = $tgt.attr('data-validated') === 'true';
if (draftDeleted && isValidated) {
return;
}
ev.preventDefault();
// Draft handling
if (!draftDeleted) {
const resp = await fetch('/posts/delete-draft', {
method: 'POST',
credentials: 'include',
headers: {
'X-CSRF-Token': QPixel.csrfToken(),
'Content-Type': 'application/json'
},
body: JSON.stringify({ path: location.pathname })
});
if (resp.status === 200) {
$tgt.attr('data-draft-deleted', 'true');
if (isValidated) {
$tgt.submit();
}
}
else {
console.error('Failed to delete draft.');
}
}
// Validation
if (!isValidated) {
const text = $(field).val();
const validated = QPixel.validatePost(text);
if (validated[0] === true) {
$tgt.attr('data-validated', 'true');
$tgt.submit();
}
else {
const warnings = validated[1].filter(x => x['type'] === 'warning');
const errors = validated[1].filter(x => x['type'] === 'error');
if (warnings.length > 0) {
const $warningBox = $(`<div class="notice is-warning"></div>`);
const $warningList = $(`<ul></ul>`);
warnings.forEach(w => {
$warningList.append(`<li>${w['message']}</li>`);
});
$warningBox.append($warningList);
$tgt.find('input[type="submit"]').before($warningBox);
}
if (errors.length > 0) {
const $errorBox = $(`<div class="notice is-danger"></div>`);
const $errorList = $(`<ul></ul>`);
errors.forEach(e => {
$errorList.append(`<li>${e['message']}</li>`);
});
$errorBox.append($errorList);
$tgt.find('input[type="submit"]').before($errorBox);
}
if (warnings.length > 0 && errors.length === 0) {
$tgt.attr('data-validated', 'true');
}
}
setTimeout(() => {
$tgt.find('input[type="submit"]').attr('disabled', false);
}, 1000);
}
});
$('.js-draft-loaded').each((i, e) => {
$(e).parents('.widget').after(`<div class="notice is-info has-font-size-caption">
<i class="fas fa-exclamation-circle"></i> <strong>Draft loaded.</strong>
You've edited this post before but didn't save it. We loaded your edits here for you.
</div>`);
});
$('.js-permalink > .js-text').text('Copy Link');
$('.js-permalink').on('click', ev => {
ev.preventDefault();
const $tgt = $(ev.target).is('a') ? $(ev.target) : $(ev.target).parents('a');
const link = $tgt.attr('href');
navigator.clipboard.writeText(link);
$tgt.find('.js-text').text('Copied!');
setTimeout(() => {
$tgt.find('.js-text').text('Copy Link');
}, 1000);
});
$('.js-nominate-promotion').on('click', async ev => {
ev.preventDefault();
const $tgt = $(ev.target);
const postId = $tgt.attr('data-post-id');
const resp = await fetch(`/posts/${postId}/promote`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'X-CSRF-Token': QPixel.csrfToken()
}
});
const data = await resp.json();
if (data.success) {
QPixel.createNotification('success', 'Added post to promotion list.');
}
else {
QPixel.createNotification('danger', `Couldn't add post to promotion list. (${resp.status})`);
}
$('.js-mod-tools').removeClass('is-active');
});
$('.js-cancel-edit').on('click', async ev => {
ev.preventDefault();
let $btn = $(ev.target);
if (!confirm($btn.attr('data-question-body'))) {
return;
}
await fetch('/posts/delete-draft', {
method: 'POST',
credentials: 'include',
headers: {
'X-CSRF-Token': QPixel.csrfToken(),
'Content-Type': 'application/json'
},
body: JSON.stringify({ path: location.pathname })
});
location.href = $btn.attr('href');
});
});