UNPKG

gatsby-plugin-scroll-indicator

Version:
80 lines (62 loc) 3.47 kB
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); var _extends2 = _interopRequireDefault(require("@babel/runtime/helpers/extends")); var _multimatch = _interopRequireDefault(require("multimatch")); var defaultOptions = { color: "linear-gradient(to right, #CC99F7, #663391)", height: "3px", paths: ["**"], zIndex: "9999" }; exports.onClientEntry = function (_, pluginOptions) { if (pluginOptions === void 0) { pluginOptions = {}; } exports.onRouteUpdate = function (_ref) { var location = _ref.location; // Merge default options with user defined options in `gatsby-config.js` var options = (0, _extends2.default)({}, defaultOptions, pluginOptions); // Check current path with specified paths in options var matchedPaths = (0, _multimatch.default)(location.pathname, options.paths); // Return bool if paths match var enableScroller = matchedPaths.length > 0; // Create indicator container and append to document body var node = document.createElement("div"); node.id = "gatsby-plugin-scroll-indicator"; // check if viewport already has a scroll indicator var indicatorPresent = document.querySelector("#" + node.id); if (enableScroller) { if (!indicatorPresent) { document.body.appendChild(node); var scrolling = false; var indicator = document.getElementById(node.id); // Determine width of scroll indicator var getIndicatorPercentageWidth = function getIndicatorPercentageWidth(currentPos, totalScroll) { return Math.floor(currentPos / totalScroll * 100); }; // Find the total height of scrolling window var getScrollHeight = function getScrollHeight() { // https://javascript.info/size-and-scroll-window#width-height-of-the-document return Math.max(document.body.scrollHeight, document.documentElement.scrollHeight, document.body.offsetHeight, document.documentElement.offsetHeight, document.body.clientHeight, document.documentElement.clientHeight); }; // Add throttled listener to update on scroll window.addEventListener("scroll", function () { var currentPos = window.scrollY, innerHeight = window.innerHeight, scrollHeight = getScrollHeight(), scrollDistance = scrollHeight - innerHeight; if (!scrolling) { window.requestAnimationFrame(function () { var indicatorWidth = getIndicatorPercentageWidth(currentPos, scrollDistance); var color = options.color, height = options.height, zIndex = options.zIndex; indicator.style.cssText = "\n background: " + color + ";\n height: " + height + ";\n left: 0;\n position: fixed;\n top: 0;\n width: " + indicatorWidth + "%;\n transition: width 0.25s;\n z-index: " + zIndex + ";\n "; scrolling = false; }); scrolling = true; } }); } } else { // Try to assign scrollIndicator if it is already attached to the DOM var scrollIndicator = document.querySelector("#gatsby-plugin-scroll-indicator"); // If the indicator is already attached to the DOM, remove it if (scrollIndicator) { scrollIndicator.remove(); } } }; };