|
| 1 | +import { Controller } from "@hotwired/stimulus" |
| 2 | + |
| 3 | +export default class extends Controller { |
| 4 | + connect() { |
| 5 | + this.activeItem = null |
| 6 | + this.setupObserver() |
| 7 | + } |
| 8 | + |
| 9 | + disconnect() { |
| 10 | + if (this.observer) { |
| 11 | + this.observer.disconnect() |
| 12 | + } |
| 13 | + } |
| 14 | + |
| 15 | + setupObserver() { |
| 16 | + const options = { |
| 17 | + root: null, |
| 18 | + rootMargin: "-20% 0px -60% 0px", |
| 19 | + threshold: 0 |
| 20 | + } |
| 21 | + |
| 22 | + this.observer = new IntersectionObserver((entries) => { |
| 23 | + this.handleIntersection(entries) |
| 24 | + }, options) |
| 25 | + |
| 26 | + document.querySelectorAll(".message-card[id^='message-']").forEach((card) => { |
| 27 | + this.observer.observe(card) |
| 28 | + }) |
| 29 | + } |
| 30 | + |
| 31 | + handleIntersection(entries) { |
| 32 | + let visibleMessages = [] |
| 33 | + |
| 34 | + entries.forEach((entry) => { |
| 35 | + if (entry.isIntersecting) { |
| 36 | + visibleMessages.push({ |
| 37 | + element: entry.target, |
| 38 | + top: entry.boundingClientRect.top |
| 39 | + }) |
| 40 | + } |
| 41 | + }) |
| 42 | + |
| 43 | + if (visibleMessages.length === 0) return |
| 44 | + |
| 45 | + visibleMessages.sort((a, b) => a.top - b.top) |
| 46 | + const topMessage = visibleMessages[0].element |
| 47 | + const messageId = topMessage.id.replace("message-", "") |
| 48 | + |
| 49 | + this.highlightOutlineItem(messageId) |
| 50 | + } |
| 51 | + |
| 52 | + highlightOutlineItem(messageId) { |
| 53 | + if (this.activeItem) { |
| 54 | + this.activeItem.classList.remove("outline-active") |
| 55 | + } |
| 56 | + if (this.activeSummary) { |
| 57 | + this.activeSummary.classList.remove("outline-active") |
| 58 | + } |
| 59 | + |
| 60 | + const outlineItem = this.element.querySelector(`a[href="#message-${messageId}"]`) |
| 61 | + if (outlineItem) { |
| 62 | + const itemContainer = outlineItem.closest(".outline-item") || outlineItem |
| 63 | + itemContainer.classList.add("outline-active") |
| 64 | + this.activeItem = itemContainer |
| 65 | + |
| 66 | + const parentDetails = outlineItem.closest("details.branch-details") |
| 67 | + if (parentDetails) { |
| 68 | + const summary = parentDetails.querySelector(":scope > summary") |
| 69 | + if (summary) { |
| 70 | + summary.classList.add("outline-active") |
| 71 | + this.activeSummary = summary |
| 72 | + } |
| 73 | + } |
| 74 | + } |
| 75 | + } |
| 76 | +} |
0 commit comments