Skip to content

Commit c8bc118

Browse files
committed
stabilize anchor position during thread loading
1 parent 450de93 commit c8bc118

File tree

1 file changed

+22
-0
lines changed

1 file changed

+22
-0
lines changed

app/javascript/controllers/batch_loader_controller.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,10 +39,25 @@ export default class extends Controller {
3939
}
4040
}
4141

42+
findScrollAnchor() {
43+
if (window.location.hash) {
44+
const el = document.getElementById(window.location.hash.slice(1))
45+
if (el) return el
46+
}
47+
for (const card of this.element.querySelectorAll('.message-card')) {
48+
const rect = card.getBoundingClientRect()
49+
if (rect.bottom > 0 && rect.top < window.innerHeight) return card
50+
}
51+
return null
52+
}
53+
4254
injectBatch(html) {
4355
const template = document.createElement("template")
4456
template.innerHTML = html
4557

58+
const anchor = this.findScrollAnchor()
59+
const anchorTop = anchor ? anchor.getBoundingClientRect().top : null
60+
4661
template.content.querySelectorAll("[data-message-id]").forEach(batchItem => {
4762
const messageId = batchItem.dataset.messageId
4863
const card = this.element.querySelector(
@@ -76,5 +91,12 @@ export default class extends Controller {
7691
}
7792
}
7893
})
94+
95+
if (anchor && anchorTop !== null) {
96+
const drift = anchor.getBoundingClientRect().top - anchorTop
97+
if (Math.abs(drift) > 1) {
98+
window.scrollBy(0, drift)
99+
}
100+
}
79101
}
80102
}

0 commit comments

Comments
 (0)