Prohlížeč zdrojového kódu
app/javascript/controllers/source_tree_controller.js
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
connect() {
this.element.addEventListener("click", this.handleClick.bind(this))
this._onLoad = this.syncActive.bind(this)
document.addEventListener("turbo:load", this._onLoad)
}
disconnect() {
document.removeEventListener("turbo:load", this._onLoad)
}
syncActive() {
const match = window.location.pathname.match(/^\/source\/(.+?)\/?$/)
const currentPath = match ? match[1] : null
let activeEl = null
this.element.querySelectorAll(".tree-file").forEach(el => {
const link = el.querySelector("a")
if (!link) return
const hrefMatch = link.getAttribute("href")?.match(/^\/source\/(.+?)\/?$/)
const filePath = hrefMatch ? hrefMatch[1] : null
const isActive = filePath !== null && filePath === currentPath
el.classList.toggle("active", isActive)
if (isActive) activeEl = el
})
// Expand every ancestor <details> so the active file is visible
if (activeEl) {
let node = activeEl.parentElement
while (node && node !== this.element) {
if (node.tagName === "DETAILS") node.open = true
node = node.parentElement
}
}
}
handleClick(event) {
const link = event.target.closest(".tree-file a")
if (!link) return
this.element.querySelectorAll(".tree-file.active").forEach(el => el.classList.remove("active"))
link.closest(".tree-file").classList.add("active")
}
}