Skip to content

Commit

Permalink
Destroy modals before leaving
Browse files Browse the repository at this point in the history
  • Loading branch information
daniel-nerdgeschoss committed Dec 18, 2024
1 parent 89ee9d3 commit b4176df
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 2 deletions.
4 changes: 4 additions & 0 deletions spec/rails_app/app/controllers/posts_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ def index
@posts = Post.all
end

def show
@post = Post.find(params[:id])
end

def new
@post = Post.new
end
Expand Down
2 changes: 2 additions & 0 deletions spec/rails_app/app/views/posts/new.html.slim
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ h1 Compose Post
= f.input :image, as: :image, placeholder: "Image of the post"
= f.submit "Save"
= link_to "Cancel", close_modal_path

= link_to "Something completely different", other_posts_path
1 change: 1 addition & 0 deletions spec/rails_app/app/views/posts/other.html.slim
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
h1 Something completely different!
2 changes: 2 additions & 0 deletions spec/rails_app/config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@
collection do
get :modal
end

get :other, on: :collection
end

get "styleguide", to: "pages#styleguide"
Expand Down
17 changes: 15 additions & 2 deletions src/modal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export class ModalPresenter {

constructor() {
document.addEventListener("turbo:load", this.prepareBlind);
document.addEventListener("turbo:before-cache", this.leave.bind(this));
}

async open(options: ModalOptions): Promise<void> {
Expand All @@ -38,8 +39,16 @@ export class ModalPresenter {
document.body.classList.toggle("modal-open", open);
}

private leave(): void {
Object.values(this.modals).map((e) => e.destroy());
this.modals = {};
this.updateBlindStatus();
}

private prepareBlind: () => void = () => {
createElement(document.body, "modal-blind");
if (!document.querySelector("body > .modal-blind")) {
createElement(document.body, "modal-blind");
}
};
}

Expand Down Expand Up @@ -82,7 +91,11 @@ export class Modal {
}
root.classList.remove("modal--open");
await wait(1);
root.remove();
this.destroy();
}

destroy(): void {
this.root?.remove();
this.root = undefined;
}
}

0 comments on commit b4176df

Please sign in to comment.