Skip to content

Commit

Permalink
abstract /delete-draft request logic & ensured drafts can be manually…
Browse files Browse the repository at this point in the history
… deleted
  • Loading branch information
Oaphi committed Dec 1, 2024
1 parent ffa4b0a commit bd00424
Showing 1 changed file with 39 additions and 21 deletions.
60 changes: 39 additions & 21 deletions app/assets/javascripts/posts.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,33 @@ $(() => {
}
};

/**
* @typedef {{ removeNotice?: boolean }} DeleteDraftOptions
*
* Attempts to remove a post draft
* @param {DeleteDraftOptions} [options]
* @returns {Promise<boolean>}
*/
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
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -360,8 +386,8 @@ $(() => {
}
});

$('.js-draft-loaded').each((i, e) => {
$(e).parents('.widget').after(`<div class="notice is-info has-font-size-caption">
$('.js-draft-loaded').each((_i, e) => {
$(e).parents('.widget').after(`<div class="notice is-info has-font-size-caption js-draft-notice">
<i class="fas fa-exclamation-circle"></i> <strong>Draft loaded.</strong>
You had edited this before but haven't saved it. We loaded the edits for you.
</div>`);
Expand Down Expand Up @@ -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');
});
Expand Down

0 comments on commit bd00424

Please sign in to comment.