-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy patheditor.js
474 lines (437 loc) · 13.9 KB
/
editor.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
import axios from 'axios';
import { DateTime } from 'luxon';
import '../../css/feed-editor.css';
import { editorToolConfig } from './helpers/editorConfig.js';
import {
NETWORK_LIMITS,
debouncedUpdateDelimiters,
getSlugFromTitle,
parseAndInsertDelimiters,
socialLinksToArray,
socialLinksToMap,
updateDelimiters,
} from './helpers/editorHelpers.js';
import EditorJS from '@editorjs/editorjs';
import SocialPostDelimiter from './SocialPostDelimiter.js';
import debounce from 'lodash.debounce';
import TomSelect from 'tom-select';
const postMeta = {
title: '',
slug: DateTime.now().toFormat('yyyyMMddHHmm'),
tags: [],
relatedPost: null,
relatedPostModel: null,
id: null,
socialLinks: {},
};
const editors = {
primary: null,
twitter: null,
mastodon: null,
bluesky: null,
};
const validation = {
twitter: true,
mastodon: true,
bluesky: true,
};
let savedPost = {};
let tagSelect;
let relatedPostsSelect;
let socialPostsCheckbox;
let saveButton;
let deleteButton;
// Change handlers -------------------------------------------------------------------------------
/**
* When the title changes:
* - Autogenerate the new slug if it's not manually set.
* - Update the postMeta.slug
* - Update the postMeta.title
*/
function onTitleChange() {
const slugElement = document.getElementById('slug');
if (postMeta.slug === getSlugFromTitle(postMeta.title)) {
postMeta.slug = getSlugFromTitle(this.value);
slugElement.value = postMeta.slug;
}
postMeta.title = this.value;
}
const debouncedOnTitleChange = debounce(onTitleChange, 250);
/**
* Update the postMeta.slug when the title changes
*/
function onSlugChange() {
postMeta.slug = this.value;
}
const debouncedOnSlugChange = debounce(onSlugChange, 250);
/**
* Toggle the social post editors when the social post checkbox is toggled.
* This initializes the editors if they've not already been initialized; otherwise, it shows/hides them.
* This also handles taking care of the initial post validation to determine if the social posts can be saved.
* @param {Event} evt
*/
async function toggleSocialPosts({ target: { checked } }) {
const editorsWrapper = document.querySelector('.social-editors');
if (checked) {
editorsWrapper.classList.remove('hidden');
// Initialize once
if (!editors.twitter) {
const post = await editors.primary.save();
for (const network of ['twitter', 'mastodon', 'bluesky']) {
const postWithDelimiters = parseAndInsertDelimiters(post, network);
editors[network] = new EditorJS({
holder: `${network}-editor`,
tools: {
...editorToolConfig,
socialPostDelimiter: {
class: SocialPostDelimiter,
config: {
limit: NETWORK_LIMITS[network].post,
},
},
},
onChange: async (api) => {
const post = await api.saver.save();
validation[network] = debouncedUpdateDelimiters(
editors[network],
post,
network,
network === 'mastodon'
? document.getElementById('mastodon-tags').value
: null,
);
validate();
},
data: postWithDelimiters,
});
// Check initial validity
validation[network] = postWithDelimiters.blocks.every(
(block) =>
block.type !== 'socialPostDelimiter' ||
block.data.limitExceeded === false,
);
}
validate();
}
} else {
editorsWrapper.classList.add('hidden');
saveButton.removeAttribute('disabled');
}
}
/**
* Toggle whether the post will be posted to a given network, then revalidate.
* @param {Event} evt
*/
function toggleSocialPostForNetwork(evt) {
const network = evt.target.id.split('-')[0];
if (!evt.target.checked) {
document.getElementById(`${network}-editor`).classList.add('hidden');
} else {
document.getElementById(`${network}-editor`).classList.remove('hidden');
}
validate();
}
/**
* Update the postMeta.socialLinks when the social post link changes
*/
function onSocialPostLinkChange() {
if (this.value) {
postMeta.socialLinks[this.id] = this.value;
} else {
delete postMeta.socialLinks[this.id];
}
}
const debouncedOnSocialChange = debounce(onSocialPostLinkChange, 250);
// Helpers to keep form in sync with DB after save ----------------------------------------------
/**
* Save relevant data from the backend to the postMeta copy.
* @param {Object} data
*/
function updateModelFromDb(data) {
savedPost = data;
postMeta.title = data.title;
postMeta.slug = data.slug;
postMeta.tags = data.tags;
postMeta.id = data.id;
postMeta.relatedPost = data.relatedPost;
postMeta.relatedPostModel = data.relatedPostModel;
postMeta.socialLinks = socialLinksToMap(data.socialLinks);
}
/**
* Set the form inputs to the values in the postMeta copy.
*/
function setInputValues() {
const titleEl = document.getElementById('title');
const slugEl = document.getElementById('slug');
const lastEdited = document.getElementById('last-edited');
titleEl.value = postMeta.title;
slugEl.value = postMeta.slug;
tagSelect.setValue(postMeta.tags);
relatedPostsSelect.setValue(postMeta.relatedPost);
Object.entries(postMeta.socialLinks).forEach(([key, value]) => {
document.getElementById(key).value = value;
});
if (savedPost.updatedAt) {
slugEl.setAttribute('disabled', true);
lastEdited.textContent = `Last edited: ${DateTime.fromISO(savedPost.updatedAt).toLocaleString(DateTime.DATETIME_FULL)}`;
}
}
// Validate ---------------------------------------------------------------------------------------
/**
* Validate the social posts and enable/disable the save button accordingly.
*/
function validate() {
const isValid = Object.entries(validation).every(
([network, value]) =>
// Check that each entry is either valid OR not selected to be posted
value || !document.getElementById(`${network}-social`).checked,
);
if (!isValid) {
saveButton.setAttribute('disabled', true);
} else {
saveButton.removeAttribute('disabled');
}
}
// Social helpers --------------------------------------------------------------------------------
/**
* Get the content of a social post editor.
* @param {string} network
* @returns {Promise<null|Object>}
*/
async function getSocialPostContent(network) {
if (!document.getElementById(`${network}-social`).checked) {
return null;
}
const resp = {};
if (network === 'mastodon') {
let tags = document.getElementById('mastodon-tags').value;
if (tags) {
tags = tags.split(/, ?/g);
resp.tags = tags
.map((tag) => {
let trimmed = tag.trim();
if (!tag.startsWith('#')) {
return `#${trimmed}`;
}
return trimmed;
})
.join(' ');
}
}
const post = await editors[network].save();
resp.blocks = post.blocks;
return resp;
}
/**
* Update delimiters based on Mastodon tag change and revalidate, since it affects character count.
* @param {Event} evt
*/
async function onMastodonTagsChange(evt) {
// Use the non-debounced update since this function is debounced.
const post = await editors.mastodon.save();
validation.mastodon = await updateDelimiters(
editors.mastodon,
post,
'mastodon',
evt.target.value,
);
validate();
}
const debouncedOnMastodonTagsChange = debounce(onMastodonTagsChange, 250);
// Save -------------------------------------------------------------------------------------------
/**
* Save the post and send social posts (if enabled).
*/
function save() {
saveButton.setAttribute('disabled', true);
editors.primary.save().then(async (savedData) => {
// Select update or create endpoint
const endpoint = savedPost._id
? `/dynamic-api/micro/entry/${savedPost._id}`
: '/dynamic-api/micro/entry';
const transformedPostMeta = {
...postMeta,
socialLinks: socialLinksToArray(postMeta.socialLinks),
};
// Update or create micro post
const promises = [
axios.post(endpoint, {
...transformedPostMeta,
post: savedData,
}),
];
// If social posts are enabled, also hit the social endpoint
if (socialPostsCheckbox.checked) {
const [twitter, mastodon, bluesky] = await Promise.all([
getSocialPostContent('twitter'),
getSocialPostContent('mastodon'),
getSocialPostContent('bluesky'),
]);
promises.push(
axios.post('/dynamic-api/micro/social', {
twitter,
mastodon,
bluesky,
}),
);
}
// Wait for the post and social post promises to resolve
Promise.all(promises)
.then(([postResp, socialResp]) => {
// Hit the tags endpoint to fetch new tags with their IDs
const tagsPromise = axios.get('/dynamic-api/tags');
let postPromise;
if (socialResp) {
// Update the post again with the social post links
postPromise = axios.post(
`/dynamic-api/micro/entry/${postResp.data._id}`,
{
...transformedPostMeta,
socialLinks: socialLinksToArray(socialResp.data),
},
);
} else {
postPromise = Promise.resolve(postResp);
}
// Pass the post and tags responses to the next block
return Promise.all([postPromise, tagsPromise]);
})
.then(([postResp, tags]) => {
// Update tags select
tagSelect.clearOptions();
tagSelect.addOptions(tags.data);
// Update postMeta and form to reflect backend changes
updateModelFromDb(postResp.data);
setInputValues();
deleteButton.classList.remove('hidden');
// Re-enable save button
saveButton.removeAttribute('disabled');
// Add slug to URL now that the post has been created
window.history.pushState(
{},
null,
`/micro/editor/${postResp.data.slug}`,
);
});
});
}
// Delete -----------------------------------------------------------------------------------------
/**
* Delete a saved post.
*/
function deletePost() {
deleteButton.setAttribute('disabled', true);
axios.delete(`/dynamic-api/micro/entry/${savedPost._id}`).then(() => {
window.location = '/feed';
});
}
// On first load --------------------------------------------------------------------------------
async function onFirstLoad() {
// Load post data if we're editing an existing post
let slug = window.location.pathname.split('/').slice(3);
if (slug.length && slug[0] !== '') {
slug = slug[0];
try {
const resp = await axios.get(`/dynamic-api/micro/entry/${slug}`);
if (resp) {
updateModelFromDb(resp.data);
} else {
throw new Error('No post found');
}
} catch (err) {
if (err && err.response && err.response.status === 404) {
document.querySelector('#error-overlay .error-message').textContent =
`No post with the slug "${slug}" was found.`;
document.getElementById('loading-overlay').classList.add('hidden');
document.getElementById('error-overlay').classList.remove('hidden');
return;
}
throw err;
}
}
// Load editor
editors.primary = new EditorJS({
holder: 'editorjs',
autofocus: true,
tools: {
...editorToolConfig,
socialPostDelimiter: {
class: SocialPostDelimiter,
config: {
limit: null,
},
},
},
data: savedPost.post || {},
});
// Load TomSelect for tags editor
const { data: tagOptions } = await axios.get('/dynamic-api/tags');
tagSelect = new TomSelect('#tags', {
create: true,
items: postMeta.tags,
valueField: '_id',
searchField: ['text'],
options: tagOptions,
maxOptions: null,
closeAfterSelect: true,
});
// Load TomSelect for related posts
const { data: relatedOptions } = await axios.get(
'/dynamic-api/micro/relatedPosts',
);
relatedPostsSelect = new TomSelect('#related', {
items: postMeta.relatedPost,
valueField: '_id',
labelField: 'title',
searchField: ['title'],
options: relatedOptions,
allowEmptyOption: true,
});
// Selectors
const titleEl = document.getElementById('title');
const slugEl = document.getElementById('slug');
socialPostsCheckbox = document.getElementById('social-posts');
const mastodonTags = document.getElementById('mastodon-tags');
saveButton = document.getElementById('save-button');
deleteButton = document.getElementById('delete-button');
// Set initial values
setInputValues();
// Attach handlers
titleEl.addEventListener('keydown', debouncedOnTitleChange);
slugEl.addEventListener('keydown', debouncedOnSlugChange);
socialPostsCheckbox.addEventListener('change', toggleSocialPosts);
document
.querySelectorAll('.social-network-toggle')
.forEach((el) => el.addEventListener('change', toggleSocialPostForNetwork));
mastodonTags.addEventListener('keydown', debouncedOnMastodonTagsChange);
document
.querySelectorAll('.social-post-id')
.forEach((el) => el.addEventListener('keydown', debouncedOnSocialChange));
// TomSelect uses .on instead of .addEventListener, attach those handlers
tagSelect.on('change', function (value) {
if (value) {
postMeta.tags = value.split(',');
} else {
postMeta.tags = [];
}
});
relatedPostsSelect.on('change', function (value) {
if (value) {
postMeta.relatedPost = value;
postMeta.relatedPostModel = relatedOptions.find(
(opt) => opt._id === value,
).type;
} else {
postMeta.relatedPost = null;
postMeta.relatedPostModel = null;
}
});
saveButton.addEventListener('click', save);
deleteButton.addEventListener('click', deletePost);
if (savedPost._id) {
deleteButton.classList.remove('hidden');
}
// Ready
document.getElementById('loading-overlay').classList.add('hidden');
}
document.addEventListener('DOMContentLoaded', onFirstLoad);