2021-11-22 17:51:50 +00:00
|
|
|
import { Controller } from "stimulus";
|
2020-11-12 20:29:12 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
* Al navegar por el sitio y llegar a ciertas secciones, se van
|
|
|
|
* activando ítems del menú.
|
|
|
|
*
|
|
|
|
* Para eso configuramos un IntersectionObserver en todo el documento y
|
|
|
|
* a medida que van apareciendo secciones actualizamos el menú.
|
|
|
|
*/
|
|
|
|
export default class extends Controller {
|
2021-11-22 17:51:50 +00:00
|
|
|
static targets = ["section"];
|
2020-11-12 20:29:12 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
connect() {
|
2020-11-12 20:29:12 +00:00
|
|
|
for (const section of this.sectionTargets) {
|
2021-11-22 17:51:50 +00:00
|
|
|
this.observer.observe(section);
|
2020-11-12 20:29:12 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/*
|
|
|
|
* Solo nos interesa la primera
|
|
|
|
*/
|
2021-11-22 17:51:50 +00:00
|
|
|
get observer() {
|
|
|
|
if (!this._observer)
|
|
|
|
this._observer = new IntersectionObserver(
|
|
|
|
(entries, observer) => this.update(entries),
|
|
|
|
this.options
|
|
|
|
);
|
|
|
|
|
|
|
|
return this._observer;
|
2020-11-12 20:29:12 +00:00
|
|
|
}
|
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
get options() {
|
|
|
|
if (!this._options) this._options = { threshold: 0, rootMargin: "0px" };
|
2020-11-12 20:29:12 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
return this._options;
|
2020-11-12 20:29:12 +00:00
|
|
|
}
|
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
update(entries) {
|
|
|
|
const section = entries.find((x) => x.isIntersecting);
|
2020-11-12 20:29:12 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
if (!section) return;
|
2020-11-12 20:29:12 +00:00
|
|
|
|
2021-11-22 17:51:50 +00:00
|
|
|
window.dispatchEvent(
|
|
|
|
new CustomEvent("scroll:section", { detail: { id: section.target.id } })
|
|
|
|
);
|
2020-11-12 20:29:12 +00:00
|
|
|
}
|
|
|
|
}
|