80 lines
2.1 KiB
JavaScript
80 lines
2.1 KiB
JavaScript
import { Controller } from "@hotwired/stimulus"
|
|
import { showToast } from "../services/toast";
|
|
|
|
export default class PosteditController extends Controller {
|
|
static targets = ['bodyTextEdit'];
|
|
static values = {
|
|
saveAction: String,
|
|
};
|
|
|
|
connect() {
|
|
this.bodyTextEditTarget.focus();
|
|
}
|
|
|
|
async save(ev) {
|
|
ev.preventDefault();
|
|
|
|
try {
|
|
await this._postForm(this.saveActionValue);
|
|
|
|
showToast({
|
|
title: "💾 Post Saved",
|
|
body: (this.saveActionValue === "Save Draft") ? "Post saved as draft." : "Post updated.",
|
|
});
|
|
} catch (e) {
|
|
console.error(e);
|
|
showToast({
|
|
title: "❌ Error",
|
|
body: "Unable to save post. Please try again later.",
|
|
});
|
|
}
|
|
}
|
|
|
|
async publish(ev) {
|
|
ev.preventDefault();
|
|
|
|
try {
|
|
await this._postForm("Publish");
|
|
|
|
window.location.href = this.element.getAttribute("action");
|
|
} catch (e) {
|
|
console.error(e);
|
|
showToast({
|
|
title: "❌ Error",
|
|
body: "Unable to publish post. Please try again later.",
|
|
});
|
|
}
|
|
}
|
|
|
|
async _postForm(action) {
|
|
if (this._isPosting) {
|
|
return;
|
|
}
|
|
this._isPosting = true;
|
|
|
|
try {
|
|
const formData = new FormData(this.element);
|
|
let data = Object.fromEntries(formData.entries());
|
|
data = {...data, action: action || 'save'};
|
|
|
|
const response = await fetch(this.element.getAttribute("action"), {
|
|
method: 'POST',
|
|
headers: {
|
|
'Accept': 'application/json',
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(data),
|
|
});
|
|
|
|
if (!response.ok) {
|
|
throw new Error(`HTTP error! status: ${response.status}`);
|
|
}
|
|
|
|
return response.json();
|
|
} finally {
|
|
this._isPosting = false;
|
|
}
|
|
}
|
|
|
|
|
|
} |