Move hiding logic to stimulus controller

This ensures morphed flashes hide like other flashes (eg in bulk order actions). I wanted to write a spec to prove it, but Capybara doesn't support mocking setTimeout and I didn't want to use sleep.

I've made it optional because this controller is shared with the shop frontend ([supposedly](5ef34347a3), although angular seems to override it).
This commit is contained in:
David Cook
2023-11-30 15:03:08 +11:00
parent 127eaa44e5
commit 7d299affd3
5 changed files with 65 additions and 7 deletions

View File

@@ -32,9 +32,6 @@ jQuery(function($) {
});
}
// Make flash messages dissapear
setTimeout('$(".flash").fadeOut()', 5000);
// Highlight hovered table column
$('table tbody tr td.actions a').hover(function(){
var tr = $(this).closest('tr');

View File

@@ -1,6 +1,6 @@
#flashes
- if defined? flashes
- flashes.each do |type, msg|
.animate-show{"data-controller": "flash"}
.animate-show{"data-controller": "flash", "data-flash-auto-close-value": "true"}
.flash{type: "#{type}", class: "#{type}"}
%span= msg

View File

@@ -5,7 +5,24 @@ document.addEventListener("turbolinks:before-cache", () =>
);
export default class extends Controller {
static values = {
autoClose: Boolean,
};
connect() {
if (this.autoCloseValue) {
setTimeout(this.close.bind(this), 5000);
}
}
close() {
// Fade out
this.element.classList.remove("animate-show");
this.element.classList.add("animate-hide-500");
setTimeout(this.remove.bind(this), 500);
}
remove() {
this.element.remove();
}
}

View File

@@ -11,13 +11,23 @@
}
@keyframes fade-out-hide {
0% {opacity: 1; visibility: visible;}
99% {opacity: 0; visibility: visible;}
100% {opacity: 0; visibility: hidden;}
0% {
opacity: 1;
visibility: visible;
}
99% {
opacity: 0;
visibility: visible;
}
100% {
opacity: 0;
visibility: hidden;
}
}
.animate-hide-500 {
animation: fade-out-hide 0.5s;
opacity: 0; // Stay invisible after animation
}
// @-webkit-keyframes slideOutDown

View File

@@ -0,0 +1,34 @@
/**
* @jest-environment jsdom
*/
import { Application } from "stimulus";
import flash_controller from "../../../app/webpacker/controllers/flash_controller";
describe("FlashController", () => {
beforeAll(() => {
const application = Application.start();
application.register("flash", flash_controller);
});
beforeEach(() => {
document.body.innerHTML = `
<div id="element" data-controller='flash' data-flash-auto-close-value='true'></div>
`;
});
describe("autoClose", () => {
jest.useFakeTimers();
it("is cleared after about 5 seconds", () => {
let element = document.getElementById("element");
expect(element).not.toBe(null);
jest.advanceTimersByTime(5500);
element = document.getElementById("element");
expect(element).toBe(null);
});
});
});