From bd00424af9ce9d366e6eadd287e1f1149a53fc3f Mon Sep 17 00:00:00 2001 From: Oleg Valter Date: Mon, 2 Dec 2024 01:30:13 +0300 Subject: [PATCH] abstract /delete-draft request logic & ensured drafts can be manually deleted --- app/assets/javascripts/posts.js | 60 +++++++++++++++++++++------------ 1 file changed, 39 insertions(+), 21 deletions(-) diff --git a/app/assets/javascripts/posts.js b/app/assets/javascripts/posts.js index ca816dc4e..8d8385119 100644 --- a/app/assets/javascripts/posts.js +++ b/app/assets/javascripts/posts.js @@ -139,6 +139,33 @@ $(() => { } }; + /** + * @typedef {{ removeNotice?: boolean }} DeleteDraftOptions + * + * Attempts to remove a post draft + * @param {DeleteDraftOptions} [options] + * @returns {Promise} + */ + const deleteDraft = async (options = {}) => { + const res = 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 }) + }); + + const success = res.status === 200; + + if (success && options.removeNotice) { + $('.js-draft-notice').remove() + } + + return success; + } + /** * Extracts draft info from a given target * @param {EventTarget} target post input field or "save draft" button @@ -179,6 +206,12 @@ $(() => { return { draft, field: $bodyField }; }; + $('.js-delete-draft').on('click', async () => { + await deleteDraft({ + removeNotice: true + }); + }); + $('.js-save-draft').on('click', async (ev) => { const { draft, field } = parseDraft(ev.target); await saveDraft(draft, field, true); @@ -295,16 +328,9 @@ $(() => { // 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) { + const status = await deleteDraft(); + + if (status) { $tgt.attr('data-draft-deleted', 'true'); if (isValidated) { @@ -360,8 +386,8 @@ $(() => { } }); - $('.js-draft-loaded').each((i, e) => { - $(e).parents('.widget').after(`
+ $('.js-draft-loaded').each((_i, e) => { + $(e).parents('.widget').after(`
Draft loaded. You had edited this before but haven't saved it. We loaded the edits for you.
`); @@ -451,15 +477,7 @@ $(() => { 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 }) - }); + await deleteDraft(); location.href = $btn.attr('href'); });