Back after a reload remounts: history.state keeps the previous view's id

Open
#4,507 0 comments 0 reactions 0 assignees View on GitHub

Maintainers usually reply within 1 day

Nobody has claimed this yet.

Assessment

Difficulty
4/5
Estimated time
3-5 days
Newbie friendliness
45/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Domain
frontend

Research direction

Start with the initial history write in assets/js/phoenix_live_view/view.ts, which runs only when history.state is null, and the popstate handler in live_socket.ts, which remounts when the entry's id differs from the main view's. Run the reproduction script with Playwright and check whether a back step after a reload patches instead of remounting. Done means that holds without changing the intended behavior for entries written by an earlier document, which the issue leaves open for maintainers to decide.

Written by the indexing model from the issue text.

Description

Environment

  • Phoenix LiveView 1.2.13 from Hex (tag v1.2.13, d8252e1e21238e150e9e6b3d7285d4c060d28e6e).
  • Also on main at ce708ec855fe6b3c6b0cb8318dc489078b525b09 (reports 1.3.0-dev); its committed priv/static/phoenix_live_view.js includes the history entry reservation from #4492.
  • Phoenix 1.8.16, Bandit 1.14.1, Elixir 1.20.4, Erlang/OTP 29.1.2, macOS 27.2.1.
  • Browser: Chromium 156.0.8078.4, headless, driven by Playwright 1.64.1.
  • Not tried: Firefox, Safari, or the steps below performed by hand (see Notes).

Actual behavior

After a full page reload, history.state for the current entry still holds the id of the main view from the document before the reload. The reloaded page's main view gets a new id, but the initial history entry is only written when history.state === null, so the entry keeps the old id.

A later push_patch adds a new entry and sets backType on the reloaded entry, but leaves its id as it was. Going back to that entry, with history.back() or the browser's Back button, fails the id === this.main.id check in the popstate handler, which by the code linked below then calls replaceMain instead of pushLinkPatch. The view is mounted again: mount/3 runs again and phx:page-loading-stop reports kind: "initial", instead of handle_params/3 running on the connected view.

Without the reload, the same patch and back step patch as expected.

After the remount the entry still carries the first document's id (in the reproduction's console output below).

Seen in a separate application, not in the script below: a modal opened with push_patch and closed with history.back(). Before any reload the back step patches and focus returns to the control that opened the modal. After a reload, the back step remounts the page, its DOM is replaced, and focus ends on <body>.

Expected behavior

After a reload, a back step to the reloaded entry behaves as it does without the reload: it patches the connected main view (handle_params/3) and does not remount it.

Reproduction

The script below is LiveView's single-file sample with one LiveView that shows a value set in mount/3, a push_patch link and a history.back() button. A small listener logs the main view's id and history.state.id on every phx:page-loading-stop.

Application.put_env(:phoenix, Example.Endpoint,
  http: [ip: {127, 0, 0, 1}, port: String.to_integer(System.get_env("PORT", "5001"))],
  adapter: Bandit.PhoenixAdapter,
  server: true,
  live_view: [signing_salt: "aaaaaaaa"],
  secret_key_base: String.duplicate("a", 64)
)

Mix.install([
  {:bandit, "~> 1.8"},
  {:jason, "~> 1.2"},
  {:phoenix, "~> 1.8"},
  {:phoenix_html, "~> 4.1"},
  {:phoenix_live_view,
   github: "phoenixframework/phoenix_live_view",
   ref: "ce708ec855fe6b3c6b0cb8318dc489078b525b09",
   override: true}
  # Same result with the latest release: {:phoenix_live_view, "1.2.13"}
])

defmodule Example.ErrorView do
  def render(template, _), do: Phoenix.Controller.status_message_from_template(template)
end

defmodule Example.HomeLive do
  use Phoenix.LiveView, layout: {__MODULE__, :live}

  def mount(_params, _session, socket) do
    {:ok, assign(socket, :mount_id, System.unique_integer([:positive]))}
  end

  def handle_params(params, _uri, socket) do
    {:noreply, assign(socket, :page, params["page"] || "one")}
  end

  def render("live.html", assigns) do
    ~H"""
    <script src="/assets/phoenix/phoenix.js">
    </script>
    <script src="/assets/phoenix_live_view/phoenix_live_view.js">
    </script>
    <script>
      let liveSocket = new window.LiveView.LiveSocket("/live", window.Phoenix.Socket);
      liveSocket.connect();
      window.addEventListener("phx:page-loading-stop", (e) => {
        const main = document.querySelector("[data-phx-main]");
        console.log(`page-loading-stop kind=${e.detail.kind} main id=${main && main.id} history.state.id=${history.state && history.state.id}`);
      });
    </script>
    {@inner_content}
    """
  end

  def render(assigns) do
    ~H"""
    <p>mount id: <span id="mount-id">{@mount_id}</span></p>
    <p>page: <span id="page">{@page}</span></p>
    <.link id="patch" patch="/?page=two">push_patch to page two</.link>
    <button id="back" onclick="history.back()">history.back()</button>
    """
  end
