feat: bilingual support (FA/EN), IRANSans typography, RTL layout, and interactive product detail pages

This commit is contained in:
s.esmaeili
2026-10-04 07:11:52 +03:30
commit a001fa5d5f
302 changed files with 35491 additions and 0 deletions
@@ -0,0 +1,109 @@
import { useEffect, useState } from "react";
import { useDeckContext } from "../core/deckContext";
import { useLocalization } from "../core/localization";
import type { SlideDefinition } from "../core/Slide";
import { ControlButton } from "./ControlButton";
import { ControlIcon } from "./ControlIcon";
import { PresentationInteractionSurface } from "./PresentationInteractionLayer";
import type { PresentationInteractionController } from "./presentationInteraction";
import { SlideStage } from "./SlideStage";
export function AudiencePresentation({
controller,
fullscreen,
slides,
onClose,
onToggleFullscreen,
}: {
controller: PresentationInteractionController;
fullscreen: boolean;
slides: SlideDefinition[];
onClose: () => void;
onToggleFullscreen: () => void;
}) {
const deck = useDeckContext();
const messages = useLocalization();
const controlsVisible = useAutoHidingControls();
const previousDisabled = deck.slideIndex === 0 && deck.revealedCount === 0;
const nextDisabled =
deck.slideIndex === deck.slideCount - 1 &&
deck.revealedCount >= (deck.stepCounts[deck.slideIndex] ?? 0);
return (
<section
className="slide-kit-presentation"
data-controls-visible={controlsVisible ? "true" : "false"}
aria-label={messages.presentation}
>
<PresentationInteractionSurface
className="slide-kit-presentation-surface"
controller={controller}
expandedImageLabel={messages.expandedImage}
modalImageFocus
slideIndex={deck.slideIndex}
>
<SlideStage slides={slides} flat />
<nav
className="slide-kit-presentation-controls"
data-presentation-regular-cursor
aria-label={messages.presentationControls}
>
<div className="slide-kit-control-pill slide-kit-presentation-navigation">
<ControlButton
iconOnly
aria-label={messages.previous}
disabled={previousDisabled}
onClick={deck.previous}
>
<ControlIcon name="previous" />
</ControlButton>
<span aria-label={messages.slidePosition}>
{deck.slideIndex + 1} / {deck.slideCount}
</span>
<ControlButton
iconOnly
aria-label={messages.next}
disabled={nextDisabled}
onClick={deck.next}
>
<ControlIcon name="next" />
</ControlButton>
</div>
<ControlButton
iconOnly
variant="primary"
className="slide-kit-presentation-mode-action"
aria-label={fullscreen ? messages.close : messages.enterFullscreen}
title={fullscreen ? messages.close : messages.enterFullscreen}
onClick={fullscreen ? onClose : onToggleFullscreen}
>
<ControlIcon name={fullscreen ? "close" : "fullscreen"} />
</ControlButton>
</nav>
</PresentationInteractionSurface>
</section>
);
}
function useAutoHidingControls(): boolean {
const [visible, setVisible] = useState(true);
useEffect(() => {
let timeout: number | undefined;
const showControls = () => {
setVisible(true);
window.clearTimeout(timeout);
timeout = window.setTimeout(() => setVisible(false), 2_000);
};
showControls();
window.addEventListener("pointermove", showControls);
window.addEventListener("touchstart", showControls);
return () => {
window.clearTimeout(timeout);
window.removeEventListener("pointermove", showControls);
window.removeEventListener("touchstart", showControls);
};
}, []);
return visible;
}
+140
View File
@@ -0,0 +1,140 @@
import {
type CSSProperties,
type ReactNode,
useId,
useLayoutEffect,
useRef,
} from "react";
import { LayoutGroup } from "motion/react";
import { getOwnerWindow } from "../core/domEnvironment";
export const CANVAS_WIDTH = 1920;
export const CANVAS_HEIGHT = 1080;
interface CanvasScalerProps {
children: ReactNode;
className?: string;
fit?: "contain" | "cover";
frameClassName?: string;
staticCanvas?: boolean;
surface: string;
}
export function CanvasScaler({
children,
className,
fit = "contain",
frameClassName,
staticCanvas = false,
surface,
}: CanvasScalerProps) {
const containerRef = useRef<HTMLDivElement | null>(null);
const frameRef = useRef<HTMLDivElement | null>(null);
const canvasRef = useRef<HTMLDivElement | null>(null);
const scaleRef = useRef<number | null>(staticCanvas ? 1 : null);
const layoutScopeId = useId().replace(/:/g, "");
useLayoutEffect(() => {
const element = containerRef.current;
const frame = frameRef.current;
const canvas = canvasRef.current;
if (!element || !frame || !canvas) {
return;
}
const applyScale = () => {
const scale = scaleRef.current;
frame.style.width = `${CANVAS_WIDTH * (scale ?? 1)}px`;
frame.style.height = `${CANVAS_HEIGHT * (scale ?? 1)}px`;
frame.style.visibility = scale === null ? "hidden" : "visible";
canvas.style.transform = `scale(${scale ?? 1})`;
};
if (staticCanvas) {
applyScale();
return;
}
const measure = () => {
const { clientHeight: height, clientWidth: width } = element;
if (width > 0 && height > 0) {
scaleRef.current =
fit === "cover"
? Math.max(width / CANVAS_WIDTH, height / CANVAS_HEIGHT)
: Math.min(width / CANVAS_WIDTH, height / CANVAS_HEIGHT);
applyScale();
}
};
measure();
const ownerWindow = getOwnerWindow(element);
const observer = new ownerWindow.ResizeObserver(measure);
observer.observe(element);
return () => observer.disconnect();
}, [fit, staticCanvas]);
useLayoutEffect(() => {
const container = containerRef.current;
if (!container) {
return;
}
const mirrorsSlideBackground = surface === "presentation";
if (!mirrorsSlideBackground) {
container.style.removeProperty("background-color");
return;
}
const slide = container.querySelector<HTMLElement>(".slide-kit-slide");
if (!slide) {
return;
}
container.style.backgroundColor =
getOwnerWindow(slide).getComputedStyle(slide).backgroundColor;
});
// applyScale owns frame size, visibility and canvas scale; nothing scale-dependent belongs in these styles.
const frameStyle: CSSProperties = staticCanvas
? {
width: CANVAS_WIDTH,
height: CANVAS_HEIGHT,
}
: {
position: "absolute",
inset: 0,
margin: "auto",
width: CANVAS_WIDTH,
height: CANVAS_HEIGHT,
visibility: "hidden",
zIndex: 1,
};
return (
<div
ref={containerRef}
className={className}
data-slide-canvas-container
data-slide-surface={surface}
>
<div
ref={frameRef}
className={`slide-kit-canvas-geometry ${frameClassName ?? ""}`.trim()}
style={frameStyle}
>
<div
ref={canvasRef}
data-slide-canvas
style={{
width: CANVAS_WIDTH,
height: CANVAS_HEIGHT,
transformOrigin: "top left",
position: "relative",
zIndex: 1,
}}
>
<LayoutGroup id={`${surface}-${layoutScopeId}`}>
{children}
</LayoutGroup>
</div>
</div>
</div>
);
}
+23
View File
@@ -0,0 +1,23 @@
import type { SlideDefinition } from "../core/Slide";
import { useLocalization } from "../core/localization";
import { CanvasScaler } from "./CanvasScaler";
import { SlideFrame } from "./SlideFrame";
export function CompactPreview({ slide }: { slide: SlideDefinition }) {
const messages = useLocalization();
return (
<main
className="slide-kit-compact-preview"
aria-label={messages.slidePreview}
>
<CanvasScaler surface="compact-preview">
<SlideFrame
definition={slide}
slideIndex={0}
revealedCount={Number.MAX_SAFE_INTEGER}
surface="preview"
/>
</CanvasScaler>
</main>
);
}
+26
View File
@@ -0,0 +1,26 @@
import type { ButtonHTMLAttributes } from "react";
type ControlButtonVariant = "ghost" | "menu" | "primary";
interface ControlButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
iconOnly?: boolean;
variant?: ControlButtonVariant;
}
export function ControlButton({
className,
iconOnly = false,
type = "button",
variant = "ghost",
...props
}: ControlButtonProps) {
return (
<button
{...props}
type={type}
className={`slide-kit-button ${className ?? ""}`.trim()}
data-icon-only={iconOnly ? "true" : undefined}
data-variant={variant}
/>
);
}
+76
View File
@@ -0,0 +1,76 @@
import type { ReactNode } from "react";
type ControlIconName =
| "close"
| "download"
| "file-pdf"
| "file-pptx"
| "fullscreen"
| "grid"
| "next"
| "panel-left-close"
| "panel-left-open"
| "play"
| "presenter"
| "previous";
const iconContents: Record<ControlIconName, ReactNode> = {
close: <path d="M6 6l8 8M14 6l-8 8" />,
download: <path d="M10 3v9m0 0 3.5-3.5M10 12 6.5 8.5M4 16h12" />,
"file-pdf": (
<>
<path d="M5 2.5h6l4 4v11H5v-15Z" />
<path d="M11 2.5v4h4M7.5 10.5h5M7.5 13.5h4" />
</>
),
"file-pptx": (
<>
<rect x="3" y="3" width="14" height="11" rx="2" />
<path d="M10 5.2v3.3h3.3M10 5.2a3.3 3.3 0 1 0 3.3 3.3M7 17h6M10 14v3" />
</>
),
fullscreen: <path d="M8 8 4 4m0 0v3m0-3h3M12 12l4 4m0 0v-3m0 3h-3" />,
grid: (
<>
<rect x="3" y="3" width="5" height="5" rx="1" />
<rect x="12" y="3" width="5" height="5" rx="1" />
<rect x="3" y="12" width="5" height="5" rx="1" />
<rect x="12" y="12" width="5" height="5" rx="1" />
</>
),
next: <path d="M7.5 5l5 5-5 5" />,
"panel-left-close": panelLeftIcon({ sidebarVisible: true }),
"panel-left-open": panelLeftIcon({ sidebarVisible: false }),
play: <path d="M7 5.5v9l7-4.5-7-4.5Z" />,
presenter: (
<>
<rect x="3" y="4" width="14" height="10" rx="2" />
<path d="M7 17h6M10 14v3" />
</>
),
previous: <path d="M12.5 5 7.5 10l5 5" />,
};
function panelLeftIcon({ sidebarVisible }: { sidebarVisible: boolean }) {
return (
<>
<rect x="2.5" y="3" width="15" height="14" rx="2" />
<path d="M7 3v14" />
<path
data-panel-fill=""
d="M4.5 3H7v14H4.5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2Z"
fill="currentColor"
fillOpacity={sidebarVisible ? 1 : 0}
stroke="none"
/>
</>
);
}
export function ControlIcon({ name }: { name: ControlIconName }) {
return (
<svg viewBox="0 0 20 20" data-icon={name} aria-hidden="true">
{iconContents[name]}
</svg>
);
}
@@ -0,0 +1,140 @@
import { useEffect, useRef, useState } from "react";
import type { DeckDownloadFormat } from "../download/deckDownloads";
import { useLocalization } from "../core/localization";
import { ControlButton } from "./ControlButton";
import { ControlIcon } from "./ControlIcon";
interface FloatingDeckControlsProps {
downloadFormat: DeckDownloadFormat | null;
onDownload: (format: DeckDownloadFormat) => void;
onPresent: () => void;
onPresenter: () => void;
}
export function FloatingDeckControls({
downloadFormat,
onDownload,
onPresent,
onPresenter,
}: FloatingDeckControlsProps) {
const messages = useLocalization();
const controlsRef = useRef<HTMLDivElement | null>(null);
const [menuOpen, setMenuOpen] = useState(false);
useEffect(() => {
if (!menuOpen) {
return;
}
const closeFromOutside = (event: PointerEvent) => {
if (!controlsRef.current?.contains(event.target as Node)) {
setMenuOpen(false);
}
};
const closeFromKeyboard = (event: KeyboardEvent) => {
if (event.key === "Escape") {
setMenuOpen(false);
}
};
document.addEventListener("pointerdown", closeFromOutside);
window.addEventListener("keydown", closeFromKeyboard);
return () => {
document.removeEventListener("pointerdown", closeFromOutside);
window.removeEventListener("keydown", closeFromKeyboard);
};
}, [menuOpen]);
const runMenuAction = (action: () => void) => {
setMenuOpen(false);
action();
};
return (
<div ref={controlsRef} className="slide-kit-viewer-controls">
<div className="slide-kit-control-cluster">
{menuOpen ? (
<div
className="slide-kit-overflow-menu"
role="menu"
aria-label={messages.download}
>
<ControlButton
variant="menu"
role="menuitem"
disabled={downloadFormat !== null}
onClick={() => runMenuAction(() => onDownload("pdf"))}
>
<span className="slide-kit-format-icon" data-format="pdf">
<ControlIcon name="file-pdf" />
</span>
<span className="slide-kit-format-copy">
<strong>
{downloadFormat === "pdf"
? messages.preparingDownload
: messages.pdfDocument}
</strong>
<small>.pdf</small>
</span>
</ControlButton>
<ControlButton
variant="menu"
role="menuitem"
disabled={downloadFormat !== null}
onClick={() => runMenuAction(() => onDownload("pptx"))}
>
<span className="slide-kit-format-icon" data-format="pptx">
<ControlIcon name="file-pptx" />
</span>
<span className="slide-kit-format-copy">
<strong>
{downloadFormat === "pptx"
? messages.preparingDownload
: messages.powerPoint}
</strong>
<small>.pptx</small>
</span>
</ControlButton>
</div>
) : null}
<nav
className="slide-kit-control-pill"
aria-label={messages.presentationControls}
>
<ControlButton
iconOnly
aria-label={messages.download}
aria-expanded={menuOpen}
onClick={() => setMenuOpen((open) => !open)}
>
<ControlIcon name="download" />
</ControlButton>
<span className="slide-kit-control-divider" aria-hidden="true" />
<ControlButton
className="slide-kit-presenter-action"
aria-label={messages.presenterView}
title={messages.presenterView}
onClick={onPresenter}
>
<ControlIcon name="presenter" />
<span className="slide-kit-presenter-action-label">
{messages.presenter}
</span>
</ControlButton>
</nav>
</div>
<ControlButton
variant="primary"
className="slide-kit-present-fab"
aria-label={messages.startPresentation}
title={messages.startPresentation}
onClick={onPresent}
>
<ControlIcon name="play" />
<span className="slide-kit-present-label">
{messages.startPresentation}
</span>
</ControlButton>
</div>
);
}
+102
View File
@@ -0,0 +1,102 @@
import { useLayoutEffect, useRef, useState } from "react";
import { MotionConfig } from "motion/react";
import type { SlideDefinition } from "../core/Slide";
import { CANVAS_HEIGHT, CANVAS_WIDTH, CanvasScaler } from "./CanvasScaler";
import { SlideFrame } from "./SlideFrame";
const GRID_GAP = 16;
const GRID_PADDING = 20;
const CAPTION_HEIGHT = 24;
interface GridLayout {
cellWidth: number;
columns: number;
}
/** A numbered contact sheet of every slide, sized so the whole deck fits the viewport. */
export function GridDeck({ slides }: { slides: SlideDefinition[] }) {
const rootRef = useRef<HTMLDivElement | null>(null);
const [layout, setLayout] = useState<GridLayout | null>(null);
useLayoutEffect(() => {
const element = rootRef.current;
/* istanbul ignore if -- React assigns the grid root before layout effects. */
if (!element) {
return;
}
const measure = () => {
const { clientHeight, clientWidth } = element;
if (clientWidth > 0 && clientHeight > 0) {
setLayout(computeGridLayout(clientWidth, clientHeight, slides.length));
}
};
measure();
const observer = new ResizeObserver(measure);
observer.observe(element);
return () => observer.disconnect();
}, [slides.length]);
return (
<MotionConfig reducedMotion="always">
<div ref={rootRef} className="slide-kit-grid" data-slide-grid-root>
{layout ? (
<div
className="slide-kit-grid-sheet"
style={{
gridTemplateColumns: `repeat(${layout.columns}, ${layout.cellWidth}px)`,
}}
>
{slides.map((slide, index) => (
<figure
key={slide.id}
className="slide-kit-grid-cell"
data-slide-grid-cell={index + 1}
>
<span
className="slide-kit-grid-frame"
style={{
width: layout.cellWidth,
height: (layout.cellWidth * CANVAS_HEIGHT) / CANVAS_WIDTH,
}}
>
<CanvasScaler surface="grid">
<SlideFrame
definition={slide}
slideIndex={index}
revealedCount={Number.MAX_SAFE_INTEGER}
surface="preview"
/>
</CanvasScaler>
</span>
<figcaption aria-hidden="true">{index + 1}</figcaption>
</figure>
))}
</div>
) : null}
</div>
</MotionConfig>
);
}
/** The column count that gives the largest cells whose rows still fit the container. */
function computeGridLayout(
width: number,
height: number,
count: number,
): GridLayout {
let best: GridLayout = { cellWidth: 1, columns: 1 };
for (let columns = 1; columns <= count; columns += 1) {
const rows = Math.ceil(count / columns);
const widthBound =
(width - 2 * GRID_PADDING - GRID_GAP * (columns - 1)) / columns;
const rowHeight =
(height - 2 * GRID_PADDING - GRID_GAP * (rows - 1)) / rows;
const heightBound =
((rowHeight - CAPTION_HEIGHT) * CANVAS_WIDTH) / CANVAS_HEIGHT;
const cellWidth = Math.min(widthBound, heightBound);
if (cellWidth > best.cellWidth) {
best = { cellWidth, columns };
}
}
return best;
}
@@ -0,0 +1,596 @@
import {
type HTMLAttributes,
type MouseEvent as ReactMouseEvent,
type PointerEvent as ReactPointerEvent,
type ReactNode,
type RefObject,
useCallback,
useEffect,
useLayoutEffect,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { CursorArrow } from "@kits/sync";
import { AnimatePresence, motion, MotionConfig } from "motion/react";
import { getOwnerWindow } from "../core/domEnvironment";
import { CANVAS_WIDTH } from "./CanvasScaler";
import {
createPresentationInteractionController,
getZoomableImage,
inspectPresentationPoint,
type NormalizedPoint,
type PresentationInteractionAction,
type PresentationInteractionController,
type PresentationInteractionSnapshot,
} from "./presentationInteraction";
const PRESENTATION_CURSOR_SCALE = 0.92;
interface PresentationInteractionSurfaceProps extends Omit<
HTMLAttributes<HTMLDivElement>,
| "children"
| "onClickCapture"
| "onDragStartCapture"
| "onPointerDownCapture"
| "onPointerLeave"
| "onPointerMove"
> {
children: ReactNode;
className: string;
controller: PresentationInteractionController;
expandedImageLabel: string;
modalImageFocus?: boolean;
slideIndex: number;
}
export function PresentationInteractionSurface({
children,
className,
controller,
expandedImageLabel,
modalImageFocus = false,
slideIndex,
...props
}: PresentationInteractionSurfaceProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
const focusBeforeImageRef = useRef<HTMLElement | null>(null);
const imageWasFocusedRef = useRef(false);
const pointerInsideRef = useRef(false);
const snapshot = useSyncExternalStore(
controller.subscribe,
controller.getSnapshot,
controller.getSnapshot,
);
const focusedImage =
snapshot.focusedImage?.slideIndex === slideIndex
? snapshot.focusedImage
: null;
const apply = useCallback(
(action: PresentationInteractionAction) => {
controller.dispatch(action);
},
[controller],
);
const leave = useCallback(() => {
if (!pointerInsideRef.current) {
return;
}
pointerInsideRef.current = false;
apply({ type: "leave" });
}, [apply]);
const onPointerMove = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
const root = rootRef.current;
/* istanbul ignore if -- React assigns the interaction root before pointer events. */
if (!root) {
return;
}
if (
event.target instanceof getOwnerWindow(root).Element &&
event.target.closest("[data-presentation-regular-cursor]")
) {
leave();
return;
}
/* istanbul ignore if -- Touch behavior runs in the dedicated touch browser project. */
if (event.pointerType === "touch") {
return;
}
const inspected = inspectPresentationPoint(
root,
event.clientX,
event.clientY,
slideIndex,
);
if (!inspected) {
leave();
return;
}
pointerInsideRef.current = true;
apply(
focusedImage
? { ...inspected.move, cursor: "pointer" }
: inspected.move,
);
},
[apply, focusedImage, leave, slideIndex],
);
const onClickCapture = useCallback(
(event: ReactMouseEvent<HTMLDivElement>) => {
if (event.button !== 0 || focusedImage) {
return;
}
const root = rootRef.current;
/* istanbul ignore if -- React assigns the interaction root before click events. */
if (!root) {
return;
}
const inspected = inspectPresentationPoint(
root,
event.clientX,
event.clientY,
slideIndex,
);
if (
inspected?.imageIndex !== null &&
inspected?.imageIndex !== undefined
) {
event.preventDefault();
event.stopPropagation();
apply({
type: "openImage",
slideIndex,
imageIndex: inspected.imageIndex,
});
}
},
[apply, focusedImage, slideIndex],
);
const onPointerDownCapture = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0 || focusedImage) {
return;
}
const root = rootRef.current;
/* istanbul ignore if -- React assigns the interaction root before pointer events. */
if (!root) {
return;
}
const inspected = inspectPresentationPoint(
root,
event.clientX,
event.clientY,
slideIndex,
);
if (
inspected?.imageIndex !== null &&
inspected?.imageIndex !== undefined
) {
focusBeforeImageRef.current = root.ownerDocument
.activeElement as HTMLElement | null;
}
},
[focusedImage, slideIndex],
);
const closeImage = useCallback(() => {
apply({ type: "closeImage" });
}, [apply]);
useEffect(() => {
const action: PresentationInteractionAction = { type: "reset" };
controller.dispatch(action);
pointerInsideRef.current = false;
}, [controller, slideIndex]);
useEffect(() => {
const content = contentRef.current;
if (!content || !modalImageFocus) {
return;
}
content.inert = Boolean(focusedImage);
return () => {
content.inert = false;
};
}, [focusedImage, modalImageFocus]);
useEffect(() => {
if (focusedImage) {
imageWasFocusedRef.current = true;
return;
}
if (!imageWasFocusedRef.current || !modalImageFocus) {
return;
}
imageWasFocusedRef.current = false;
const root = rootRef.current;
if (!root) {
return;
}
const ownerWindow = getOwnerWindow(root);
const animationFrame = ownerWindow.requestAnimationFrame(() =>
focusBeforeImageRef.current?.focus(),
);
return () => ownerWindow.cancelAnimationFrame(animationFrame);
}, [focusedImage, modalImageFocus]);
useEffect(() => {
if (!focusedImage) {
return;
}
const closeFromKeyboard = (event: KeyboardEvent) => {
if (event.key !== "Escape") {
return;
}
event.preventDefault();
event.stopImmediatePropagation();
closeImage();
};
const root = rootRef.current;
if (!root) {
return;
}
const ownerWindow = getOwnerWindow(root);
ownerWindow.addEventListener("keydown", closeFromKeyboard, true);
return () =>
ownerWindow.removeEventListener("keydown", closeFromKeyboard, true);
}, [closeImage, focusedImage]);
return (
<div
{...props}
ref={rootRef}
className={`slide-kit-presentation-interaction ${className}`}
data-image-focused={focusedImage ? "true" : "false"}
onClickCapture={onClickCapture}
onDragStartCapture={(event) => {
if (
event.target instanceof getOwnerWindow(event.currentTarget).Element &&
event.target.closest("[data-slide-canvas]")
) {
event.preventDefault();
}
}}
onPointerDownCapture={onPointerDownCapture}
onPointerLeave={leave}
onPointerMove={onPointerMove}
>
<div
ref={contentRef}
className="slide-kit-presentation-interaction-content"
aria-hidden={modalImageFocus && focusedImage ? "true" : undefined}
>
{children}
</div>
<MotionConfig reducedMotion="user">
<AnimatePresence>
{focusedImage ? (
<FocusedImageOverlay
key={`${focusedImage.slideIndex}-${focusedImage.imageIndex}`}
expandedImageLabel={expandedImageLabel}
imageIndex={focusedImage.imageIndex}
modal={modalImageFocus}
onClose={closeImage}
rootRef={rootRef}
/>
) : null}
</AnimatePresence>
</MotionConfig>
<PresentationCursor
rootRef={rootRef}
slideIndex={slideIndex}
snapshot={snapshot}
/>
</div>
);
}
export function usePresentationInteractionController(): PresentationInteractionController {
const [controller] = useState(createPresentationInteractionController);
useEffect(() => () => controller.destroy(), [controller]);
return controller;
}
function PresentationCursor({
rootRef,
slideIndex,
snapshot,
}: {
rootRef: RefObject<HTMLElement | null>;
slideIndex: number;
snapshot: PresentationInteractionSnapshot;
}) {
const cursor =
snapshot.cursor?.slideIndex === slideIndex ? snapshot.cursor : null;
const lastCursorRef = useRef(cursor);
if (cursor) {
lastCursorRef.current = cursor;
}
const renderedCursor = cursor ?? lastCursorRef.current;
const position = useCanvasPosition(rootRef, renderedCursor?.point ?? null);
const magnifier = renderedCursor?.kind === "magnifier";
// The arrow's tip is its top-left corner; the magnifier is centred on the point.
const centre = magnifier ? -34 : 0;
return (
<span
className="slide-kit-presentation-cursor"
data-cursor-kind={renderedCursor?.kind}
data-visible={cursor && position ? "true" : "false"}
style={
position
? {
transform: `translate3d(${position.x}px, ${position.y}px, 0) scale(${position.scale * PRESENTATION_CURSOR_SCALE}) translate(${centre}px, ${centre}px)`,
}
: undefined
}
aria-hidden="true"
>
{magnifier ? (
<svg viewBox="0 0 84 84" focusable="false">
<path className="slide-kit-cursor-handle" d="m51 51 23 23" />
<circle cx="34" cy="34" r="24" />
<path className="slide-kit-cursor-plus" d="M34 21v26M21 34h26" />
</svg>
) : (
<CursorArrow />
)}
</span>
);
}
interface ImageGeometry {
alt: string;
authorHeight: number;
authorWidth: number;
sourceImage: HTMLImageElement;
sourceScale: number;
sourceX: number;
sourceY: number;
targetScale: number;
targetX: number;
targetY: number;
}
function FocusedImageOverlay({
expandedImageLabel,
imageIndex,
modal,
onClose,
rootRef,
}: {
expandedImageLabel: string;
imageIndex: number;
modal: boolean;
onClose: () => void;
rootRef: RefObject<HTMLElement | null>;
}) {
const cloneHostRef = useRef<HTMLDivElement | null>(null);
const overlayRef = useRef<HTMLDivElement | null>(null);
const [geometry, setGeometry] = useState<ImageGeometry | null>(null);
useLayoutEffect(() => {
const root = rootRef.current;
/* istanbul ignore if -- React assigns the overlay root before layout effects. */
if (!root) {
return;
}
const measure = () => {
const image = getZoomableImage(root, imageIndex);
/* istanbul ignore if -- Authored slide structure remains stable while presented. */
if (!image) {
onClose();
return;
}
const rootRect = root.getBoundingClientRect();
const canvas = root.querySelector<HTMLElement>("[data-slide-canvas]");
/* istanbul ignore if -- Interaction surfaces always render a CanvasScaler. */
if (!canvas) {
onClose();
return;
}
const canvasRect = canvas.getBoundingClientRect();
const imageRect = image.getBoundingClientRect();
/* istanbul ignore if -- Focus can only open from a rendered image hit target. */
if (imageRect.width <= 0 || imageRect.height <= 0) {
onClose();
return;
}
const sourceScale = canvasRect.width / CANVAS_WIDTH;
const authorWidth = image.offsetWidth;
const authorHeight = image.offsetHeight;
/* istanbul ignore if -- A rendered image has nonzero author dimensions. */
if (authorWidth <= 0 || authorHeight <= 0) {
onClose();
return;
}
const targetScale = Math.min(
(rootRect.width * 0.86) / authorWidth,
(rootRect.height * 0.84) / authorHeight,
);
const targetWidth = authorWidth * targetScale;
const targetHeight = authorHeight * targetScale;
setGeometry({
alt: image.alt,
authorHeight,
authorWidth,
sourceImage: image,
sourceScale,
sourceX: imageRect.left - rootRect.left,
sourceY: imageRect.top - rootRect.top,
targetScale,
targetX: (rootRect.width - targetWidth) / 2,
targetY: (rootRect.height - targetHeight) / 2,
});
};
measure();
const ownerWindow = getOwnerWindow(root);
const observer = new ownerWindow.ResizeObserver(measure);
observer.observe(root);
return () => observer.disconnect();
}, [imageIndex, onClose, rootRef]);
useLayoutEffect(() => {
const host = cloneHostRef.current;
if (!host || !geometry) {
return;
}
const clone = createVisualImageClone(
geometry.sourceImage,
geometry.authorWidth,
geometry.authorHeight,
);
host.replaceChildren(clone);
return () => clone.remove();
}, [geometry]);
useEffect(() => {
if (!modal || !geometry) {
return;
}
overlayRef.current?.focus();
}, [geometry, modal]);
if (!geometry) {
return null;
}
return (
<motion.div
ref={overlayRef}
className="slide-kit-focused-image-overlay"
data-focused-image
role={modal ? "dialog" : undefined}
aria-hidden={modal ? undefined : "true"}
aria-label={modal ? geometry.alt || expandedImageLabel : undefined}
aria-modal={modal ? "true" : undefined}
tabIndex={modal ? -1 : undefined}
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
onClick={(event) => {
event.stopPropagation();
onClose();
}}
>
<motion.div
className="slide-kit-focused-image"
data-expanded-image-container
initial={{
x: geometry.sourceX,
y: geometry.sourceY,
scale: geometry.sourceScale,
}}
animate={{
x: geometry.targetX,
y: geometry.targetY,
scale: geometry.targetScale,
}}
exit={{
x: geometry.sourceX,
y: geometry.sourceY,
scale: geometry.sourceScale,
}}
transition={{ duration: 0.38, ease: [0.22, 1, 0.36, 1] }}
style={{
width: geometry.authorWidth,
height: geometry.authorHeight,
}}
>
<div ref={cloneHostRef} className="slide-kit-focused-image-host" />
</motion.div>
</motion.div>
);
}
function createVisualImageClone(
image: HTMLImageElement,
width: number,
height: number,
): HTMLImageElement {
const clone = image.cloneNode(false) as HTMLImageElement;
const computedStyle = getOwnerWindow(image).getComputedStyle(image);
clone.removeAttribute("class");
clone.removeAttribute("id");
clone.removeAttribute("sizes");
clone.removeAttribute("srcset");
clone.src = image.currentSrc || image.src;
clone.alt = "";
clone.ariaHidden = "true";
clone.draggable = false;
clone.setAttribute("data-expanded-image", "");
for (let index = 0; index < computedStyle.length; index += 1) {
const property = computedStyle.item(index);
clone.style.setProperty(
property,
computedStyle.getPropertyValue(property),
"important",
);
}
const layoutOverrides: Record<string, string> = {
display: "block",
height: `${height}px`,
inset: "auto",
margin: "0",
"max-height": "none",
"max-width": "none",
"min-height": "0",
"min-width": "0",
"pointer-events": "none",
position: "static",
transform: "none",
width: `${width}px`,
};
for (const [property, value] of Object.entries(layoutOverrides)) {
clone.style.setProperty(property, value, "important");
}
return clone;
}
function useCanvasPosition(
rootRef: RefObject<HTMLElement | null>,
point: NormalizedPoint | null,
): { scale: number; x: number; y: number } | null {
const [position, setPosition] = useState<{
scale: number;
x: number;
y: number;
} | null>(null);
useLayoutEffect(() => {
const root = rootRef.current;
if (!root || !point) {
return;
}
const canvas = root.querySelector<HTMLElement>("[data-slide-canvas]");
/* istanbul ignore if -- Interaction surfaces always render a CanvasScaler. */
if (!canvas) {
return;
}
const measure = () => {
const rootRect = root.getBoundingClientRect();
const canvasRect = canvas.getBoundingClientRect();
setPosition({
scale: canvasRect.width / CANVAS_WIDTH,
x: canvasRect.left - rootRect.left + canvasRect.width * point.x,
y: canvasRect.top - rootRect.top + canvasRect.height * point.y,
});
};
measure();
const ownerWindow = getOwnerWindow(root);
const observer = new ownerWindow.ResizeObserver(measure);
observer.observe(root);
return () => observer.disconnect();
}, [point, rootRef]);
return position;
}
+85
View File
@@ -0,0 +1,85 @@
import { type HTMLAttributes, useLayoutEffect, useRef } from "react";
import { MotionConfig } from "motion/react";
import { SlidePositionProvider, useDeckContext } from "../core/deckContext";
import { useLocalization } from "../core/localization";
import type { SlideDefinition } from "../core/Slide";
import { StepRegistry, type StepMode } from "../core/Step";
type SlideFrameSurface =
| "stage"
| "thumbnail"
| "preview"
| "presenter"
| "static";
interface SlideFrameProps {
definition: SlideDefinition;
slideIndex: number;
revealedCount: number;
surface: SlideFrameSurface;
onStepCountChange?: (stepCount: number) => void;
}
export function SlideFrame({
definition,
slideIndex,
revealedCount,
surface,
onStepCountChange,
}: SlideFrameProps) {
const deck = useDeckContext();
const messages = useLocalization();
const rootRef = useRef<HTMLDivElement | null>(null);
const stepMode = resolveStepMode(surface);
const inactive =
surface !== "stage" && surface !== "preview" && surface !== "static";
useLayoutEffect(() => {
/* istanbul ignore else -- React assigns the slide host before layout effects. */
if (rootRef.current) {
rootRef.current.inert = inactive;
}
}, [inactive]);
const inertProps = inactive
? ({ "aria-hidden": true } satisfies HTMLAttributes<HTMLDivElement>)
: {};
return (
<SlidePositionProvider slideIndex={slideIndex}>
<MotionConfig skipAnimations={stepMode !== "interactive"}>
<StepRegistry
mode={stepMode}
revealedCount={revealedCount}
onStepCountChange={onStepCountChange}
>
<div
{...inertProps}
ref={rootRef}
role="group"
aria-label={messages.slideLabel(slideIndex + 1, deck.slideCount)}
aria-current={surface === "stage" ? "page" : undefined}
className={`slide-kit-slide ${definition.className ?? ""}`.trim()}
data-slide-number={slideIndex + 1}
style={definition.style}
>
{definition.content}
</div>
</StepRegistry>
</MotionConfig>
</SlidePositionProvider>
);
}
function resolveStepMode(surface: SlideFrameSurface): StepMode {
switch (surface) {
case "stage":
case "presenter":
return "interactive";
case "preview":
return "controlled";
case "thumbnail":
case "static":
return "static";
}
}
+47
View File
@@ -0,0 +1,47 @@
import { useRef } from "react";
import { MotionConfig } from "motion/react";
import type { SlideDefinition } from "../core/Slide";
import { CanvasScaler } from "./CanvasScaler";
import { SlideFrame } from "./SlideFrame";
import { useStaticReadiness } from "./useStaticReadiness";
export function SlidePreview({
slides,
requestedPage,
}: {
slides: SlideDefinition[];
requestedPage: string;
}) {
const rootRef = useRef<HTMLDivElement | null>(null);
const parsedPage = Number(requestedPage);
const slideIndex =
Number.isInteger(parsedPage) &&
parsedPage >= 1 &&
parsedPage <= slides.length
? parsedPage - 1
: 0;
const slide = slides[slideIndex]!;
useStaticReadiness(rootRef, slide.staticAssets);
return (
<MotionConfig reducedMotion="always">
<div
ref={rootRef}
id={`slide-preview-${slideIndex + 1}`}
className="slide-kit-preview"
data-slide-kit-readiness="pending"
data-slide-preview-page={slideIndex + 1}
data-slide-preview-root
>
<CanvasScaler surface="preview">
<SlideFrame
definition={slide}
slideIndex={slideIndex}
revealedCount={Number.MAX_SAFE_INTEGER}
surface="preview"
/>
</CanvasScaler>
</div>
</MotionConfig>
);
}
@@ -0,0 +1,41 @@
import { useDeckContext } from "../core/deckContext";
import { useLocalization } from "../core/localization";
import type { SlideDefinition } from "../core/Slide";
import { SlideViewers } from "./SlideViewers";
export function SlideProgressRail({
slides,
visible,
}: {
slides: SlideDefinition[];
visible: boolean;
}) {
const deck = useDeckContext();
const messages = useLocalization();
return (
<nav
className="slide-kit-progress-rail"
aria-hidden={visible ? undefined : true}
aria-label={messages.slides}
data-visible={visible ? "true" : undefined}
>
{slides.map((slide, index) => (
<button
key={slide.id}
type="button"
aria-current={index === deck.slideIndex ? "page" : undefined}
aria-label={messages.goToSlideNumber(index + 1)}
tabIndex={visible ? 0 : -1}
onClick={() => deck.goToSlide(index + 1)}
>
<SlideViewers
className="slide-kit-progress-viewers"
size={14}
slideNumber={index + 1}
/>
</button>
))}
</nav>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { MotionConfig } from "motion/react";
import { useDeckContext } from "../core/deckContext";
import type { SlideDefinition } from "../core/Slide";
import { CanvasScaler } from "./CanvasScaler";
import { SlideFrame } from "./SlideFrame";
export function SlideStage({
slides,
flat = false,
}: {
slides: SlideDefinition[];
flat?: boolean;
}) {
const deck = useDeckContext();
const activeIndex = Math.min(deck.slideIndex, slides.length - 1);
const definition = slides[activeIndex]!;
return (
<CanvasScaler
className="slide-kit-stage"
frameClassName={flat ? undefined : "slide-kit-viewer-frame"}
surface={flat ? "presentation" : "stage"}
>
<MotionConfig reducedMotion="user">
<SlideFrame
key={definition.id}
definition={definition}
slideIndex={activeIndex}
revealedCount={
deck.presenting
? (deck.revealedBySlide[activeIndex] ?? 0)
: Number.MAX_SAFE_INTEGER
}
surface="stage"
onStepCountChange={(stepCount) =>
deck.setStepCount(activeIndex, stepCount)
}
/>
</MotionConfig>
</CanvasScaler>
);
}
+16
View File
@@ -0,0 +1,16 @@
import { AvatarGroup } from "@kits/clickup";
import { useViewersOfSlide } from "../core/slidePresence";
/** The people on a slide as a facepile; nothing when the viewer is alone there. */
export function SlideViewers({
className,
size,
slideNumber,
}: {
className: string;
size: number;
slideNumber: number;
}) {
const viewers = useViewersOfSlide(slideNumber);
return <AvatarGroup className={className} of={viewers} size={size} />;
}
+54
View File
@@ -0,0 +1,54 @@
import { useMemo, useRef } from "react";
import { MotionConfig } from "motion/react";
import type { SlideDefinition } from "../core/Slide";
import { CanvasScaler } from "./CanvasScaler";
import { SlideFrame } from "./SlideFrame";
import type { StaticReadyDetail } from "./staticReadiness";
import { useStaticReadiness } from "./useStaticReadiness";
interface StaticDeckProps {
slides: SlideDefinition[];
readinessTimeoutMs?: number;
onReadiness?: (root: HTMLElement, detail: StaticReadyDetail) => void;
}
export function StaticDeck({
slides,
readinessTimeoutMs,
onReadiness,
}: StaticDeckProps) {
const rootRef = useRef<HTMLDivElement | null>(null);
const assets = useMemo(
() => slides.flatMap((slide) => slide.staticAssets),
[slides],
);
useStaticReadiness(rootRef, assets, readinessTimeoutMs, onReadiness);
return (
<MotionConfig reducedMotion="always">
<div
ref={rootRef}
className="slide-kit-static"
data-slide-kit-readiness="pending"
data-slide-static-root
>
{slides.map((slide, index) => (
<div
key={slide.id}
className="slide-kit-static-page"
data-slide-static-page={index + 1}
>
<CanvasScaler staticCanvas surface="static">
<SlideFrame
definition={slide}
slideIndex={index}
revealedCount={Number.MAX_SAFE_INTEGER}
surface="static"
/>
</CanvasScaler>
</div>
))}
</div>
</MotionConfig>
);
}
+184
View File
@@ -0,0 +1,184 @@
import {
type RefCallback,
useCallback,
useEffect,
useRef,
useState,
} from "react";
import { useDeckContext } from "../core/deckContext";
import { getOwnerWindow } from "../core/domEnvironment";
import { useLocalization } from "../core/localization";
import type { SlideDefinition } from "../core/Slide";
import { CanvasScaler } from "./CanvasScaler";
import { SlideFrame } from "./SlideFrame";
import { SlideViewers } from "./SlideViewers";
const SCROLL_MARGIN_PX = 12;
const ACTIVE_THUMBNAIL_SELECTOR = '.slide-kit-thumbnail[data-active="true"]';
export function ThumbnailRail({
slides,
collapsed,
}: {
slides: SlideDefinition[];
collapsed: boolean;
}) {
const deck = useDeckContext();
const messages = useLocalization();
const [rootElement, setRootElement] = useState<HTMLElement | null>(null);
const rootRef: RefCallback<HTMLElement> = useCallback((element) => {
setRootElement(element);
}, []);
useActiveThumbnailInView(rootElement, deck.slideIndex, collapsed);
return (
<aside className="slide-kit-thumbnail-panel" aria-label={messages.slides}>
<div ref={rootRef} className="slide-kit-thumbnails">
{slides.map((slide, index) => (
<LazyThumbnail
key={slide.id}
definition={slide}
slideIndex={index}
active={index === deck.slideIndex}
rootElement={rootElement}
selectLabel={messages.goToSlideNumber(index + 1)}
onSelect={() => deck.goToSlide(index + 1)}
/>
))}
</div>
</aside>
);
}
function useActiveThumbnailInView(
rail: HTMLElement | null,
slideIndex: number,
collapsed: boolean,
): void {
const scrolledOnce = useRef(false);
useEffect(() => {
if (!rail || collapsed) {
scrolledOnce.current = false;
return;
}
const active = rail.querySelector<HTMLElement>(ACTIVE_THUMBNAIL_SELECTOR);
if (!active) {
return;
}
const animated =
scrolledOnce.current &&
!getOwnerWindow(rail).matchMedia("(prefers-reduced-motion: reduce)")
.matches;
scrollThumbnailIntoRail(rail, active, animated ? "smooth" : "auto");
scrolledOnce.current = true;
}, [collapsed, rail, slideIndex]);
}
function scrollThumbnailIntoRail(
rail: HTMLElement,
thumbnail: HTMLElement,
behavior: ScrollBehavior,
): void {
const railBox = rail.getBoundingClientRect();
const thumbnailBox = thumbnail.getBoundingClientRect();
const top = railScrollOffset(
rail.scrollTop,
thumbnailBox.top - railBox.top,
thumbnailBox.height,
railBox.height,
);
const left = railScrollOffset(
rail.scrollLeft,
thumbnailBox.left - railBox.left,
thumbnailBox.width,
railBox.width,
);
if (top === rail.scrollTop && left === rail.scrollLeft) {
return;
}
rail.scrollTo({ behavior, left, top });
}
function railScrollOffset(
scrollOffset: number,
thumbnailOffset: number,
thumbnailSize: number,
railSize: number,
): number {
if (thumbnailOffset < SCROLL_MARGIN_PX) {
return scrollOffset + thumbnailOffset - SCROLL_MARGIN_PX;
}
const overflow =
thumbnailOffset + thumbnailSize + SCROLL_MARGIN_PX - railSize;
return overflow > 0 ? scrollOffset + overflow : scrollOffset;
}
function LazyThumbnail({
definition,
slideIndex,
active,
rootElement,
selectLabel,
onSelect,
}: {
definition: SlideDefinition;
slideIndex: number;
active: boolean;
rootElement: HTMLElement | null;
selectLabel: string;
onSelect: () => void;
}) {
const buttonRef = useRef<HTMLDivElement | null>(null);
const [visible, setVisible] = useState(active);
useEffect(() => {
const element = buttonRef.current;
if (!element || !rootElement) {
return;
}
const observer = new IntersectionObserver(
([entry]) => {
setVisible(Boolean(entry?.isIntersecting));
},
{ root: rootElement, rootMargin: "240px" },
);
observer.observe(element);
return () => observer.disconnect();
}, [rootElement]);
return (
<div
ref={buttonRef}
className="slide-kit-thumbnail"
data-active={active ? "true" : undefined}
>
<span className="slide-kit-thumbnail-frame">
{visible || active ? (
<CanvasScaler fit="cover" surface="thumbnail">
<SlideFrame
definition={definition}
slideIndex={slideIndex}
revealedCount={Number.MAX_SAFE_INTEGER}
surface="thumbnail"
/>
</CanvasScaler>
) : null}
</span>
<SlideViewers
className="slide-kit-thumbnail-viewers"
size={18}
slideNumber={slideIndex + 1}
/>
<button
type="button"
className="slide-kit-thumbnail-action"
aria-label={selectLabel}
aria-current={active ? "page" : undefined}
disabled={active}
onClick={onSelect}
/>
</div>
);
}
@@ -0,0 +1,263 @@
import { getOwnerWindow } from "../core/domEnvironment";
export const PRESENTATION_CURSOR_IDLE_MS = 2_000;
export interface NormalizedPoint {
x: number;
y: number;
}
export type PresentationCursorKind = "magnifier" | "pointer";
export type PresentationInteractionAction =
| {
type: "move";
slideIndex: number;
point: NormalizedPoint;
cursor: PresentationCursorKind;
}
| { type: "leave" }
| { type: "openImage"; slideIndex: number; imageIndex: number }
| { type: "closeImage" }
| { type: "reset" };
export interface PresentationInteractionSnapshot {
cursor: {
kind: PresentationCursorKind;
point: NormalizedPoint;
slideIndex: number;
} | null;
focusedImage: { slideIndex: number; imageIndex: number } | null;
}
export interface PresentationInteractionController {
destroy: () => void;
dispatch: (action: PresentationInteractionAction) => void;
getSnapshot: () => PresentationInteractionSnapshot;
subscribe: (listener: () => void) => () => void;
}
const EMPTY_SNAPSHOT: PresentationInteractionSnapshot = {
cursor: null,
focusedImage: null,
};
export function createPresentationInteractionController(): PresentationInteractionController {
let snapshot = EMPTY_SNAPSHOT;
let pendingMove: Extract<
PresentationInteractionAction,
{ type: "move" }
> | null = null;
let animationFrame: number | null = null;
let idleTimeout: number | null = null;
const listeners = new Set<() => void>();
const publish = (next: PresentationInteractionSnapshot) => {
snapshot = next;
for (const listener of listeners) {
listener();
}
};
const clearAnimationFrame = () => {
if (animationFrame !== null) {
window.cancelAnimationFrame(animationFrame);
animationFrame = null;
}
pendingMove = null;
};
const clearIdleTimeout = () => {
if (idleTimeout !== null) {
window.clearTimeout(idleTimeout);
idleTimeout = null;
}
};
const hideCursor = () => {
clearAnimationFrame();
clearIdleTimeout();
if (snapshot.cursor) {
publish({ ...snapshot, cursor: null });
}
};
const scheduleIdle = () => {
clearIdleTimeout();
idleTimeout = window.setTimeout(hideCursor, PRESENTATION_CURSOR_IDLE_MS);
};
const dispatch = (action: PresentationInteractionAction) => {
switch (action.type) {
case "move": {
pendingMove = {
...action,
point: normalizePoint(action.point),
cursor: snapshot.focusedImage ? "pointer" : action.cursor,
};
scheduleIdle();
if (animationFrame === null) {
animationFrame = window.requestAnimationFrame(() => {
animationFrame = null;
const move = pendingMove;
pendingMove = null;
if (move) {
publish({
...snapshot,
cursor: {
kind: move.cursor,
point: move.point,
slideIndex: move.slideIndex,
},
});
}
});
}
break;
}
case "leave":
hideCursor();
break;
case "openImage":
if (action.slideIndex >= 0 && action.imageIndex >= 0) {
const pendingCursor = pendingMove
? {
kind: "pointer" as const,
point: pendingMove.point,
slideIndex: pendingMove.slideIndex,
}
: null;
clearAnimationFrame();
publish({
...snapshot,
cursor:
pendingCursor ??
(snapshot.cursor
? { ...snapshot.cursor, kind: "pointer" }
: null),
focusedImage: {
slideIndex: action.slideIndex,
imageIndex: action.imageIndex,
},
});
}
break;
case "closeImage":
if (snapshot.focusedImage) {
publish({ ...snapshot, focusedImage: null });
}
break;
case "reset":
clearAnimationFrame();
clearIdleTimeout();
if (snapshot !== EMPTY_SNAPSHOT) {
publish(EMPTY_SNAPSHOT);
}
break;
}
};
return {
destroy: () => {
clearAnimationFrame();
clearIdleTimeout();
listeners.clear();
},
dispatch,
getSnapshot: () => snapshot,
subscribe: (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
}
export interface InspectedPresentationPoint {
imageIndex: number | null;
move: Extract<PresentationInteractionAction, { type: "move" }>;
}
export function inspectPresentationPoint(
root: HTMLElement,
clientX: number,
clientY: number,
slideIndex: number,
): InspectedPresentationPoint | null {
const canvas = root.querySelector<HTMLElement>("[data-slide-canvas]");
/* istanbul ignore if -- Interaction surfaces always render a CanvasScaler. */
if (!canvas) {
return null;
}
const canvasRect = canvas.getBoundingClientRect();
if (
canvasRect.width <= 0 ||
canvasRect.height <= 0 ||
clientX < canvasRect.left ||
clientX > canvasRect.right ||
clientY < canvasRect.top ||
clientY > canvasRect.bottom
) {
return null;
}
const images = getZoomableImages(root);
let imageIndex: number | null = null;
for (let index = images.length - 1; index >= 0; index -= 1) {
const image = images[index]!;
const rect = image.getBoundingClientRect();
const style = getOwnerWindow(image).getComputedStyle(image);
if (
rect.width > 0 &&
rect.height > 0 &&
style.display !== "none" &&
style.visibility !== "hidden" &&
clientX >= rect.left &&
clientX <= rect.right &&
clientY >= rect.top &&
clientY <= rect.bottom
) {
imageIndex = index;
break;
}
}
return {
imageIndex,
move: {
type: "move",
slideIndex,
point: {
x: (clientX - canvasRect.left) / canvasRect.width,
y: (clientY - canvasRect.top) / canvasRect.height,
},
cursor: imageIndex === null ? "pointer" : "magnifier",
},
};
}
export function getZoomableImage(
root: HTMLElement,
imageIndex: number,
): HTMLImageElement | null {
return getZoomableImages(root)[imageIndex] ?? null;
}
function getZoomableImages(root: HTMLElement): HTMLImageElement[] {
const activeSlide = root.querySelector<HTMLElement>(".slide-kit-slide");
/* istanbul ignore if -- A rendered interaction canvas always contains its slide. */
if (!activeSlide) {
return [];
}
return Array.from(
activeSlide.querySelectorAll<HTMLImageElement>(
'img:not([data-slide-image-zoom="false"])',
),
);
}
function normalizePoint(point: NormalizedPoint): NormalizedPoint {
return {
x: Math.min(1, Math.max(0, point.x)),
y: Math.min(1, Math.max(0, point.y)),
};
}
@@ -0,0 +1,68 @@
import type { SlideTransition } from "../core/Slide";
export type SlideTransitionDirection = "forward" | "backward";
export interface ResolvedSlideTransition {
durationMs: number;
easing: string;
newKeyframes: Keyframe[];
}
export const STAGE_VIEW_TRANSITION_NAME = "slide-kit-stage";
const REFINED_EASING = "cubic-bezier(0.22, 1, 0.36, 1)";
export function resolveSlideTransition(
transition: SlideTransition | undefined,
direction: SlideTransitionDirection,
): ResolvedSlideTransition {
switch (transition ?? "fade") {
case "none":
return {
durationMs: 0,
easing: "linear",
newKeyframes: [],
};
case "fade":
return {
durationMs: 240,
easing: REFINED_EASING,
newKeyframes: [{ opacity: 0 }, { opacity: 1 }],
};
case "slide":
return {
durationMs: 280,
easing: REFINED_EASING,
newKeyframes: [
{
opacity: 0,
transform:
direction === "forward"
? "translateX(2.5%)"
: "translateX(-2.5%)",
},
{ opacity: 1, transform: "none" },
],
};
}
}
export function animateSlideTransition(
transition: ResolvedSlideTransition,
target: HTMLElement = document.documentElement,
): Animation[] {
if (
transition.newKeyframes.length === 0 ||
window.matchMedia("(prefers-reduced-motion: reduce)").matches
) {
return [];
}
return [
target.animate(transition.newKeyframes, {
duration: transition.durationMs,
easing: transition.easing,
fill: "both",
pseudoElement: `::view-transition-new(${STAGE_VIEW_TRANSITION_NAME})`,
}),
];
}
+236
View File
@@ -0,0 +1,236 @@
export const STATIC_READY_EVENT = "slide-kit:static-ready";
interface StaticReadinessOptions {
assets?: readonly string[];
signal?: AbortSignal;
timeoutMs?: number;
}
export interface StaticReadyDetail {
status: "ready" | "error";
error?: string;
}
export async function waitForStaticReadiness(
root: HTMLElement,
{
assets = [],
signal: externalSignal,
timeoutMs = 10_000,
}: StaticReadinessOptions = {},
): Promise<void> {
const controller = new AbortController();
const forwardAbort = () => controller.abort(externalSignal?.reason);
if (externalSignal?.aborted) {
forwardAbort();
} else {
externalSignal?.addEventListener("abort", forwardAbort, { once: true });
}
const timeout = window.setTimeout(
() =>
controller.abort(
new Error(
"Static slide rendering did not become ready before the timeout.",
),
),
timeoutMs,
);
try {
await settleStaticSurface(root, assets, controller.signal);
} catch (error) {
controller.abort(error);
throw error;
} finally {
window.clearTimeout(timeout);
externalSignal?.removeEventListener("abort", forwardAbort);
}
}
export function publishStaticReadiness(
root: HTMLElement,
detail: StaticReadyDetail,
): void {
root.dataset.slideKitReadiness = detail.status;
root.dispatchEvent(
new CustomEvent<StaticReadyDetail>(STATIC_READY_EVENT, {
bubbles: true,
detail,
}),
);
}
async function settleStaticSurface(
root: HTMLElement,
assets: readonly string[],
signal: AbortSignal,
): Promise<void> {
/* istanbul ignore else -- Supported artifact browsers expose FontFaceSet. */
if (document.fonts) {
await waitForPromise(document.fonts.ready, signal);
}
await Promise.all([
...Array.from(root.querySelectorAll<HTMLImageElement>("img")).map((image) =>
waitForImage(image, signal),
),
...Array.from(root.querySelectorAll<HTMLMediaElement>("video, audio")).map(
(media) => waitForMedia(media, signal),
),
...[...new Set(assets)].map((asset) => waitForImageSource(asset, signal)),
]);
throwIfAborted(signal);
for (const animation of getAnimations(root)) {
/* istanbul ignore next -- Browser animations normally retain their effect. */
const timing = animation.effect?.getComputedTiming();
if (timing?.endTime === Infinity) {
animation.pause();
animation.currentTime = 0;
} else {
animation.finish();
}
}
await nextAnimationFrame(signal);
await nextAnimationFrame(signal);
}
async function waitForImage(
image: HTMLImageElement,
signal: AbortSignal,
): Promise<void> {
if (image.loading === "lazy") {
image.loading = "eager";
}
if (!image.complete) {
await waitForEvent(image, "load", "error", signal);
}
/* istanbul ignore else -- Supported artifact browsers implement image decoding. */
if (image.decode) {
await waitForPromise(image.decode(), signal);
}
}
async function waitForImageSource(
source: string,
signal: AbortSignal,
): Promise<void> {
const image = new Image();
image.src = source;
await waitForImage(image, signal);
}
async function waitForMedia(
media: HTMLMediaElement,
signal: AbortSignal,
): Promise<void> {
if (media.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA) {
return;
}
const ready = waitForEvent(media, "loadeddata", "error", signal);
media.load();
await ready;
}
function waitForEvent(
target: EventTarget,
successEvent: string,
errorEvent: string,
signal: AbortSignal,
): Promise<void> {
return new Promise((resolve, reject) => {
const cleanup = () => {
target.removeEventListener(successEvent, onSuccess);
target.removeEventListener(errorEvent, onError);
signal.removeEventListener("abort", onAbort);
};
const onSuccess = () => {
cleanup();
resolve();
};
const onError = () => {
cleanup();
reject(new Error(`Failed while waiting for ${successEvent}.`));
};
const onAbort = () => {
cleanup();
reject(abortReason(signal));
};
if (signal.aborted) {
onAbort();
return;
}
target.addEventListener(successEvent, onSuccess, { once: true });
target.addEventListener(errorEvent, onError, { once: true });
signal.addEventListener("abort", onAbort, { once: true });
});
}
function getAnimations(root: HTMLElement): Animation[] {
/* istanbul ignore else -- Supported artifact browsers expose subtree animations. */
if (root.getAnimations) {
return root.getAnimations({ subtree: true });
}
return [];
}
function nextAnimationFrame(signal: AbortSignal): Promise<void> {
return new Promise((resolve, reject) => {
let frame: number | undefined;
const onAbort = () => {
if (frame !== undefined && typeof cancelAnimationFrame !== "undefined") {
cancelAnimationFrame(frame);
}
reject(abortReason(signal));
};
if (signal.aborted) {
onAbort();
return;
}
frame = requestAnimationFrame(() => {
signal.removeEventListener("abort", onAbort);
resolve();
});
signal.addEventListener("abort", onAbort, { once: true });
});
}
function waitForPromise<T>(
promise: Promise<T>,
signal: AbortSignal,
): Promise<T> {
return new Promise((resolve, reject) => {
const cleanup = () => signal.removeEventListener("abort", onAbort);
const onAbort = () => {
cleanup();
reject(abortReason(signal));
};
if (signal.aborted) {
onAbort();
return;
}
signal.addEventListener("abort", onAbort, { once: true });
promise.then(
(value) => {
cleanup();
resolve(value);
},
(error: unknown) => {
cleanup();
reject(error);
},
);
});
}
function throwIfAborted(signal: AbortSignal): void {
if (signal.aborted) {
throw abortReason(signal);
}
}
function abortReason(signal: AbortSignal): Error {
return signal.reason instanceof Error
? signal.reason
: new Error("Static slide rendering was cancelled.");
}
@@ -0,0 +1,176 @@
import { type RefObject, useEffect } from "react";
import { useDeckContext } from "../core/deckContext";
import { getOwnerWindow } from "../core/domEnvironment";
const WHEEL_THRESHOLD = 20;
const WHEEL_IDLE_RESET_MS = 250;
const WHEEL_NEW_GESTURE_GAP_MS = 150;
const WHEEL_REVERSAL_MIN = 4;
const WHEEL_DECAY_RUN = 3;
const WHEEL_RISE_FACTOR = 2;
const WHEEL_RISE_MIN = 12;
const SWIPE_DISTANCE = 50;
const SWIPE_DOMINANCE = 1.2;
const SWIPE_MAX_DURATION_MS = 600;
interface TouchStart {
x: number;
y: number;
startedAt: number;
}
export function useSlideGestureNavigation({
enabled,
rootRef,
}: {
enabled: boolean;
rootRef: RefObject<HTMLElement | null>;
}) {
const { next, previous } = useDeckContext();
useEffect(() => {
const root = rootRef.current;
if (!enabled || !root) {
return;
}
const ownerWindow = getOwnerWindow(root);
let accumulated = 0;
let cooldown = false;
let gestureSign = 0;
let gestureAxis: "x" | "y" = "y";
let lastMagnitude = 0;
let lastEventAt = Number.NEGATIVE_INFINITY;
let decayRun = 0;
let tailEstablished = false;
let wheelIdleTimer: number | null = null;
let touchStart: TouchStart | null = null;
const navigate = (forward: boolean) => {
if (forward) {
next();
} else {
previous();
}
};
const resetWheelGesture = () => {
accumulated = 0;
cooldown = false;
gestureSign = 0;
lastMagnitude = 0;
decayRun = 0;
tailEstablished = false;
wheelIdleTimer = null;
};
const onWheel = (event: WheelEvent) => {
// Pinch-to-zoom arrives as ctrl+wheel.
if (event.ctrlKey) {
return;
}
event.preventDefault();
if (wheelIdleTimer !== null) {
ownerWindow.clearTimeout(wheelIdleTimer);
}
wheelIdleTimer = ownerWindow.setTimeout(
resetWheelGesture,
WHEEL_IDLE_RESET_MS,
);
if (!cooldown && accumulated === 0) {
gestureAxis =
Math.abs(event.deltaX) > Math.abs(event.deltaY) ? "x" : "y";
}
const delta = gestureAxis === "x" ? event.deltaX : event.deltaY;
if (delta === 0) {
return;
}
const magnitude = Math.abs(delta);
const gap = event.timeStamp - lastEventAt;
lastEventAt = event.timeStamp;
if (cooldown) {
const reversed =
Math.sign(delta) !== gestureSign && magnitude >= WHEEL_REVERSAL_MIN;
const separated =
gap >= WHEEL_NEW_GESTURE_GAP_MS && magnitude >= lastMagnitude;
const risen =
tailEstablished &&
magnitude >=
Math.max(lastMagnitude * WHEEL_RISE_FACTOR, WHEEL_RISE_MIN);
if (!reversed && !separated && !risen) {
if (magnitude <= lastMagnitude) {
decayRun += 1;
tailEstablished = tailEstablished || decayRun >= WHEEL_DECAY_RUN;
} else {
decayRun = 0;
}
lastMagnitude = magnitude;
return;
}
cooldown = false;
accumulated = 0;
}
lastMagnitude = magnitude;
accumulated += delta;
if (Math.abs(accumulated) >= WHEEL_THRESHOLD) {
gestureSign = Math.sign(accumulated);
cooldown = true;
accumulated = 0;
decayRun = 0;
tailEstablished = false;
navigate(gestureSign > 0);
}
};
const onTouchStart = (event: TouchEvent) => {
if (event.touches.length !== 1) {
touchStart = null;
return;
}
const touch = event.touches[0]!;
touchStart = {
x: touch.clientX,
y: touch.clientY,
startedAt: Date.now(),
};
};
const onTouchMove = (event: TouchEvent) => {
if (touchStart && event.touches.length === 1) {
event.preventDefault();
}
};
const onTouchEnd = (event: TouchEvent) => {
const start = touchStart;
touchStart = null;
const touch = event.changedTouches[0];
if (!start || !touch) {
return;
}
const deltaX = start.x - touch.clientX;
const deltaY = start.y - touch.clientY;
if (
Date.now() - start.startedAt <= SWIPE_MAX_DURATION_MS &&
Math.abs(deltaY) >= SWIPE_DISTANCE &&
Math.abs(deltaY) > Math.abs(deltaX) * SWIPE_DOMINANCE
) {
event.preventDefault();
navigate(deltaY > 0);
}
};
const onTouchCancel = () => {
touchStart = null;
};
root.addEventListener("wheel", onWheel, { passive: false });
root.addEventListener("touchstart", onTouchStart, { passive: true });
root.addEventListener("touchmove", onTouchMove, { passive: false });
root.addEventListener("touchend", onTouchEnd, { passive: false });
root.addEventListener("touchcancel", onTouchCancel);
return () => {
root.removeEventListener("wheel", onWheel);
root.removeEventListener("touchstart", onTouchStart);
root.removeEventListener("touchmove", onTouchMove);
root.removeEventListener("touchend", onTouchEnd);
root.removeEventListener("touchcancel", onTouchCancel);
if (wheelIdleTimer !== null) {
ownerWindow.clearTimeout(wheelIdleTimer);
}
};
}, [enabled, next, previous, rootRef]);
}
@@ -0,0 +1,47 @@
import { type RefObject, useEffect } from "react";
import {
publishStaticReadiness,
type StaticReadyDetail,
waitForStaticReadiness,
} from "./staticReadiness";
export function useStaticReadiness(
rootRef: RefObject<HTMLElement | null>,
assets: readonly string[],
timeoutMs?: number,
onReadiness?: (root: HTMLElement, detail: StaticReadyDetail) => void,
): void {
useEffect(() => {
const root = rootRef.current;
/* istanbul ignore if -- React assigns the static root before effects run. */
if (!root) {
return;
}
root.dataset.slideKitReadiness = "pending";
const controller = new AbortController();
waitForStaticReadiness(root, {
assets,
signal: controller.signal,
...(timeoutMs === undefined ? {} : { timeoutMs }),
}).then(
() => {
if (!controller.signal.aborted) {
const detail: StaticReadyDetail = { status: "ready" };
publishStaticReadiness(root, detail);
onReadiness?.(root, detail);
}
},
(error: unknown) => {
if (!controller.signal.aborted) {
const detail: StaticReadyDetail = {
status: "error",
error: error instanceof Error ? error.message : String(error),
};
publishStaticReadiness(root, detail);
onReadiness?.(root, detail);
}
},
);
return () => controller.abort();
}, [assets, onReadiness, rootRef, timeoutMs]);
}