Remove usage of 'null' in favor of 'undefined'

This commit is contained in:
Keavon Chambers
2022-08-25 21:32:27 -07:00
parent 1e74ccb4f8
commit 33cb6fcb00
21 changed files with 45 additions and 323 deletions
-164
View File
@@ -1,164 +0,0 @@
const FLING_VELOCITY_THRESHOLD = 10;
const FLING_VELOCITY_WINDOW_SIZE = 20;
let carouselImages;
let carouselDirectionPrev;
let carouselDirectionNext;
let carouselDots;
let carouselDescriptions;
let carouselDragLastClientX;
const velocityDeltaWindow = Array.from({ length: FLING_VELOCITY_WINDOW_SIZE }, () => ({ time: 0, delta: 0 }));
window.addEventListener("DOMContentLoaded", initializeCarousel);
window.addEventListener("pointerup", () => dragEnd(false));
window.addEventListener("scroll", () => dragEnd(true));
window.addEventListener("pointermove", dragMove);
function initializeCarousel() {
carouselImages = document.querySelectorAll(".carousel img");
carouselImages.forEach((image) => {
image.addEventListener("pointerdown", dragBegin);
});
carouselDirectionPrev = document.querySelector(".carousel-controls .direction.prev");
carouselDirectionNext = document.querySelector(".carousel-controls .direction.next");
carouselDots = document.querySelectorAll(".carousel-controls .dot");
carouselDescriptions = document.querySelectorAll(".screenshot-description p");
carouselDirectionPrev.addEventListener("click", () => slideDirection("prev", true, false));
carouselDirectionNext.addEventListener("click", () => slideDirection("next", true, false));
Array.from(carouselDots).forEach((dot) =>
dot.addEventListener("click", (event) => {
const index = Array.from(carouselDots).indexOf(event.target);
slideTo(index, true);
})
);
}
function slideDirection(direction, smooth, clamped = false) {
const directionIndexOffset = { prev: -1, next: 1 }[direction];
const offsetDotIndex = currentClosestImageIndex() + directionIndexOffset;
const nextDotIndex = (offsetDotIndex + carouselDots.length) % carouselDots.length;
const unwrappedNextDotIndex = clamp(offsetDotIndex, 0, carouselDots.length - 1);
if (clamped) slideTo(unwrappedNextDotIndex, smooth);
else slideTo(nextDotIndex, smooth);
}
function slideTo(index, smooth) {
const activeDot = document.querySelector(".carousel-controls .dot.active");
activeDot.classList.remove("active");
carouselDots[index].classList.add("active");
const activeDescription = document.querySelector(".screenshot-description p.active");
activeDescription.classList.remove("active");
carouselDescriptions[index].classList.add("active");
setCurrentTransform(index * -100, "%", smooth);
}
function currentTransform() {
const currentTransformMatrix = window.getComputedStyle(carouselImages[0]).transform;
// Grab the X value from the format that looks like: `matrix(1, 0, 0, 1, -1332.13, 0)` or `none`
return Number(currentTransformMatrix.split(",")[4] || "0");
}
function setCurrentTransform(x, unit, smooth) {
Array.from(carouselImages).forEach((image) => {
image.style.transitionTimingFunction = smooth ? "ease-in-out" : "cubic-bezier(0, 0, 0.2, 1)";
image.style.transform = `translateX(${x}${unit})`;
});
}
function currentClosestImageIndex() {
const currentTransformX = -currentTransform();
const imageWidth = carouselImages[0].getBoundingClientRect().width;
return Math.round(currentTransformX / imageWidth);
}
function currentActiveDotIndex() {
const activeDot = document.querySelector(".carousel-controls .dot.active");
return Array.from(carouselDots).indexOf(activeDot);
}
function dragBegin(event) {
event.preventDefault();
carouselDragLastClientX = event.clientX;
setCurrentTransform(currentTransform(), "px", false);
document.querySelector("#screenshots").classList.add("dragging");
}
function dragEnd(dropWithoutVelocity) {
if (!carouselImages) return;
carouselDragLastClientX = undefined;
document.querySelector("#screenshots").classList.remove("dragging");
const onlyRecentVelocityDeltaWindow = velocityDeltaWindow.filter((delta) => delta.time > Date.now() - 1000);
const timeRange = Date.now() - (onlyRecentVelocityDeltaWindow[0]?.time ?? NaN);
// Weighted (higher by recency) sum of velocity deltas from previous window of frames
const recentVelocity = onlyRecentVelocityDeltaWindow.reduce((acc, entry) => {
const timeSinceNow = Date.now() - entry.time;
const recencyFactorScore = 1 - timeSinceNow / timeRange;
return acc + entry.delta * recencyFactorScore;
}, 0);
const closestImageIndex = currentClosestImageIndex();
const activeDotIndex = currentActiveDotIndex();
// If the speed is fast enough, slide to the next or previous image in that direction
if (Math.abs(recentVelocity) > FLING_VELOCITY_THRESHOLD && !dropWithoutVelocity) {
// Positive velocity should go to the previous image
if (recentVelocity > 0) {
// Don't apply the velocity-based fling if we're already snapping to the next image
if (closestImageIndex >= activeDotIndex) {
slideDirection("prev", false, true);
return;
}
}
// Negative velocity should go to the next image
else {
// Don't apply the velocity-based fling if we're already snapping to the next image
// eslint-disable-next-line no-lonely-if
if (closestImageIndex <= activeDotIndex) {
slideDirection("next", false, true);
return;
}
}
}
// If we didn't slide in a direction due to clear velocity, just snap to the closest image
// This can be reached either by not entering the if statement above, or by its inner if statements not returning early and exiting back to this scope
slideTo(clamp(closestImageIndex, 0, carouselDots.length - 1), true);
}
function dragMove(event) {
if (carouselDragLastClientX === undefined) return;
event.preventDefault();
const LEFT_MOUSE_BUTTON = 1;
if (!(event.buttons & LEFT_MOUSE_BUTTON)) {
dragEnd(false);
return;
}
const deltaX = event.clientX - carouselDragLastClientX;
velocityDeltaWindow.shift();
velocityDeltaWindow.push({ time: Date.now(), delta: deltaX });
const newTransformX = currentTransform() + deltaX;
setCurrentTransform(newTransformX, "px", false);
carouselDragLastClientX = event.clientX;
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
+2 -2
View File
@@ -24,8 +24,8 @@ function initializeRipples() {
ripples = Array.from(navButtons).map((button) => ({
element: button,
animationStartTime: null,
animationEndTime: null,
animationStartTime: 0,
animationEndTime: 0,
goingUp: false,
}));
-115
View File
@@ -1,115 +0,0 @@
const NAV_BUTTON_INITIAL_FONT_SIZE = 32;
const RIPPLE_ANIMATION_MILLISECONDS = 100;
const RIPPLE_WIDTH = 140;
const HANDLE_STRETCH = 0.4;
let ripplesInitialized;
let navButtons;
let rippleSvg;
let ripplePath;
let fullRippleHeight;
let ripples;
let activeRippleIndex;
window.addEventListener("DOMContentLoaded", initializeRipples);
window.addEventListener("resize", () => animate(true));
function initializeRipples() {
ripplesInitialized = true;
navButtons = document.querySelectorAll("header nav a");
rippleSvg = document.querySelector("header .ripple");
ripplePath = rippleSvg.querySelector("path");
fullRippleHeight = Number.parseInt(window.getComputedStyle(rippleSvg).height, 10) - 4;
ripples = Array.from(navButtons).map((button) => ({
element: button,
animationStartTime: null,
animationEndTime: null,
goingUp: false,
}));
activeRippleIndex = ripples.findIndex((ripple) => ripple.element.getAttribute("href").replace(/\//g, "") === window.location.pathname.replace(/\//g, ""));
ripples.forEach((ripple) => {
const updateTimings = (goingUp) => {
const start = ripple.animationStartTime;
const now = Date.now();
const stop = ripple.animationStartTime + RIPPLE_ANIMATION_MILLISECONDS;
const elapsed = now - start;
const remaining = stop - now;
ripple.animationStartTime = now < stop ? now - remaining : now;
ripple.animationEndTime = now < stop ? now + elapsed : now + RIPPLE_ANIMATION_MILLISECONDS;
ripple.goingUp = goingUp;
animate(false);
};
ripple.element.addEventListener("pointerenter", () => updateTimings(true));
ripple.element.addEventListener("pointerleave", () => updateTimings(false));
});
ripples[activeRippleIndex] = {
...ripples[activeRippleIndex],
animationStartTime: 1,
animationEndTime: 1 + RIPPLE_ANIMATION_MILLISECONDS,
goingUp: true,
};
setRipples();
}
function animate(forceRefresh) {
if (!ripplesInitialized) return;
const animateThisFrame = ripples.some((ripple) => ripple.animationStartTime && ripple.animationEndTime && Date.now() <= ripple.animationEndTime);
if (animateThisFrame || forceRefresh) {
setRipples();
window.requestAnimationFrame(() => animate(false));
}
}
function setRipples() {
const navButtonFontSize = Number.parseInt(window.getComputedStyle(navButtons[0]).fontSize, 10) || NAV_BUTTON_INITIAL_FONT_SIZE;
const mediaQueryScaleFactor = navButtonFontSize / NAV_BUTTON_INITIAL_FONT_SIZE;
const rippleHeight = fullRippleHeight * (mediaQueryScaleFactor * 0.5 + 0.5);
const rippleSvgRect = rippleSvg.getBoundingClientRect();
const rippleSvgLeft = rippleSvgRect.left;
const rippleSvgWidth = rippleSvgRect.width;
let path = `M 0,${rippleHeight + 3} `;
ripples.forEach((ripple) => {
if (!ripple.animationStartTime || !ripple.animationEndTime) return;
const t = Math.min((Date.now() - ripple.animationStartTime) / (ripple.animationEndTime - ripple.animationStartTime), 1);
const height = rippleHeight * (ripple.goingUp ? ease(t) : 1 - ease(t));
const buttonRect = ripple.element.getBoundingClientRect();
const buttonCenter = buttonRect.width / 2;
const rippleCenter = (RIPPLE_WIDTH / 2) * mediaQueryScaleFactor;
const rippleOffset = rippleCenter - buttonCenter;
const rippleStartX = buttonRect.left - rippleSvgLeft - rippleOffset;
const rippleRadius = (RIPPLE_WIDTH / 2) * mediaQueryScaleFactor;
const handleRadius = rippleRadius * HANDLE_STRETCH;
path += `L ${rippleStartX},${rippleHeight + 3} `;
path += `c ${handleRadius},0 ${rippleRadius - handleRadius},${-height} ${rippleRadius},${-height} `;
path += `s ${rippleRadius - handleRadius},${height} ${rippleRadius},${height} `;
});
path += `l ${rippleSvgWidth},0`;
ripplePath.setAttribute("d", path);
}
function ease(x) {
return 1 - (1 - x) * (1 - x);
}
+1 -1
View File
@@ -11,7 +11,7 @@
<link rel="stylesheet" href="/base.css">
<link rel="stylesheet" href="https://rsms.me/inter/inter.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Bona+Nova:wght@400;700">
<script src="/navbar.js"></script>
<script src="/js/navbar.js"></script>
<style>
.balance-text {
visibility: hidden;
+1 -1
View File
@@ -329,5 +329,5 @@
</div>
</section>
<script src="/carousel.js"></script>
<script src="/js/carousel.js"></script>
{% endblock content %}