feat: coordinate sections signs and native navigation

This commit is contained in:
2026-09-02 04:27:10 +03:00
parent 9bbe4652ac
commit 22d456a6ca
11 changed files with 1510 additions and 31 deletions

View File

@@ -0,0 +1,243 @@
import {
onMounted,
onUnmounted,
readonly,
shallowRef,
watch,
type Ref,
} from "vue";
import type { SectionId } from "@/content/types";
import type { NavigationState } from "@/journey/navigation-controller";
import {
activationLineDocumentY,
deriveSectionState,
isAtDocumentEnd,
selectActiveSection,
type SectionHeadingGeometry,
} from "@/journey/section-controller";
import { nextSign } from "@/journey/sign-controller";
import type { JourneySnapshot } from "@/journey/types";
import { useScrollDrive } from "./useScrollDrive";
const PASSIVE_LISTENER: AddEventListenerOptions = { passive: true };
const initialJourney = (activeSectionId: SectionId): JourneySnapshot => ({
scrollY: 0,
routeProgress: 0,
direction: 0,
acceleration: 0,
driveSpeed: 0.18,
...deriveSectionState(activeSectionId),
sign: null,
});
export function useJourneySections(
canonicalIds: readonly SectionId[],
navigationState: Readonly<Ref<NavigationState>>,
motionAllowed?: Readonly<Ref<boolean>>,
): Readonly<Ref<JourneySnapshot>> {
const firstId = canonicalIds[0];
if (firstId === undefined) {
throw new Error("At least one canonical journey section is required.");
}
const drive = useScrollDrive();
const snapshot = shallowRef<JourneySnapshot>(initialJourney(firstId));
let scheduleMeasurement = (): void => {};
let teardown = (): void => {};
const stopNavigationWatch = watch(
() => navigationState.value,
() => scheduleMeasurement(),
);
const stopMotionWatch =
motionAllowed === undefined
? (): void => {}
: watch(motionAllowed, () => scheduleMeasurement());
onMounted(() => {
const visualViewport = window.visualViewport;
let frameId: number | undefined;
let disposed = false;
let previousScrollY = window.scrollY;
let previousActiveId = firstId;
let headings: readonly SectionHeadingGeometry[] = [];
const readHeadings = (): readonly SectionHeadingGeometry[] =>
canonicalIds.flatMap((id) => {
const heading = document.getElementById(`${id}-heading`);
return heading instanceof HTMLElement
? [{ id, top: heading.getBoundingClientRect().top + window.scrollY }]
: [];
});
const measure = (): void => {
frameId = undefined;
headings = readHeadings();
if (headings.length === 0) return;
const scrollingElement =
document.scrollingElement ?? document.documentElement;
const viewportHeight =
visualViewport?.height ?? document.documentElement.clientHeight;
const viewportOffsetTop = visualViewport?.offsetTop ?? 0;
const scrollY = scrollingElement.scrollTop;
const activationY = activationLineDocumentY({
scrollY,
visualViewportOffsetTop: viewportOffsetTop,
visualViewportHeight: viewportHeight,
});
const atDocumentEnd = isAtDocumentEnd({
scrollY,
scrollHeight: scrollingElement.scrollHeight,
visualViewportHeight: viewportHeight,
});
const activeSectionId = selectActiveSection({
headings,
activationY,
atDocumentEnd,
});
const previousActiveIndex = canonicalIds.indexOf(previousActiveId);
const activeIndex = canonicalIds.indexOf(activeSectionId);
const crossedBoundaries = Math.abs(activeIndex - previousActiveIndex);
const deltaY = scrollY - previousScrollY;
const currentSign = snapshot.value.sign;
const signTargetId =
currentSign?.targetId ?? canonicalIds[activeIndex + 1] ?? null;
const signTarget = headings.find(
(heading) => heading.id === signTargetId,
);
const sign =
signTargetId === null || signTarget === undefined || viewportHeight <= 0
? null
: nextSign(currentSign, {
source: navigationState.value.source,
deltaY,
viewportHeight,
crossedBoundaries,
candidateId: signTargetId,
distanceVh: (signTarget.top - activationY) / viewportHeight,
motionAllowed: motionAllowed?.value ?? true,
});
const sectionState = deriveSectionState(activeSectionId);
snapshot.value = {
...drive.value,
routeProgress: atDocumentEnd ? 1 : drive.value.routeProgress,
...sectionState,
sign,
};
previousScrollY = scrollY;
previousActiveId = activeSectionId;
};
scheduleMeasurement = (): void => {
if (
!disposed &&
frameId === undefined &&
document.visibilityState !== "hidden"
) {
frameId = window.requestAnimationFrame(measure);
}
};
const resizeObserver = new ResizeObserver(scheduleMeasurement);
resizeObserver.observe(document.documentElement);
for (const id of canonicalIds) {
const section = document.getElementById(id);
const heading = document.getElementById(`${id}-heading`);
if (section !== null) resizeObserver.observe(section);
if (heading !== null) resizeObserver.observe(heading);
}
for (const media of document.querySelectorAll("img, video")) {
resizeObserver.observe(media);
}
const handleVisibility = (): void => {
if (document.visibilityState === "hidden") {
if (frameId !== undefined) {
window.cancelAnimationFrame(frameId);
frameId = undefined;
}
return;
}
previousScrollY = window.scrollY;
scheduleMeasurement();
};
window.addEventListener("scroll", scheduleMeasurement, PASSIVE_LISTENER);
window.addEventListener("resize", scheduleMeasurement, PASSIVE_LISTENER);
window.addEventListener(
"orientationchange",
scheduleMeasurement,
PASSIVE_LISTENER,
);
visualViewport?.addEventListener(
"resize",
scheduleMeasurement,
PASSIVE_LISTENER,
);
visualViewport?.addEventListener(
"scroll",
scheduleMeasurement,
PASSIVE_LISTENER,
);
document.addEventListener("load", scheduleMeasurement, true);
document.addEventListener("loadedmetadata", scheduleMeasurement, true);
document.addEventListener(
"visibilitychange",
handleVisibility,
PASSIVE_LISTENER,
);
scheduleMeasurement();
void document.fonts.ready.then(() => scheduleMeasurement());
teardown = (): void => {
disposed = true;
window.removeEventListener(
"scroll",
scheduleMeasurement,
PASSIVE_LISTENER,
);
window.removeEventListener(
"resize",
scheduleMeasurement,
PASSIVE_LISTENER,
);
window.removeEventListener(
"orientationchange",
scheduleMeasurement,
PASSIVE_LISTENER,
);
visualViewport?.removeEventListener(
"resize",
scheduleMeasurement,
PASSIVE_LISTENER,
);
visualViewport?.removeEventListener(
"scroll",
scheduleMeasurement,
PASSIVE_LISTENER,
);
document.removeEventListener("load", scheduleMeasurement, true);
document.removeEventListener("loadedmetadata", scheduleMeasurement, true);
document.removeEventListener(
"visibilitychange",
handleVisibility,
PASSIVE_LISTENER,
);
resizeObserver.disconnect();
if (frameId !== undefined) {
window.cancelAnimationFrame(frameId);
frameId = undefined;
}
};
});
onUnmounted(() => {
stopNavigationWatch();
stopMotionWatch();
teardown();
});
return readonly(snapshot);
}

