From bead5822a87200feb37cba20e88f5c2831f30d87 Mon Sep 17 00:00:00 2001 From: f Date: Tue, 12 Jan 2021 13:38:32 -0300 Subject: [PATCH] turbolinks y anchors --- _packs/entry.js | 26 ++++++++++++++++++++++++++ package.json | 3 +++ 2 files changed, 29 insertions(+) diff --git a/_packs/entry.js b/_packs/entry.js index 5a9e1fa..de80b2d 100644 --- a/_packs/entry.js +++ b/_packs/entry.js @@ -1,9 +1,35 @@ import 'core-js/stable' import 'regenerator-runtime/runtime' +const Turbolinks = require("turbolinks") +Turbolinks.start() + import { Application } from 'stimulus' import { definitionsFromContext } from "stimulus/webpack-helpers" const application = Application.start() const context = require.context("./controllers", true, /\.js$/) application.load(definitionsFromContext(context)) + +// Prevenir que Turbolinks interfiera con la navegación por anchors +// https://github.com/turbolinks/turbolinks/issues/75#issuecomment-445325162 +document.addEventListener('turbolinks:click', event => { + const anchorElement = event.target + const isSamePageAnchor = ( + anchorElement.hash && + anchorElement.origin === window.location.origin && + anchorElement.pathname === window.location.pathname + ) + + if (!isSamePageAnchor) return + + Turbolinks.controller.pushHistoryWithLocationAndRestorationIdentifier(event.data.url, Turbolinks.uuid()) + + event.preventDefault() +}) + +// Prevenir que Turbolinks interfiera la navegación a un anchor al +// recargar la página +document.addEventListener('turbolinks:load', event => { + window.location.hash = window.location.hash +}) diff --git a/package.json b/package.json index 93456c4..b4b562c 100644 --- a/package.json +++ b/package.json @@ -17,5 +17,8 @@ "webpack-cli": "^3.3.12", "webpack-dev-server": "^3.11.0", "webpack-merge": "^5.0.9" + }, + "devDependencies": { + "turbolinks": "^5.2.0" } }