Bug: buildNavJs forEach error when parent.clientWidth == 0
fixed
### Disclaimer
- [x] I am aware that this issue will be closed or converted to a discussion if the requested code is missing or invalid.
### Description
Pagy v43.5.1
Came across an issue in `nav.render()` in `buildNavJs` with turbolinks.
We're using a Stimulus controller to fire Pagy.init() on connect().
On initial page load, it all works correctly.
When I then click on any pagination link and it turbolinks navigates, I get a js error.
`series[index].forEach()` throws as `index == -1`.
This seems to be caused by `parent.clientWidth == 0` while turbolinks is re-rendering.
`nav.render()` is being called twice on initial page load, and twice on turbolinks page load.
In the first `nav.render()`, called from buildNavJs, `parent.clientWidth == 1400`. As expected.
In the second call from ResizeObserver, `parent.clientWidth == 0`. Throws.
On initial page load, both calls correctly return `1400`. Just the first ResizeObserver call after navigation throws.
On browser resize it works fine too.
I was able to get it working using 3 methods:
a) by changing `<` to `<=` to fallback to the smallest breakpoint:
```diff
- const index = widths.findIndex((w) => w < parent.clientWidth);
+ const index = widths.findIndex((w) => w <= parent.clientWidth);
```
b) keep using `<` and default to the smallest breakpoint when index is < 0:
```diff
- const index = widths.findIndex((w) => w < parent.clientWidth);
+ let index = widths.findIndex((w) => w < parent.clientWidth);
+ if (index === -1) { index = widths.length - 1; }
```
c) or simply return early if clientWidth is 0 and let the next `nav.render()` handle it:
```diff
+ if (parent.clientWidth === 0) return;
```
**Our setup**
/config/initializers/pagy.rb
```ruby
Pagy::OPTIONS[:steps] = { 0 => 5, 576 => 10 }
```
/app/javascript/controllers/pagy_init_controller.js
```javascript
import { Controller } from "@hotwired/stimulus";
import Pagy from "pagy.mjs"
export default class extends Controller {
connect() {
if (!Pagy) return;
Pagy.init(this.element);
}
}
```
/app/views/nav/_pagy.html.slim
```
.d-flex.justify-content-center data-controller="pagy-init"
== pagy.series_nav_js if pagy.pages > 1
```
关闭于 2026-04-24 5 条评论