end

defmodule Example.Router do
  use Phoenix.Router
  import Phoenix.LiveView.Router

  pipeline :browser do
    plug :accepts, ["html"]
  end

  scope "/", Example do
    pipe_through :browser

    live "/", HomeLive, :index
  end
end

defmodule Example.Endpoint do
  use Phoenix.Endpoint, otp_app: :phoenix

  socket "/live", Phoenix.LiveView.Socket

  plug Plug.Static, from: {:phoenix, "priv/static"}, at: "/assets/phoenix"
  plug Plug.Static, from: {:phoenix_live_view, "priv/static"}, at: "/assets/phoenix_live_view"

  plug Example.Router
end

{:ok, _} = Supervisor.start_link([Example.Endpoint], strategy: :one_for_one)
IO.puts("phoenix #{Application.spec(:phoenix, :vsn)}, phoenix_live_view #{Application.spec(:phoenix_live_view, :vsn)}")
Process.sleep(:infinity)

Steps:

  1. Run elixir repro.exs and open http://localhost:5001/ with the browser console open. Note the mount id.
  2. Click "push_patch to page two", then "history.back()". The page shows "one" and the mount id is unchanged: the back step patched. This is the control.
  3. Reload the page. The mount id changes, as expected. The console logs kind=initial with a new main id and the old history.state.id from step 1.
  4. Click "push_patch to page two". The mount id is unchanged.
  5. Click "history.back()". The page shows "one", but the mount id has changed and the console logs kind=initial: the view was mounted again.
  6. Reload, click "push_patch to page two", then press the browser's Back button. The mount id changes again, as in step 5.

Mount ids and ids read at each step, with the console lines copied as logged, from the automated run on main at ce708ec (the run on 1.2.13 gave the same pattern):

1. first load: mount id 18568, main id phx-GOfDk-_kkqi8SWwG, history.state.id phx-GOfDk-_kkqi8SWwG
2. patch, then history.back() without a reload: mount id 18568 (same, patched)
3. after reload: mount id 27911, main id phx-GOfDk_hogSjkGWyG, history.state.id phx-GOfDk-_kkqi8SWwG
   page-loading-stop kind=initial main id=phx-GOfDk_hogSjkGWyG history.state.id=phx-GOfDk-_kkqi8SWwG
4. patch to page two: mount id 27911
   page-loading-stop kind=patch main id=phx-GOfDk_hogSjkGWyG history.state.id=phx-GOfDk_hogSjkGWyG
5. history.back(): mount id 27975 (changed, remounted)
   page-loading-stop kind=initial main id=phx-GOfDk_hogSjkGWyG history.state.id=phx-GOfDk-_kkqi8SWwG
6. reload, patch, browser Back: mount id 28167 then 28231 (changed, remounted)

On 1.2.13 the same steps gave mount ids 41799, 41799 (patched), 41991 after the reload, 42055 after history.back() (remounted), and 42247 then 42311 for the browser's Back button (remounted).

Where in the code

The initial entry's id is written only when there is no state, so a reload keeps the previous document's id:

if (this.isMain() && window.history.state === null) {
  // set initial history entry if this is the first page load (no history)
  Browser.pushState("replace", {
    type: "patch",
    id: this.id,
    position: this.liveSocket.currentHistoryPosition,
  });
}

When a patch adds an entry, the current entry gets backType only and keeps its id:

The popstate handler patches only when the entry's id is the current main view's, and otherwise remounts:

Notes

  • Verified only in headless Chromium driven by Playwright, which ran exactly steps 1–6 against this script on main at ce708ec and on 1.2.13. The manual steps are the same actions but were not performed by hand. Firefox and Safari were not tried.
  • Seen in a separate application on 1.2.13, not with this script: loading the same URL again (which Chromium treats as a reload) leaves the same stale id, and replacing history.state.id with the connected main view's id after the initial join made the next back step patch instead of remount. That is an observation about the cause, not a proposed patch.
  • Not checked: whether refusing to patch an entry written by an earlier document is intended.
Dominant language
Elixir
Stars
6.8k
Forks
1.1k
Avg merge
1d 3h
Merged PRs (30d)
19

Getting set up

This project ships no dev container, Dockerfile or contributing guide, so setting up is up to you: start from its README, and see our first-contribution guide for the general steps.

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from phoenixframework/phoenix_live_view

All issues in phoenixframework/phoenix_live_view

Similar issues

More Elixir issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.