View File

@@ -0,0 +1,142 @@
import { onMounted, onUnmounted, readonly, shallowRef, type Ref } from "vue";
import type { SectionId } from "@/content/types";
import {
canonicalSectionIdFromHash,
createNavigationController,
validateSectionAnchor,
type NavigationController,
type NavigationState,
} from "@/journey/navigation-controller";
const PASSIVE_LISTENER: AddEventListenerOptions = { passive: true };
const SCROLL_KEYS = new Set([
"PageUp",
"PageDown",
"Home",
"End",
" ",
"Spacebar",
"ArrowUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
]);
export const isScrollIntentKey = (key: string): boolean => SCROLL_KEYS.has(key);
const isEditableTarget = (target: EventTarget | null): boolean =>
target instanceof HTMLElement &&
(target.isContentEditable ||
target instanceof HTMLInputElement ||
target instanceof HTMLTextAreaElement ||
target instanceof HTMLSelectElement);
export interface KeyboardNavigation {
state: Readonly<Ref<NavigationState>>;
onSectionLinkClick(event: MouseEvent): void;
notePassiveSection(id: SectionId): void;
}
export function useKeyboardNavigation(
canonicalIds: readonly SectionId[],
): KeyboardNavigation {
const state = shallowRef<NavigationState>({
epoch: 0,
source: "initial",
destinationId: null,
});
let controller: NavigationController | undefined;
let teardown = (): void => {};
const restoreCurrentFragment = (
source: "initial" | "history-restoration",
): void => {
if (controller === undefined) return;
const id = canonicalSectionIdFromHash(window.location.hash, canonicalIds);
if (id === null) return;
const target = document.getElementById(id);
if (!(target instanceof HTMLElement)) return;
if (source === "initial") controller.initialize(id, target);
else controller.restore(id, target);
};
const onSectionLinkClick = (event: MouseEvent): void => {
if (
event.defaultPrevented ||
event.button !== 0 ||
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
controller === undefined ||
!(event.currentTarget instanceof HTMLAnchorElement)
) {
return;
}
const validated = validateSectionAnchor(event.currentTarget, canonicalIds);
if (validated === null) return;
event.preventDefault();
controller.navigate(validated.id, validated.target);
};
onMounted(() => {
controller = createNavigationController(canonicalIds);
const unsubscribe = controller.subscribe((nextState) => {
state.value = nextState;
});
const noteScrollIntent = (): void => {
controller?.noteUserScrollIntent();
};
const handleKeydown = (event: KeyboardEvent): void => {
if (
event.altKey ||
event.ctrlKey ||
event.metaKey ||
event.shiftKey ||
isEditableTarget(event.target) ||
!isScrollIntentKey(event.key)
) {
return;
}
noteScrollIntent();
};
const handlePopstate = (): void =>
restoreCurrentFragment("history-restoration");
const handlePageshow = (event: PageTransitionEvent): void => {
if (event.persisted) restoreCurrentFragment("history-restoration");
};
window.addEventListener("wheel", noteScrollIntent, PASSIVE_LISTENER);
window.addEventListener("touchmove", noteScrollIntent, PASSIVE_LISTENER);
window.addEventListener("keydown", handleKeydown);
window.addEventListener("popstate", handlePopstate);
window.addEventListener("pageshow", handlePageshow);
if (window.location.hash !== "") restoreCurrentFragment("initial");
teardown = (): void => {
window.removeEventListener("wheel", noteScrollIntent, PASSIVE_LISTENER);
window.removeEventListener(
"touchmove",
noteScrollIntent,
PASSIVE_LISTENER,
);
window.removeEventListener("keydown", handleKeydown);
window.removeEventListener("popstate", handlePopstate);
window.removeEventListener("pageshow", handlePageshow);
unsubscribe();
controller?.dispose();
controller = undefined;
};
});
onUnmounted(() => teardown());
return {
state: readonly(state),
onSectionLinkClick,
notePassiveSection(id) {
controller?.notePassiveSection(id);
},
};
}