Revamp the Graphite website (#1265)

Revamp the website with more content
This commit is contained in:
Keavon Chambers
2023-08-10 18:37:04 -07:00
parent f2b0abc164
commit f429db6369
76 changed files with 3506 additions and 1670 deletions
+52
View File
@@ -0,0 +1,52 @@
addEventListener("DOMContentLoaded", trackScrollHeadingInTOC);
// Listen for scroll events and update the active section in the table of contents to match the visible content's heading
function trackScrollHeadingInTOC() {
const updateVisibleHeading = () => {
const content = Array.from(document.querySelectorAll("article > *"));
// Find the first element in `content` that is visible in the top of the viewport
let firstVisible = content.find((element) => element.getBoundingClientRect().bottom >= 0);
// Find the next heading
let heading = firstVisible;
while (heading && !heading.tagName.match(/^H[1-6]$/)) {
if (!heading.nextElementSibling) break;
heading = heading.nextElementSibling;
}
// If the next heading isn't fully visible, use the previous heading
if (heading && heading.getBoundingClientRect().bottom > window.innerHeight) {
prevHeading = firstVisible;
while (prevHeading && !prevHeading.tagName.match(/^H[1-6]$/)) {
if (!prevHeading.previousElementSibling) break;
prevHeading = prevHeading.previousElementSibling;
}
if (prevHeading && prevHeading.tagName.match(/^H[1-6]$/)) heading = prevHeading;
}
// If the headding isn't an h1-h6, use the last heading
if (!heading || !heading.tagName.match(/^H[1-6]$/)) {
const filtered = content.filter((element) => element.tagName.match(/^H[1-6]$/));
heading = filtered[filtered.length - 1];
}
// If there is no heading, use the first heading
if (!heading) heading = document.querySelector("article > h1");
// Remove the existing active heading
const existingActive = document.querySelector("aside.contents li.active");
existingActive?.classList.remove("active");
// Exit if there are no headings
if (!heading) return;
// Set the new active heading
const tocHeading = document.querySelector(`aside.contents a[href="#${heading.id}"]`)?.parentElement;
if (tocHeading instanceof HTMLElement) tocHeading.classList.add("active");
};
addEventListener("scroll", updateVisibleHeading);
updateVisibleHeading();
}
-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);
}
+32
View File
@@ -0,0 +1,32 @@
window.addEventListener("DOMContentLoaded", initializeFundraisingBar);
function initializeFundraisingBar() {
const VISIBILITY_COVERAGE_FRACTION = 0.5;
let loaded = false;
const fundraising = document.querySelector("[data-fundraising]");
const bar = fundraising.querySelector("[data-fundraising-bar]");
const dynamicPercent = fundraising.querySelector("[data-fundraising-percent] [data-dynamic]")
const dynamicGoal = fundraising.querySelector("[data-fundraising-goal] [data-dynamic]")
if (!(fundraising instanceof HTMLElement && bar instanceof HTMLElement && dynamicPercent instanceof HTMLElement && dynamicGoal instanceof HTMLElement)) return;
const setFundraisingGoal = async () => {
const request = await fetch("https://graphite.rs/fundraising-goal");
/** @type {{ percentComplete: number, targetValue: number }} */
const data = await request.json();
fundraising.classList.remove("loading");
bar.style.setProperty("--fundraising-percent", `${data.percentComplete}%`);
dynamicPercent.textContent = data.percentComplete;
dynamicGoal.textContent = data.targetValue;
loaded = true;
};
new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!loaded && entry.intersectionRatio > VISIBILITY_COVERAGE_FRACTION) setFundraisingGoal();
});
}, { threshold: VISIBILITY_COVERAGE_FRACTION })
.observe(fundraising);
}
+279
View File
@@ -0,0 +1,279 @@
// ================================================================================================
// CAROUSEL
// ================================================================================================
const FLING_VELOCITY_THRESHOLD = 10;
const FLING_VELOCITY_WINDOW_SIZE = 20;
window.addEventListener("DOMContentLoaded", initializeCarousel);
window.addEventListener("pointerup", () => dragEnd(false));
window.addEventListener("scroll", () => dragEnd(true));
window.addEventListener("pointermove", dragMove);
const carousels = [];
function initializeCarousel() {
const carouselContainers = document.querySelectorAll("[data-carousel]");
carouselContainers.forEach((carouselContainer) => {
const images = carouselContainer.querySelectorAll("[data-carousel-image]");
const directionPrev = carouselContainer.querySelector("[data-carousel-prev]");
const directionNext = carouselContainer.querySelector("[data-carousel-next]");
const dots = carouselContainer.querySelectorAll("[data-carousel-dot]");
const descriptions = carouselContainer.querySelectorAll("[data-carousel-description]");
const dragLastClientX = undefined;
const velocityDeltaWindow = Array.from({ length: FLING_VELOCITY_WINDOW_SIZE }, () => ({ time: 0, delta: 0 }));
const carousel = {
carouselContainer,
images,
directionPrev,
directionNext,
dots,
descriptions,
dragLastClientX,
velocityDeltaWindow,
};
carousels.push(carousel);
images.forEach((image) => {
image.addEventListener("pointerdown", dragBegin);
});
directionPrev.addEventListener("click", () => slideDirection(carousel, "prev", true, false));
directionNext.addEventListener("click", () => slideDirection(carousel, "next", true, false));
Array.from(dots).forEach((dot) =>
dot.addEventListener("click", (event) => {
const index = Array.from(dots).indexOf(event.target);
slideTo(carousel, index, true);
})
);
});
}
function slideDirection(carousel, direction, smooth, clamped = false) {
const directionIndexOffset = { prev: -1, next: 1 }[direction];
const offsetDotIndex = currentClosestImageIndex(carousel) + directionIndexOffset;
const nextDotIndex = (offsetDotIndex + carousel.dots.length) % carousel.dots.length;
const unwrappedNextDotIndex = clamp(offsetDotIndex, 0, carousel.dots.length - 1);
if (clamped) slideTo(carousel, unwrappedNextDotIndex, smooth);
else slideTo(carousel, nextDotIndex, smooth);
}
function slideTo(carousel, index, smooth) {
const activeDot = carousel.carouselContainer.querySelector("[data-carousel-dot].active");
activeDot.classList.remove("active");
carousel.dots[index].classList.add("active");
const activeDescription = carousel.carouselContainer.querySelector("[data-carousel-description].active");
if (activeDescription) {
activeDescription.classList.remove("active");
carousel.descriptions[index].classList.add("active");
}
setCurrentTransform(carousel, index * -100, "%", smooth);
}
function currentTransform(carousel) {
const currentTransformMatrix = window.getComputedStyle(carousel.images[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(carousel, x, unit, smooth) {
Array.from(carousel.images).forEach((image) => {
image.style.transitionTimingFunction = smooth ? "ease-in-out" : "cubic-bezier(0, 0, 0.2, 1)";
image.style.transform = `translateX(${x}${unit})`;
});
}
function currentClosestImageIndex(carousel) {
const currentTransformX = -currentTransform(carousel);
const imageWidth = carousel.images[0].getBoundingClientRect().width;
return Math.round(currentTransformX / imageWidth);
}
function currentActiveDotIndex(carousel) {
const activeDot = carousel.carouselContainer.querySelector("[data-carousel-dot].active");
return Array.from(carousel.dots).indexOf(activeDot);
}
function dragBegin(event) {
const carouselContainer = event.target.closest("[data-carousel]");
const carousel = carousels.find((carousel) => carousel.carouselContainer === carouselContainer);
if (!carousel) return;
event.preventDefault();
carousel.dragLastClientX = event.clientX;
setCurrentTransform(carousel, currentTransform(carousel), "px", false);
carouselContainer.classList.add("dragging");
}
function dragEnd(dropWithoutVelocity) {
const carousel = carousels.find((carousel) => carousel.dragLastClientX !== undefined);
if (!carousel) return;
if (!carousel.images) return;
carousel.dragLastClientX = undefined;
carousel.carouselContainer.classList.remove("dragging");
const onlyRecentVelocityDeltaWindow = carousel.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(carousel);
const activeDotIndex = currentActiveDotIndex(carousel);
// 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(carousel, "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(carousel, "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(carousel, clamp(closestImageIndex, 0, carousel.dots.length - 1), true);
}
function dragMove(event) {
const carouselContainer = event.target.closest("[data-carousel]");
const carousel = carousels.find((carousel) => carousel.carouselContainer === carouselContainer);
if (!carousel) return;
if (carousel.dragLastClientX === undefined) return;
event.preventDefault();
const LEFT_MOUSE_BUTTON = 1;
if (!(event.buttons & LEFT_MOUSE_BUTTON)) {
dragEnd(false);
return;
}
const deltaX = event.clientX - carousel.dragLastClientX;
carousel.velocityDeltaWindow.shift();
carousel.velocityDeltaWindow.push({ time: Date.now(), delta: deltaX });
const newTransformX = currentTransform(carousel) + deltaX;
setCurrentTransform(carousel, newTransformX, "px", false);
carousel.dragLastClientX = event.clientX;
}
function clamp(value, min, max) {
return Math.min(Math.max(value, min), max);
}
// ================================================================================================
// IMAGE COMPARISON
// ================================================================================================
const RECENTER_DELAY = 1;
const RECENTER_ANIMATION_DURATION = 0.25;
window.addEventListener("DOMContentLoaded", initializeImageComparison);
function initializeImageComparison() {
Array.from(document.querySelectorAll("[data-image-comparison]")).forEach((element) => {
const moveHandler = (event) => {
const factor = (event.clientX - element.getBoundingClientRect().left) / element.getBoundingClientRect().width;
const capped = Math.max(0, Math.min(1, factor));
if (!(element instanceof HTMLElement)) return;
element.style.setProperty("--comparison-percent", `${capped * 100}%`);
element.dataset.lastInteraction = "";
};
const leaveHandler = (event) => {
moveHandler(event);
const randomCode = Math.random().toString().substring(2);
element.dataset.lastInteraction = randomCode;
setTimeout(() => {
if (element.dataset.lastInteraction === randomCode) {
element.dataset.recenterStartTime = Date.now();
element.dataset.recenterStartValue = parseFloat(element.style.getPropertyValue("--comparison-percent"));
recenterAnimationStep();
}
}, RECENTER_DELAY * 1000);
};
const recenterAnimationStep = () => {
if (element.dataset.lastInteraction === "") return;
const completionFactor = (Date.now() - element.dataset.recenterStartTime) / (RECENTER_ANIMATION_DURATION * 1000);
if (completionFactor > 1) {
element.dataset.lastInteraction = "";
return;
}
const factor = smootherstep(completionFactor);
const newLocation = lerp(element.dataset.recenterStartValue, 50, factor);
element.style.setProperty("--comparison-percent", `${newLocation}%`);
requestAnimationFrame(recenterAnimationStep);
};
const lerp = (a, b, t) => (1 - t) * a + t * b;
const smootherstep = (x) => x * x * x * (x * (x * 6 - 15) + 10);
element.addEventListener("pointermove", moveHandler);
element.addEventListener("pointerenter", moveHandler);
element.addEventListener("pointerleave", leaveHandler);
element.addEventListener("dragstart", (event) => event.preventDefault());
});
}
// ================================================================================================
// AUTO-PLAYING VIDEO
// ================================================================================================
window.addEventListener("DOMContentLoaded", initializeVideoAutoPlay);
function initializeVideoAutoPlay() {
const VISIBILITY_COVERAGE_FRACTION = 0.25;
let loaded = false;
const player = document.querySelector("[data-auto-play]");
if (!(player instanceof HTMLVideoElement)) return;
new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (!loaded && entry.intersectionRatio > VISIBILITY_COVERAGE_FRACTION) {
player.play();
loaded = true;
};
});
}, { threshold: VISIBILITY_COVERAGE_FRACTION })
.observe(player);
}
+14 -3
View File
@@ -1,6 +1,6 @@
const NAV_BUTTON_INITIAL_FONT_SIZE = 32;
const RIPPLE_ANIMATION_MILLISECONDS = 100;
const RIPPLE_WIDTH = 140;
const RIPPLE_WIDTH = 120;
const HANDLE_STRETCH = 0.4;
let ripplesInitialized;
@@ -29,7 +29,18 @@ function initializeRipples() {
goingUp: false,
}));
activeRippleIndex = ripples.findIndex((ripple) => ripple.element.getAttribute("href").replace(/\//g, "") === window.location.pathname.replace(/\//g, ""));
activeRippleIndex = ripples.findIndex((ripple) => {
let link = ripple.element.getAttribute("href");
if (!link.endsWith("/")) link += "/";
let location = window.location.pathname;
if (!location.endsWith("/")) location += "/";
// Special case for the root, which will otherwise match as the starting prefix of all pages
if (link === "/" && location === "/") return true;
if (link === "/") return false;
return location.startsWith(link);
});
ripples.forEach((ripple) => {
const updateTimings = (goingUp) => {
@@ -51,7 +62,7 @@ function initializeRipples() {
ripple.element.addEventListener("pointerleave", () => updateTimings(false));
});
ripples[activeRippleIndex] = {
if (activeRippleIndex >= 0) ripples[activeRippleIndex] = {
...ripples[activeRippleIndex],
animationStartTime: 1,
animationEndTime: 1 + RIPPLE_ANIMATION_MILLISECONDS,