RailsのTurboでAjaxで要素を削除したときにCSSアニメーションさせる方法2(Stimlus化)

RailsのTurboでAjaxで要素を追加したときにCSSアニメーションさせる方法 では、application.js に記載していましたが、これをStimulus化して利用しやすくしてみます。

やってみる

stream_animations_controller.js

import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  connect() {
    document.addEventListener("turbo:before-stream-render", this.animate)
  }

  disconnect() {
    document.removeEventListener("turbo:before-stream-render", this.animate)
  }

  animate(e) {
    const turboStreamElm = e.target
    const { action, target } = turboStreamElm

    if (action === "remove") {
      const turboFrameElm = document.getElementById(target)
      const { leavingClass } = turboFrameElm.dataset
      if (leavingClass) {
        e.preventDefault()
        turboFrameElm.classList.add(leavingClass)
        turboFrameElm.addEventListener("animationend", () => {
          console.log("aaa");
          e.target.performAction()
        })
      }
    }
  }
}

index.js

registerで追加。

import StreamAnimationsController from "./stream_animations_controller"
application.register("stream-animations", StreamAnimationsController)

html

data-controllerで指定するだけ。

      .images{"data-controller": "stream-animations" }
        = render partial: "image", collection: @user.images, locals: { user: @user }

See Also

RailsのTurboでAjaxで要素を削除したときにCSSアニメーションさせる方法
RailsのHotwireでCSSアニメーションさせる方法(登録処理もTurbo/Stimlusで実装)