Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 49 additions & 0 deletions app/assets/javascripts/stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,57 @@ document.addEventListener("DOMContentLoaded", () => {
debounceTimer = window.setTimeout(updateMarkdown, 300);
});
});

const form = document.querySelector(".edit_story");
const backButton = document.getElementById("back");
const logo = document.getElementById("logo");
let isDirty = false;

if (form) {
// Mark the form as dirty when any input changes
form.addEventListener("input", function () {
isDirty = true;
addBeforeUnloadEventListener(isDirty);
});

// Reset isDirty on form submission
form.addEventListener("submit", function () {
isDirty = false;
addBeforeUnloadEventListener(isDirty);
});
}

// Attach a click event to the custom back button
[backButton, logo].forEach(element => {
element.addEventListener("click", function (event) {
if (isDirty) {
const confirmLeave = confirm("You have unsaved changes. Are you sure you want to go back?");
if (confirmLeave) {
// Optionally, reset isDirty if leaving
isDirty = false;
addBeforeUnloadEventListener(isDirty)
} else {
// Prevent navigation if the user chooses not to leave
event.preventDefault();
}
}
})
});
});

function addBeforeUnloadEventListener(isDirty) {
if (isDirty) {
window.addEventListener("beforeunload", warnUserIfUnsavedEdits);
} else {
window.removeEventListener("beforeunload", warnUserIfUnsavedEdits);
}
}

function warnUserIfUnsavedEdits(event) {
event.preventDefault();
event.returnValue = '';
}

function updateStatusButton(color, status) {
const button = document.querySelector(".story-title .dropdown-wrapper > button");
button.className = `button ${color}`;
Expand Down
26 changes: 26 additions & 0 deletions spec/features/stories_manage_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,32 @@
expect(page).to have_content "Story updated!"
end

it "alerts me when I try to navigate away from the page without saving my edits", js: true do
visit project_path(id: project.id)
click_button "More actions"
click_link "Edit"

click_link "Back"
assert_current_path project_path(id: project.id)

click_button "More actions"
click_link "Edit"

fill_in "story[title]", with: "As a user, I want to edit stories"

dismiss_confirm("You have unsaved changes. Are you sure you want to go back?") do
find("#logo").click
end

assert_current_path edit_project_story_path(project, story)

accept_confirm("You have unsaved changes. Are you sure you want to go back?") do
click_link "Back"
end

assert_current_path project_path(id: project.id)
end

it "allows me to delete a story" do
visit project_path(id: project.id)

Expand Down