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
+180
View File
@@ -0,0 +1,180 @@
# Slides
Build fixed-canvas slide decks with the shared slide kit. The kit ships the entire viewer: scaling to any screen, keyboard and touch navigation, thumbnail rail, play mode with a presentation pointer and image zoom, presenter view with speaker notes, PDF and PPTX downloads. You author slide content only; never rebuild any of that chrome.
In a live artifact, decks are multiplayer out of the box: the rail shows who is on which slide, and each slide shows the cursors of the people on it, their cursor chat (`/`) and the text they select. Leave all of it on unless the user asks otherwise; `<Deck cursors={{ chat: false }}>` (or `selection: false`, `enabled: false`) turns one part off.
When the user wants every future deck to share one look (master slides), don't re-describe the design each time: load the ART-KITS subskill and turn an approved deck into an Art Kit.
## What you are building
The decks people admire are not documents cut into pages; they are talks, staged. Jobs introduced the iPod with a slide that said "1,000 songs in your pocket": five words on screen, every other word spoken. You are the speechwriter and the stage designer, not the typesetter: write the talk first, then stage it, and the classic failures of generated decks (walls of text, no build, no arc) never get a chance to happen.
Two different artifacts get called a deck. Decide which one you are building before anything else:
- **Presented deck**, the default. A presenter speaks over it, and each canvas anchors its moment with the one thing that must be seen to be believed. Sparse slides, real speaker `Notes`, reveals that follow the speech.
- **Reading deck**, only when the deck will be read rather than watched ("pre-read", "send-around", "leave-behind"). With no presenter to carry the words, each canvas has to make its point alone, like a consulting pre-read: the headline states a conclusion and one exhibit backs it up. The extra room goes to evidence (charts, tables, comparisons), never to prose; a slide of paragraphs is a memo wearing a deck's clothes. Don't use `Step` reveals here, since a reader only ever sees the settled slide.
If the request leaves the genre genuinely unclear, ask ("Will you present this, or should it read on its own?"): one question is cheaper than the wrong deck. Everything below assumes a presented deck; the reading deck differs only where called out.
## The beat sheet
Every deck starts as a beat sheet: the talk written out in order, opening on the thesis, building it with evidence, closing on the one takeaway. Each beat answers two questions:
- **What do you say?** The sentence or three you would actually speak. These words ship as the slide's `Notes`, nearly verbatim, so the canvas never has to absorb them.
- **What do they see?** The one thing the audience must see while hearing it. A number at statement scale (the takeaway, not the table it came from), an image or diagram that shows what words can't, a phrase (only the words that must be remembered verbatim), a chart whose shape is the point, or nothing new: the previous canvas holds while the speech moves on (Jobs often spoke over a plain black slide).
A slide shows only what its beat puts on screen: no headers, footers, sheet numbers, or corner labels. What you say can run long; what they see cannot. A beat that seems to need two things on screen is two beats. Every slide must pass the billboard test: one dominant element, huge type, readable in three seconds from across the room. A headline asserts the beat ("Churn dropped 40% after the rework"), never labels a topic ("Churn update"). Finish every slide with Chanel's rule: look once more and take one thing off.
Test the sheet before building anything: read the spoken lines top to bottom; they should reconstruct the whole argument. For a reading deck, each beat's words become the slide's headline instead of `Notes`, and the same test runs on the headlines.
Then stage it. A beat usually gets its own slide; consecutive beats can share one canvas, with the later beats becoming `Step` reveals. The audience must never read ahead of the narration: a list spoken item by item reveals item by item, an annotation lands when the speech reaches it.
## Build
Set up the project like any artifact; the kit is in every project as `kits/slides`:
```bash
artifact init "Q3 Review" # or: artifact clone <artifact-url> [-v N] to rework an existing deck (or one of its versions)
```
The deck is the whole app; `Notes` carry the talk, `Step`s carry the clicks. Every prop is in `kits/slides/docs/slides.d.ts`:
```jsx
import { motion } from "motion/react";
import "https://fonts.googleapis.com/css2?family=Schibsted+Grotesk:wght@400..900&display=swap";
import { Deck, Notes, Slide, Step, useSlideSteps, useStep } from "@kits/slides";
// The deck's one bold beat: snaps into focus when its step is revealed and
// unwinds going back; static surfaces (exports, thumbnails) render it settled.
function BoldBeat() {
const { visible } = useStep();
const { interactive } = useSlideSteps();
const beat = (delay) => ({
initial: false,
animate: visible
? { opacity: 1, filter: "blur(0px)", scale: 1 }
: { opacity: 0, filter: "blur(24px)", scale: 1.14 },
transition: { duration: interactive ? 0.9 : 0, ease: [0.16, 1, 0.3, 1], delay: interactive && visible ? delay : 0 },
});
return (
<>
<motion.h2 {...beat(0)} style={{ fontFamily: "Schibsted Grotesk" }} className="origin-left text-[240px] font-extrabold leading-none tracking-[-0.05em]">
Then move.
</motion.h2>
<motion.p {...beat(0.3)} className="mt-[52px] max-w-[880px] origin-left text-[40px] leading-[1.4] text-[#a89d92]">
Motion spends the attention that stillness saves.
</motion.p>
</>
);
}
export default function App() {
return (
<Deck>
<Slide className="flex flex-col justify-between bg-[#a4492e] p-[120px] text-[#f6f1e7]">
<p className="text-[24px] font-semibold uppercase tracking-[0.2em] text-[#efc4b2]">Slide craft</p>
{/* The hero: the same viewTransitionName and text on both slides makes
it travel between them. Keep it w-fit and never animate it. */}
<h1 style={{ fontFamily: "Schibsted Grotesk", viewTransitionName: "thesis" }} className="w-fit text-[300px] font-extrabold leading-none tracking-[-0.04em]">
Subtract.
</h1>
<div className="max-w-[880px] self-end">
<p className="text-[40px] leading-[1.4] text-[#f2d5c8]">
“Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.”
</p>
<p className="mt-[28px] text-[26px] text-[#efc4b2]">— Antoine de Saint-Exupéry</p>
</div>
{/* Notes are the talk, nearly verbatim; "advance" cues mark the clicks. */}
<Notes>
Saint-Exupéry said perfection is reached when there is nothing left
to take away. That is this whole talk in one word; let it hold the
room for a moment. Advance: the counter-beat.
</Notes>
</Slide>
<Slide className="flex flex-col justify-center bg-[#211d19] p-[120px] text-[#f6f1e7]">
<p style={{ fontFamily: "Schibsted Grotesk", viewTransitionName: "thesis" }} className="w-fit text-[56px] font-extrabold text-[#e17a55]">
Subtract.
</p>
<Step className="mt-[72px]">
<BoldBeat />
</Step>
<Notes>
But stillness is only half the craft. Advance, then move: motion
spends the attention that stillness saves, so spend it where the
story turns.
</Notes>
</Slide>
</Deck>
);
}
```
Slides crossfade into each other by default; `<Slide transition="slide">` pushes sideways, `"none"` cuts.
Hooks, for content that reacts to the deck:
```tsx
useSlideNumber(): number; useSlideCount(): number; // 1-based slide this renders on / total slides
useSlideSteps(): { revealed, total, interactive }; // reveal cursor; interactive=false on static surfaces
useStep(): { visible, index }; // the surrounding Step
useSlideNavigation(): { next, previous, goToSlide }; // in-slide nav, e.g. agenda links; goToSlide is 1-based
```
Slides render on several surfaces at once (stage, thumbnails, presenter, export), so keep them pure: no `window` reads or randomness in render. Design the resting pose first; exports skip animation and freeze infinite loops at their first frame. `<Slide staticAssets={[url]}>` declares URLs that only CSS references, so exports wait for them. Images are click-to-zoom in play mode; `data-slide-image-zoom="false"` opts a logo out.
## Craft
Word budgets: headline ≤ 8 words, a bullet ≤ 6 words and never wrapping, ~30 words visible per slide in total (a reading deck may run denser).
Density ceilings per slide type; hitting one means split, never shrink:
| Slide type | Maximum |
| ----------------- | ------------------------------------------------------- |
| Title / statement | 1 heading + 1 support line |
| Content | 1 heading + 4 one-line bullets **or** 1 short paragraph |
| Grid | 1 heading + 6 cards |
| Quote | 1 quote (≤3 lines) + attribution |
| Data | 1 chart **or** 2–3 big stats, + 1 takeaway line |
Type scale (px):
| Role | Size |
| ------------------------------------ | --------------------------- |
| Statement h1 (the text is the slide) | 120–200 |
| Section heading h2 | 64 |
| Subheading h3 | 44 |
| Body | 36 |
| Eyebrow, labels, captions | 24 (the floor for any text) |
Canvas padding ≥ 80px, gaps between tiers ≥ 48px; both grow as slides get sparser. Text blocks ≤ 900px wide. Left-align body text; center only statements.
The shared design principles, applied to a fixed canvas:
- **Hierarchy has depth.** Build it on two or three dimensions at once (size, weight, color, position, surrounding space), never size alone. Scale with sparseness: the fewer the elements, the bigger the type. Dead space around enormous type reads as intent; around timid type, as an accident.
- **Place the whitespace.** Push it between content tiers (`justify-between`, generous gaps) instead of letting it pool at the bottom. Horizontal asymmetry is composition; vertical imbalance is a bug. A slide that feels empty needs bigger type, not more decoration.
- **One visual system.** Two typefaces (one display face that stays composed at statement scale, one workhorse for body and labels), a committed palette, the same grammar on every slide. Vary the composition within it: no two adjacent slides should look alike.
- **Commit to color.** Decks carry far more color than UI: full-bleed color slides make great section breaks and closers. Never pure #000/#fff.
- **Motion hands attention to the content, never holds it.** Design the resting composition first, then decide how the slide arrives. Ambient motion is this medium's superpower: no other slide tool can make a canvas breathe (a drifting gradient, a texture stirring at the edges). Spectacle is welcome too when the motion acts out the idea (a number counting up, three options collapsing into one). Choreograph the deck like music: quiet slides frame expressive ones, elements move together rather than each on its own. Motion fails only when it is beside the point.
- **Never:** topic-label titles; accent bars or underlines beneath headings; the same card grid twice; bullets as the default body; every slide centered; hairline frames, divider lines, or corner marks where spacing would do; sheet numbers, rev tags, or other fake print metadata; gradient text; default chart styling; icons or emoji as filler; boxes added because a corner felt empty.
## Review
The URL hash switches review surfaces without reloading.
```bash
# Every slide as a numbered contact sheet in one screenshot (square viewport packs it largest).
artifact cdp -v 1500x1500 -e 'location.hash = "slide-preview-grid"' -s
# Slide N at full 1920×1080 resolution, steps revealed, animations settled.
artifact cdp --continue -v 1920x1080 -e 'location.hash = "slide-preview-3"' -s
# The live viewer (empty hash), for checking real choreography like hero carries
# and multi-step builds; each ArrowRight is one beat: next step, then next slide.
artifact cdp --continue -e 'location.hash = ""' \
-e 'window.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight" }))' -s
```
The grid is usually all you need: review it the way you would review a junior designer's work. Does it deliver the plan, does every slide land its one beat, does anything read as a wall of text (a thumbnail that does is a document, not a slide). Then get obsessive about the finish, because that is where generated decks betray themselves.
These screenshots are your working material, not deliverables: the user sees the saved deck itself. Never embed your captures in a reply, as markdown images or attachment URLs, unless the user explicitly asks to see a screenshot.
+158
View File
@@ -0,0 +1,158 @@
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
import { type HTMLMotionProps } from "motion/react";
import { type CSSProperties, type ReactNode, type RefObject } from "react";
export interface ViewTransitionStyle {
viewTransitionName?: string;
}
declare module "react" {
interface CSSProperties extends ViewTransitionStyle {
}
}
/** Which of `enabled`, `chat` and `selection` to turn off; all three are on by default. */
export interface DeckCursors {
/** Everyone else's pointer over the slide they share and the space around it. */
enabled?: boolean;
/** `/` types a message everyone sees at your cursor. */
chat?: boolean;
/** Text you select on a slide is highlighted for everyone else on it. */
selection?: boolean;
}
export interface DeckProps {
children: ReactNode;
className?: string;
/** In a live artifact, the cursors of the people on the same slide. */
cursors?: DeckCursors;
locale?: string;
style?: CSSProperties;
}
export declare function Deck({ children, className, cursors, locale, style, }: DeckProps): import("react/jsx-runtime").JSX.Element;
export type SlideTransition = "none" | "fade" | "slide";
export interface SlideProps extends Pick<HTMLAttributes<HTMLDivElement>, "className" | "style"> {
children?: ReactNode;
staticAssets?: readonly string[];
transition?: SlideTransition;
}
/** One slide of a `Deck`. Its children are what the audience sees; put `Step`s inside for the clicks and `Notes` for what the presenter says. */
export declare function Slide({ children }: SlideProps): import("react/jsx-runtime").JSX.Element;
interface SlideDefinition {
id: string;
content: ReactNode;
notes: ReactNode | null;
className?: string;
style?: CSSProperties;
staticAssets: readonly string[];
transition?: SlideTransition;
}
export interface SlideNavigation {
next: () => void;
previous: () => void;
goToSlide: (slideNumber: number) => void;
}
interface DeckContextValue extends SlideNavigation {
slideIndex: number;
slideCount: number;
revealedCount: number;
revealedBySlide: number[];
stepCounts: number[];
setStepCount: (slideIndex: number, stepCount: number) => void;
/** Steps reveal one beat at a time while presenting; elsewhere all of them show at once. */
presenting: boolean;
setPresenting: (presenting: boolean) => void;
}
declare function useDeckController(slides: SlideDefinition[], rootRef: RefObject<HTMLDivElement | null>): DeckContextValue;
declare function DeckProvider({ value, children, }: {
value: DeckContextValue;
children: ReactNode;
}): import("react/jsx-runtime").JSX.Element;
declare function SlidePositionProvider({ slideIndex, children, }: {
slideIndex: number;
children: ReactNode;
}): import("react/jsx-runtime").JSX.Element;
declare function useDeckContext(): DeckContextValue;
export declare function useSlideNumber(): number;
export declare function useSlideCount(): number;
export declare function useSlideNavigation(): SlideNavigation;
export interface NotesProps {
children: ReactNode;
}
/** The speaker notes of the surrounding `Slide`; the presenter sees them, the audience never does. */
export declare function Notes(_props: NotesProps): null;
export type SupportedLocale = "de" | "en" | "es" | "fr" | "ja" | "ko" | "pt" | "zh-CN" | "zh-TW";
declare function resolveLocale(requestedLocale?: string): SupportedLocale;
type StepMode = "controlled" | "interactive" | "static";
interface StepRegistryProps {
children: ReactNode;
mode: StepMode;
revealedCount: number;
onStepCountChange?: (stepCount: number) => void;
}
declare function StepRegistry({ children, mode, revealedCount, onStepCountChange, }: StepRegistryProps): import("react/jsx-runtime").JSX.Element;
export interface SlideStepsState {
/** How many of the slide's steps are revealed so far. */
revealed: number;
total: number;
/** True on the audience stage and the presenter's current slide, where animations play; other surfaces render the final pose at once. */
interactive: boolean;
}
/** The slide's reveal state, for content outside a `Step` that reacts to reveals; on static surfaces every step counts as revealed. */
export declare function useSlideSteps(): SlideStepsState;
export interface StepState {
visible: boolean;
/** The surrounding `Step`'s position among the slide's steps, in reveal order. */
index: number;
}
/** The state of the nearest surrounding Step. */
export declare function useStep(): StepState;
export interface StepProps extends Omit<HTMLMotionProps<"div">, "animate" | "initial" | "variants"> {
/** What appears when the presenter clicks; leave empty for a click that only advances `useSlideSteps()`. */
children?: ReactNode;
}
export declare function Step({ children, transition, ...props }: StepProps): import("react/jsx-runtime").JSX.Element;
export type DeckDownloadFormat = "pdf" | "pptx";
export interface DeckDownloadOptions {
filename?: string;
readinessTimeoutMs?: number;
}
export interface DeckDownloads {
downloadDeck: (format: DeckDownloadFormat, options?: DeckDownloadOptions) => Promise<void>;
downloadPdf: (options?: DeckDownloadOptions) => Promise<void>;
downloadPptx: (options?: DeckDownloadOptions) => Promise<void>;
}
declare function DeckDownloadProvider({ children, slides, }: {
children: ReactNode;
slides: SlideDefinition[];
}): import("react/jsx-runtime").JSX.Element;
export declare function useDeckDownloads(): DeckDownloads;
export declare const CANVAS_WIDTH = 1920;
export declare const CANVAS_HEIGHT = 1080;
interface CanvasScalerProps {
children: ReactNode;
className?: string;
fit?: "contain" | "cover";
frameClassName?: string;
staticCanvas?: boolean;
surface: string;
}
declare function CanvasScaler({ children, className, fit, frameClassName, staticCanvas, surface, }: CanvasScalerProps): import("react/jsx-runtime").JSX.Element;
export declare 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;
}
declare function waitForStaticReadiness(root: HTMLElement, { assets, signal: externalSignal, timeoutMs, }?: StaticReadinessOptions): Promise<void>;
declare function publishStaticReadiness(root: HTMLElement, detail: StaticReadyDetail): void;
+16
View File
@@ -0,0 +1,16 @@
import "./engine.css";
export {
CANVAS_HEIGHT,
CANVAS_WIDTH,
Deck,
Notes,
STATIC_READY_EVENT,
Slide,
Step,
useDeckDownloads,
useSlideCount,
useSlideNavigation,
useSlideNumber,
useSlideSteps,
useStep,
} from "./index.ts";
+552
View File
@@ -0,0 +1,552 @@
import {
type CSSProperties,
type RefObject,
type ReactNode,
useCallback,
useEffect,
useLayoutEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { Cursors } from "@kits/sync";
import {
DeckDownloadProvider,
type DeckDownloadFormat,
useDeckDownloads,
} from "../download/deckDownloads";
import { PresenterMode } from "../presenter/PresenterMode";
import {
openPresenterPopup,
PresenterPopupPortal,
type PresenterPopupTarget,
} from "../presenter/PresenterPopupPortal";
import { AudiencePresentation } from "../render/AudiencePresentation";
import { CompactPreview } from "../render/CompactPreview";
import { ControlButton } from "../render/ControlButton";
import { ControlIcon } from "../render/ControlIcon";
import { FloatingDeckControls } from "../render/FloatingDeckControls";
import { usePresentationInteractionController } from "../render/PresentationInteractionLayer";
import { GridDeck } from "../render/GridDeck";
import { SlideProgressRail } from "../render/SlideProgressRail";
import { SlideStage } from "../render/SlideStage";
import { SlidePreview } from "../render/SlidePreview";
import { StaticDeck } from "../render/StaticDeck";
import { ThumbnailRail } from "../render/ThumbnailRail";
import { useSlideGestureNavigation } from "../render/useSlideGestureNavigation";
import { DeckProvider, useDeckController, useDeckContext } from "./deckContext";
import {
handleKeyboardNavigation,
shouldIgnoreKeyboardEvent,
} from "./keyboardNavigation";
import { LocalizationProvider, useLocalization } from "./localization";
import { resolveLocale } from "./locale";
import { normalizeDeck } from "./normalizeDeck";
import type { SlideDefinition } from "./Slide";
import { useAnnounceSlide } from "./slidePresence";
/** Which of `enabled`, `chat` and `selection` to turn off; all three are on by default. */
export interface DeckCursors {
/** Everyone else's pointer over the slide they share and the space around it. */
enabled?: boolean;
/** `/` types a message everyone sees at your cursor. */
chat?: boolean;
/** Text you select on a slide is highlighted for everyone else on it. */
selection?: boolean;
}
export interface DeckProps {
children: ReactNode;
className?: string;
/** In a live artifact, the cursors of the people on the same slide. */
cursors?: DeckCursors;
locale?: string;
style?: CSSProperties;
}
export function Deck({
children,
className,
cursors,
locale,
style,
}: DeckProps) {
const resolvedLocale = resolveLocale(locale);
const slides = useMemo(() => normalizeDeck(children), [children]);
const rootRef = useRef<HTMLDivElement | null>(null);
const controller = useDeckController(slides, rootRef);
const mode = useRequestedMode();
return (
<LocalizationProvider locale={resolvedLocale}>
<DeckProvider value={controller}>
<div
ref={rootRef}
className={`slide-kit-root ${className ?? ""}`.trim()}
data-theme="light"
lang={resolvedLocale}
style={style}
>
<DeckDownloadProvider slides={slides}>
{mode.type === "static" ? (
<StaticDeck slides={slides} />
) : mode.type === "preview" ? (
<SlidePreview
slides={slides}
requestedPage={mode.requestedPage}
/>
) : mode.type === "grid" ? (
<GridDeck slides={slides} />
) : (
<AudienceMode
cursors={cursors}
slides={slides}
rootRef={rootRef}
/>
)}
</DeckDownloadProvider>
</div>
</DeckProvider>
</LocalizationProvider>
);
}
function AudienceMode({
cursors: { enabled = true, chat = true, selection = true } = {},
slides,
rootRef,
}: {
cursors?: DeckCursors;
slides: SlideDefinition[];
rootRef: RefObject<HTMLDivElement | null>;
}) {
const messages = useLocalization();
const { goToSlide, setPresenting, slideIndex } = useDeckContext();
useAnnounceSlide(slideIndex + 1);
const compactPreview = useCompactPreview();
const [fullscreen, setFullscreen] = useState(false);
const [presentationOpen, setPresentationOpen] = useState(false);
const [presenterTarget, setPresenterTarget] =
useState<PresenterPopupTarget | null>(null);
const [presenterError, setPresenterError] = useState<string | null>(null);
const [downloadError, setDownloadError] = useState<string | null>(null);
const [downloadFormat, setDownloadFormat] =
useState<DeckDownloadFormat | null>(null);
const [thumbnailsCollapsed, setThumbnailsCollapsed] =
useThumbnailsCollapsedPreference();
const [thumbnailsMotionReady, setThumbnailsMotionReady] = useState(false);
const mainRef = useRef<HTMLElement | null>(null);
const startedAtRef = useRef(Date.now());
const presentationInteraction = usePresentationInteractionController();
const { downloadDeck } = useDeckDownloads();
const startPresentation = useCallback(
(openFullscreen: boolean) => {
goToSlide(slideIndex + 1);
presentationInteraction.dispatch({ type: "reset" });
startedAtRef.current = Date.now();
setPresentationOpen(true);
if (openFullscreen) {
rootRef.current?.requestFullscreen?.().catch(ignoreFullscreenError);
}
},
[goToSlide, presentationInteraction, rootRef, slideIndex],
);
const closePresentation = useCallback(() => {
presentationInteraction.dispatch({ type: "reset" });
setPresentationOpen(false);
const presentationDocument = rootRef.current?.ownerDocument;
if (presentationDocument?.fullscreenElement) {
presentationDocument.exitFullscreen?.().catch(ignoreFullscreenError);
}
}, [presentationInteraction, rootRef]);
const toggleFullscreen = useCallback(() => {
const root = rootRef.current;
const presentationDocument = root?.ownerDocument;
/* istanbul ignore if -- Audience controls require a mounted deck root. */
if (!root || !presentationDocument) {
return;
}
if (presentationDocument.fullscreenElement) {
presentationDocument.exitFullscreen?.().catch(ignoreFullscreenError);
} else {
root.requestFullscreen?.().catch(ignoreFullscreenError);
}
}, [rootRef]);
const openPresenter = useCallback(() => {
const root = rootRef.current;
/* istanbul ignore if -- Audience controls require a mounted deck root. */
if (!root) {
return;
}
if (presenterTarget && !presenterTarget.popupWindow.closed) {
presenterTarget.popupWindow.focus();
startedAtRef.current = Date.now();
presentationInteraction.dispatch({ type: "reset" });
setPresenterError(null);
setPresentationOpen(true);
return;
}
const target = openPresenterPopup(root, messages.presenterView);
if (!target) {
setPresenterError(messages.popupBlocked);
return;
}
startedAtRef.current = Date.now();
presentationInteraction.dispatch({ type: "reset" });
setPresenterError(null);
setPresentationOpen(true);
setPresenterTarget(target);
}, [
messages.popupBlocked,
messages.presenterView,
presentationInteraction,
presenterTarget,
rootRef,
]);
const closePresenter = useCallback((target: PresenterPopupTarget) => {
setPresenterTarget((current) => (current === target ? null : current));
}, []);
const startDownload = useCallback(
async (format: DeckDownloadFormat) => {
if (downloadFormat) {
return;
}
setDownloadFormat(format);
setDownloadError(null);
try {
await downloadDeck(format);
} catch (error: unknown) {
setDownloadError(
error instanceof Error
? `${messages.downloadFailed} ${error.message}`
: messages.downloadFailed,
);
} finally {
setDownloadFormat(null);
}
},
[downloadDeck, downloadFormat, messages.downloadFailed],
);
useLayoutEffect(() => {
setPresenting(presentationOpen || presenterTarget !== null);
}, [presentationOpen, presenterTarget, setPresenting]);
useEffect(() => {
const frame = window.requestAnimationFrame(() =>
setThumbnailsMotionReady(true),
);
return () => window.cancelAnimationFrame(frame);
}, []);
useEffect(() => {
const presentationDocument = rootRef.current?.ownerDocument;
/* istanbul ignore if -- The effect only runs for a mounted deck root. */
if (!presentationDocument) {
return;
}
const onFullscreenChange = () =>
setFullscreen(Boolean(presentationDocument.fullscreenElement));
onFullscreenChange();
presentationDocument.addEventListener(
"fullscreenchange",
onFullscreenChange,
);
return () =>
presentationDocument.removeEventListener(
"fullscreenchange",
onFullscreenChange,
);
}, [rootRef]);
useDeckKeyboard({
enabled: !compactPreview,
onPresent: presentationOpen
? toggleFullscreen
: () => startPresentation(true),
onPresenter: openPresenter,
onClose: closePresentation,
presentationOpen,
});
useSlideGestureNavigation({
enabled: !compactPreview && !presentationOpen,
rootRef: mainRef,
});
if (compactPreview) {
return <CompactPreview slide={slides[0]!} />;
}
return (
<>
{presenterTarget ? (
<PresenterPopupPortal target={presenterTarget} onClose={closePresenter}>
<PresenterMode
controller={presentationInteraction}
presenterWindow={presenterTarget.popupWindow}
slides={slides}
startedAt={startedAtRef.current}
/>
</PresenterPopupPortal>
) : null}
{presentationOpen ? (
<AudiencePresentation
controller={presentationInteraction}
fullscreen={fullscreen}
slides={slides}
onClose={closePresentation}
onToggleFullscreen={toggleFullscreen}
/>
) : (
<section
className="slide-kit-viewer"
data-thumbnails-collapsed={thumbnailsCollapsed ? "true" : undefined}
data-thumbnails-motion-ready={
thumbnailsMotionReady ? "true" : undefined
}
>
<ThumbnailRail collapsed={thumbnailsCollapsed} slides={slides} />
<main ref={mainRef} className="slide-kit-main">
<SlideStage slides={slides} />
{enabled && (
<Cursors
chat={chat}
frame=".slide-kit-canvas-geometry"
region={`slide-${slideIndex + 1}`}
selection={selection}
/>
)}
</main>
<ControlButton
iconOnly
className="slide-kit-thumbnail-toggle"
aria-expanded={!thumbnailsCollapsed}
aria-label={
thumbnailsCollapsed
? messages.showThumbnails
: messages.hideThumbnails
}
title={
thumbnailsCollapsed
? messages.showThumbnails
: messages.hideThumbnails
}
onClick={() => setThumbnailsCollapsed(!thumbnailsCollapsed)}
>
<ControlIcon
name={
thumbnailsCollapsed ? "panel-left-open" : "panel-left-close"
}
/>
</ControlButton>
<SlideProgressRail slides={slides} visible={thumbnailsCollapsed} />
<FloatingDeckControls
downloadFormat={downloadFormat}
onDownload={(format) => void startDownload(format)}
onPresent={() => startPresentation(true)}
onPresenter={openPresenter}
/>
</section>
)}
{presenterError || downloadError || downloadFormat ? (
<div
className="slide-kit-toast"
role={presenterError || downloadError ? "alert" : "status"}
>
{presenterError ??
downloadError ??
`${messages.preparingDownload} ${downloadFormat?.toUpperCase()}`}
</div>
) : null}
</>
);
}
function useDeckKeyboard({
enabled,
presentationOpen,
onPresent,
onPresenter,
onClose,
}: {
enabled: boolean;
presentationOpen: boolean;
onPresent: () => void;
onPresenter: () => void;
onClose: () => void;
}) {
const controller = useDeckContext();
useEffect(() => {
if (!enabled) {
return;
}
const onKeyDown = (event: KeyboardEvent) => {
if (shouldIgnoreKeyboardEvent(event)) {
return;
}
if (
handleKeyboardNavigation(event, {
first: () => controller.goToSlide(1),
last: () => controller.goToSlide(controller.slideCount),
next: controller.next,
previous: controller.previous,
})
) {
return;
}
if (event.key === "f" || event.key === "F") {
event.preventDefault();
onPresent();
} else if (event.key === "p" || event.key === "P") {
event.preventDefault();
onPresenter();
} else if (event.key === "Escape" && presentationOpen) {
event.preventDefault();
onClose();
}
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
}, [controller, enabled, presentationOpen, onPresent, onPresenter, onClose]);
}
function ignoreFullscreenError() {
return undefined;
}
const THUMBNAILS_COLLAPSED_STORAGE_KEY = "slide-kit:thumbnails-collapsed";
function useThumbnailsCollapsedPreference(): [
boolean,
(collapsed: boolean) => void,
] {
const [collapsed, setCollapsedState] = useState(
readThumbnailsCollapsedPreference,
);
const setCollapsed = useCallback((next: boolean) => {
setCollapsedState(next);
writeThumbnailsCollapsedPreference(next);
}, []);
useEffect(() => {
const onStorage = (event: StorageEvent) => {
if (
event.key === THUMBNAILS_COLLAPSED_STORAGE_KEY ||
event.key === null
) {
setCollapsedState(event.newValue === "true");
}
};
window.addEventListener("storage", onStorage);
return () => window.removeEventListener("storage", onStorage);
}, []);
return [collapsed, setCollapsed];
}
function readThumbnailsCollapsedPreference(): boolean {
/* istanbul ignore if -- Server rendering has no local storage. */
if (typeof window === "undefined") {
return false;
}
try {
return (
window.localStorage.getItem(THUMBNAILS_COLLAPSED_STORAGE_KEY) === "true"
);
} catch {
return false;
}
}
function writeThumbnailsCollapsedPreference(collapsed: boolean): void {
try {
window.localStorage.setItem(
THUMBNAILS_COLLAPSED_STORAGE_KEY,
String(collapsed),
);
} catch {
// Storage can be unavailable in sandboxed artifact hosts.
}
}
const PHONE_PORTRAIT_WIDTH = 320;
const PHONE_PORTRAIT_HEIGHT = 568;
function useCompactPreview(): boolean {
const [compact, setCompact] = useState(readCompactPreview);
useEffect(() => {
const onResize = () => setCompact(readCompactPreview());
window.addEventListener("resize", onResize);
return () => window.removeEventListener("resize", onResize);
}, []);
return compact;
}
function readCompactPreview(): boolean {
/* istanbul ignore if -- Server rendering has no viewport. */
if (typeof window === "undefined") {
return false;
}
const { innerHeight, innerWidth } = window;
return (
(innerWidth < PHONE_PORTRAIT_WIDTH &&
innerHeight < PHONE_PORTRAIT_HEIGHT) ||
(innerWidth < PHONE_PORTRAIT_HEIGHT && innerHeight < PHONE_PORTRAIT_WIDTH)
);
}
type RequestedMode =
| { type: "audience" }
| { type: "preview"; requestedPage: string }
| { type: "static" }
| { type: "grid" };
type ReviewSurface = "audience" | "grid" | "static" | `preview-page:${string}`;
const PREVIEW_PAGE_HASH_PATTERN = /^slide-preview-(\d+)$/;
function useRequestedMode(): RequestedMode {
const reviewSurface = useSyncExternalStore(
subscribeToHash,
readReviewSurface,
() => "audience" as const,
);
if (reviewSurface.startsWith("preview-page:")) {
return {
type: "preview",
requestedPage: reviewSurface.slice("preview-page:".length),
};
}
if (reviewSurface === "static") {
return { type: "static" };
}
return reviewSurface === "grid" ? { type: "grid" } : { type: "audience" };
}
function subscribeToHash(onChange: () => void): () => void {
window.addEventListener("hashchange", onChange);
return () => window.removeEventListener("hashchange", onChange);
}
function readReviewSurface(): ReviewSurface {
const hash = window.location.hash.replace(/^#/, "");
if (hash === "slide-preview-grid") {
return "grid";
}
if (hash === "slide-static") {
return "static";
}
const previewPage = hash.match(PREVIEW_PAGE_HASH_PATTERN)?.[1];
if (previewPage) {
return `preview-page:${previewPage}`;
}
return "audience";
}
+10
View File
@@ -0,0 +1,10 @@
import type { ReactNode } from "react";
export interface NotesProps {
children: ReactNode;
}
/** The speaker notes of the surrounding `Slide`; the presenter sees them, the audience never does. */
export function Notes(_props: NotesProps) {
return null;
}
+27
View File
@@ -0,0 +1,27 @@
import type { CSSProperties, HTMLAttributes, ReactNode } from "react";
export type SlideTransition = "none" | "fade" | "slide";
export interface SlideProps extends Pick<
HTMLAttributes<HTMLDivElement>,
"className" | "style"
> {
children?: ReactNode;
staticAssets?: readonly string[];
transition?: SlideTransition;
}
/** One slide of a `Deck`. Its children are what the audience sees; put `Step`s inside for the clicks and `Notes` for what the presenter says. */
export function Slide({ children }: SlideProps) {
return <>{children}</>;
}
export interface SlideDefinition {
id: string;
content: ReactNode;
notes: ReactNode | null;
className?: string;
style?: CSSProperties;
staticAssets: readonly string[];
transition?: SlideTransition;
}
+217
View File
@@ -0,0 +1,217 @@
import {
createContext,
type ReactNode,
useCallback,
useContext,
useId,
useLayoutEffect,
useMemo,
useRef,
useState,
} from "react";
import { motion, type HTMLMotionProps, type Variants } from "motion/react";
export type StepMode = "controlled" | "interactive" | "static";
interface StepRegistryValue {
mode: StepMode;
revealedCount: number;
indices: ReadonlyMap<string, number>;
register: (id: string, element: HTMLElement) => () => void;
}
const StepRegistryContext = createContext<StepRegistryValue | null>(null);
const stepVariants: Variants = {
hidden: {
opacity: 0,
y: 20,
visibility: "hidden",
transition: { duration: 0.18 },
},
visible: {
opacity: 1,
y: 0,
visibility: "visible",
transition: { duration: 0.22, ease: [0, 0, 0.2, 1] },
},
};
interface StepRegistryProps {
children: ReactNode;
mode: StepMode;
revealedCount: number;
onStepCountChange?: (stepCount: number) => void;
}
export function StepRegistry({
children,
mode,
revealedCount,
onStepCountChange,
}: StepRegistryProps) {
const elementsRef = useRef(new Map<string, HTMLElement>());
const onStepCountChangeRef = useRef(onStepCountChange);
const mountedRef = useRef(false);
const reportVersionRef = useRef(0);
const [indices, setIndices] = useState<ReadonlyMap<string, number>>(
() => new Map(),
);
onStepCountChangeRef.current = onStepCountChange;
const scheduleStepCountReport = useCallback(() => {
const version = ++reportVersionRef.current;
queueMicrotask(() => {
if (mountedRef.current && version === reportVersionRef.current) {
onStepCountChangeRef.current?.(elementsRef.current.size);
}
});
}, []);
const refresh = useCallback(() => {
const entries = [...elementsRef.current.entries()].sort(
([, left], [, right]) => {
return left.compareDocumentPosition(right) &
Node.DOCUMENT_POSITION_FOLLOWING
? -1
: 1;
},
);
setIndices(new Map(entries.map(([id], index) => [id, index])));
scheduleStepCountReport();
}, [scheduleStepCountReport]);
const register = useCallback(
(id: string, element: HTMLElement) => {
elementsRef.current.set(id, element);
refresh();
return () => {
elementsRef.current.delete(id);
refresh();
};
},
[refresh],
);
useLayoutEffect(() => {
mountedRef.current = true;
scheduleStepCountReport();
return () => {
mountedRef.current = false;
reportVersionRef.current += 1;
};
}, [scheduleStepCountReport]);
const value = useMemo(
() => ({ mode, revealedCount, indices, register }),
[mode, revealedCount, indices, register],
);
return (
<StepRegistryContext.Provider value={value}>
{children}
</StepRegistryContext.Provider>
);
}
export interface SlideStepsState {
/** How many of the slide's steps are revealed so far. */
revealed: number;
total: number;
/** True on the audience stage and the presenter's current slide, where animations play; other surfaces render the final pose at once. */
interactive: boolean;
}
/** The slide's reveal state, for content outside a `Step` that reacts to reveals; on static surfaces every step counts as revealed. */
export function useSlideSteps(): SlideStepsState {
const registry = useContext(StepRegistryContext);
if (!registry) {
throw new Error("useSlideSteps must be used inside a Slide.");
}
const total = registry.indices.size;
return {
revealed:
registry.mode === "static"
? total
: Math.min(registry.revealedCount, total),
total,
interactive: registry.mode === "interactive",
};
}
export interface StepState {
visible: boolean;
/** The surrounding `Step`'s position among the slide's steps, in reveal order. */
index: number;
}
const StepContext = createContext<StepState | null>(null);
/** The state of the nearest surrounding Step. */
export function useStep(): StepState {
const value = useContext(StepContext);
if (!value) {
throw new Error("useStep must be used inside a Step.");
}
return value;
}
export interface StepProps extends Omit<
HTMLMotionProps<"div">,
"animate" | "initial" | "variants"
> {
/** What appears when the presenter clicks; leave empty for a click that only advances `useSlideSteps()`. */
children?: ReactNode;
}
export function Step({ children, transition, ...props }: StepProps) {
const registry = useContext(StepRegistryContext);
if (!registry) {
throw new Error("Step must be rendered inside a Slide.");
}
const id = useId();
const elementRef = useRef<HTMLDivElement | null>(null);
const index = registry.indices.get(id);
const visible =
registry.mode === "static" ||
(index !== undefined && index < registry.revealedCount);
useLayoutEffect(() => {
const element = elementRef.current;
/* istanbul ignore if -- React assigns the host ref before layout effects. */
if (!element) {
return;
}
return registry.register(id, element);
}, [id, registry.register]);
useLayoutEffect(() => {
/* istanbul ignore else -- React keeps the host ref throughout mounted updates. */
if (elementRef.current) {
elementRef.current.inert = !visible;
}
}, [visible]);
const stepState = useMemo(
() => ({ visible, index: index ?? -1 }),
[visible, index],
);
return (
<motion.div
{...props}
ref={elementRef}
data-slide-step={visible ? "visible" : "hidden"}
aria-hidden={!visible}
initial={false}
animate={visible ? "visible" : "hidden"}
variants={stepVariants}
transition={
registry.mode === "interactive" ? transition : { duration: 0 }
}
>
<StepContext.Provider value={stepState}>{children}</StepContext.Provider>
</motion.div>
);
}
+192
View File
@@ -0,0 +1,192 @@
import {
createContext,
type ReactNode,
type RefObject,
useCallback,
useContext,
useEffect,
useMemo,
useReducer,
useRef,
useState,
} from "react";
import { createNavigationState, navigationReducer } from "./navigationReducer";
import type { SlideDefinition } from "./Slide";
import { useSlideTransitionCoordinator } from "./slideTransitionCoordinator";
export interface SlideNavigation {
next: () => void;
previous: () => void;
goToSlide: (slideNumber: number) => void;
}
interface DeckContextValue extends SlideNavigation {
slideIndex: number;
slideCount: number;
revealedCount: number;
revealedBySlide: number[];
stepCounts: number[];
setStepCount: (slideIndex: number, stepCount: number) => void;
/** Steps reveal one beat at a time while presenting; elsewhere all of them show at once. */
presenting: boolean;
setPresenting: (presenting: boolean) => void;
}
const DeckContext = createContext<DeckContextValue | null>(null);
const SlidePositionContext = createContext<number | null>(null);
const NO_STEP_BEATS: number[] = [];
export function useDeckController(
slides: SlideDefinition[],
rootRef: RefObject<HTMLDivElement | null>,
): DeckContextValue {
const slideCount = slides.length;
const [state, dispatch] = useReducer(
navigationReducer,
slideCount,
createNavigationState,
);
const [stepCounts, setStepCounts] = useState<number[]>(() =>
Array.from({ length: slideCount }, () => 0),
);
const stepCountsRef = useRef(stepCounts);
stepCountsRef.current = stepCounts;
const [presenting, setPresenting] = useState(false);
const presentingRef = useRef(presenting);
presentingRef.current = presenting;
useEffect(() => {
const next = Array.from(
{ length: slideCount },
(_, index) => stepCountsRef.current[index] ?? 0,
);
stepCountsRef.current = next;
setStepCounts(next);
}, [slideCount]);
useEffect(() => {
dispatch({ type: "syncSlides", slideCount, stepCounts });
}, [slideCount, stepCounts]);
const getStepCounts = useCallback(
() => (presentingRef.current ? stepCountsRef.current : NO_STEP_BEATS),
[],
);
const dispatchNavigation = useSlideTransitionCoordinator({
dispatch,
getStepCounts,
rootRef,
slides,
state,
});
const setStepCount = useCallback((slideIndex: number, stepCount: number) => {
const current = stepCountsRef.current;
if (current[slideIndex] !== stepCount) {
const next = [...current];
next[slideIndex] = stepCount;
stepCountsRef.current = next;
setStepCounts(next);
}
dispatch({ type: "syncStepCount", slideIndex, stepCount });
}, []);
const next = useCallback(() => {
dispatchNavigation({ type: "next" });
}, [dispatchNavigation]);
const previous = useCallback(() => {
dispatchNavigation({ type: "previous" });
}, [dispatchNavigation]);
const goToSlide = useCallback(
(slideNumber: number) => {
if (!Number.isFinite(slideNumber)) {
return;
}
dispatchNavigation({
type: "goTo",
slideIndex: Math.trunc(slideNumber) - 1,
});
},
[dispatchNavigation],
);
const slideIndex = Math.min(state.slideIndex, slideCount - 1);
return useMemo(
() => ({
slideIndex,
slideCount,
revealedCount: state.revealedBySlide[slideIndex] ?? 0,
revealedBySlide: state.revealedBySlide,
stepCounts,
setStepCount,
presenting,
setPresenting,
next,
previous,
goToSlide,
}),
[
slideIndex,
state.revealedBySlide,
slideCount,
stepCounts,
setStepCount,
presenting,
next,
previous,
goToSlide,
],
);
}
export function DeckProvider({
value,
children,
}: {
value: DeckContextValue;
children: ReactNode;
}) {
return <DeckContext.Provider value={value}>{children}</DeckContext.Provider>;
}
export function SlidePositionProvider({
slideIndex,
children,
}: {
slideIndex: number;
children: ReactNode;
}) {
return (
<SlidePositionContext.Provider value={slideIndex}>
{children}
</SlidePositionContext.Provider>
);
}
export function useDeckContext(): DeckContextValue {
const value = useContext(DeckContext);
if (!value) {
throw new Error("Slide kit hooks must be used inside Deck.");
}
return value;
}
export function useSlideNumber(): number {
const deck = useDeckContext();
const renderedSlideIndex = useContext(SlidePositionContext);
return (renderedSlideIndex ?? deck.slideIndex) + 1;
}
export function useSlideCount(): number {
return useDeckContext().slideCount;
}
export function useSlideNavigation(): SlideNavigation {
const { next, previous, goToSlide } = useDeckContext();
return useMemo(
() => ({ next, previous, goToSlide }),
[next, previous, goToSlide],
);
}
+7
View File
@@ -0,0 +1,7 @@
export function getOwnerWindow(element: Element): Window & typeof globalThis {
const ownerWindow = element.ownerDocument.defaultView;
if (!ownerWindow) {
throw new Error("Rendered slide content must belong to a browser window.");
}
return ownerWindow as Window & typeof globalThis;
}
@@ -0,0 +1,83 @@
type KeyboardNavigationCommand = "first" | "last" | "next" | "previous";
interface KeyboardNavigationHandlers {
first: () => void;
last: () => void;
next: () => void;
previous: () => void;
}
function getKeyboardNavigationCommand(
key: string,
): KeyboardNavigationCommand | null {
if (
key === "ArrowRight" ||
key === "ArrowDown" ||
key === " " ||
key === "PageDown"
) {
return "next";
}
if (key === "ArrowLeft" || key === "ArrowUp" || key === "PageUp") {
return "previous";
}
if (key === "Home") {
return "first";
}
if (key === "End") {
return "last";
}
return null;
}
export function handleKeyboardNavigation(
event: KeyboardEvent,
handlers: KeyboardNavigationHandlers,
): boolean {
const command = getKeyboardNavigationCommand(event.key);
if (!command) {
return false;
}
event.preventDefault();
handlers[command]();
return true;
}
export function shouldIgnoreKeyboardEvent(event: KeyboardEvent): boolean {
return hasCommandModifier(event) || isInteractiveTarget(event.target);
}
function isInteractiveTarget(target: EventTarget | null): boolean {
const element = target as
| (EventTarget & { closest?: Element["closest"] })
| null;
return (
typeof element?.closest === "function" &&
element.closest(
[
"a[href]",
"audio[controls]",
"button",
"iframe",
"input",
"select",
"summary",
"textarea",
"video[controls]",
"[contenteditable]:not([contenteditable='false'])",
"[role='button']",
"[role='combobox']",
"[role='listbox']",
"[role='menuitem']",
"[role='slider']",
"[role='spinbutton']",
"[role='textbox']",
"[tabindex]:not([tabindex='-1'])",
].join(","),
) !== null
);
}
function hasCommandModifier(event: KeyboardEvent): boolean {
return event.altKey || event.ctrlKey || event.metaKey;
}
+38
View File
@@ -0,0 +1,38 @@
export type SupportedLocale =
| "de"
| "en"
| "es"
| "fr"
| "ja"
| "ko"
| "pt"
| "zh-CN"
| "zh-TW";
export function resolveLocale(requestedLocale?: string): SupportedLocale {
const browserLocale =
typeof navigator === "undefined"
? undefined
: (navigator.languages?.[0] ?? navigator.language);
const normalized = (requestedLocale ?? browserLocale ?? "en")
.replace("_", "-")
.toLowerCase();
if (normalized.startsWith("zh-")) {
return /-(hk|mo|tw)(-|$)/.test(normalized) ? "zh-TW" : "zh-CN";
}
const language = normalized.split("-")[0];
if (
language === "de" ||
language === "en" ||
language === "es" ||
language === "fr" ||
language === "ja" ||
language === "ko" ||
language === "pt"
) {
return language;
}
return "en";
}
+378
View File
@@ -0,0 +1,378 @@
import { createContext, type ReactNode, useContext, useMemo } from "react";
import type { SupportedLocale } from "./locale";
interface TranslationStrings {
close: string;
connected: string;
currentSlide: string;
download: string;
downloadFailed: string;
elapsedTime: string;
enterFullscreen: string;
expandedImage: string;
next: string;
noNotes: string;
pdfDocument: string;
startPresentation: string;
popupBlocked: string;
presenter: string;
preparingDownload: string;
presentation: string;
presentationControls: string;
presenterView: string;
powerPoint: string;
previous: string;
hideThumbnails: string;
showThumbnails: string;
slidePosition: string;
slidePreview: string;
slides: string;
speakerNotes: string;
upNext: string;
goToSlideNumber: string;
slideLabel: string;
}
type TranslationMessages = Omit<
TranslationStrings,
"goToSlideNumber" | "slideLabel"
> & {
goToSlideNumber: (slideNumber: number) => string;
slideLabel: (slideNumber: number, slideCount: number) => string;
};
const translations: Record<SupportedLocale, TranslationStrings> = {
en: {
close: "Close",
connected: "Connected",
currentSlide: "Current slide",
download: "Download",
downloadFailed: "Download failed.",
elapsedTime: "Elapsed time",
enterFullscreen: "Enter fullscreen",
expandedImage: "Expanded image",
next: "Next",
noNotes: "No notes for this slide.",
pdfDocument: "PDF document",
startPresentation: "Play",
popupBlocked:
"The presenter window was blocked. Allow popups and try again.",
presenter: "Presenter",
preparingDownload: "Preparing download…",
presentation: "Presentation",
presentationControls: "Presentation controls",
presenterView: "Presenter view",
powerPoint: "PowerPoint",
previous: "Previous",
hideThumbnails: "Hide slide previews",
showThumbnails: "Show slide previews",
slidePosition: "Slide position",
slidePreview: "Slide preview",
slides: "Slides",
speakerNotes: "Speaker notes",
upNext: "Up next",
goToSlideNumber: "Go to slide {slideNumber}",
slideLabel: "Slide {slideNumber} of {slideCount}",
},
de: {
close: "Schließen",
connected: "Verbunden",
currentSlide: "Aktuelle Folie",
download: "Herunterladen",
downloadFailed: "Download fehlgeschlagen.",
elapsedTime: "Verstrichene Zeit",
enterFullscreen: "Vollbild aktivieren",
expandedImage: "Vergrößertes Bild",
next: "Weiter",
noNotes: "Keine Notizen für diese Folie.",
pdfDocument: "PDF-Dokument",
startPresentation: "Präsentieren",
popupBlocked:
"Das Referentenfenster wurde blockiert. Erlauben Sie Pop-ups und versuchen Sie es erneut.",
presenter: "Referentenansicht",
preparingDownload: "Download wird vorbereitet…",
presentation: "Präsentation",
presentationControls: "Präsentationssteuerung",
presenterView: "Referentenansicht",
powerPoint: "PowerPoint",
previous: "Zurück",
hideThumbnails: "Folienvorschauen ausblenden",
showThumbnails: "Folienvorschauen anzeigen",
slidePosition: "Folienposition",
slidePreview: "Folienvorschau",
slides: "Folien",
speakerNotes: "Sprechernotizen",
upNext: "Als Nächstes",
goToSlideNumber: "Zu Folie {slideNumber} wechseln",
slideLabel: "Folie {slideNumber} von {slideCount}",
},
es: {
close: "Cerrar",
connected: "Conectado",
currentSlide: "Diapositiva actual",
download: "Descargar",
downloadFailed: "No se pudo completar la descarga.",
elapsedTime: "Tiempo transcurrido",
enterFullscreen: "Activar pantalla completa",
expandedImage: "Imagen ampliada",
next: "Siguiente",
noNotes: "No hay notas para esta diapositiva.",
pdfDocument: "Documento PDF",
startPresentation: "Presentar",
popupBlocked:
"Se bloqueó la ventana del presentador. Permite las ventanas emergentes e inténtalo de nuevo.",
presenter: "Vista del presentador",
preparingDownload: "Preparando la descarga…",
presentation: "Presentación",
presentationControls: "Controles de presentación",
presenterView: "Vista del presentador",
powerPoint: "PowerPoint",
previous: "Anterior",
hideThumbnails: "Ocultar vistas previas",
showThumbnails: "Mostrar vistas previas",
slidePosition: "Posición de la diapositiva",
slidePreview: "Vista previa de la diapositiva",
slides: "Diapositivas",
speakerNotes: "Notas del orador",
upNext: "A continuación",
goToSlideNumber: "Ir a la diapositiva {slideNumber}",
slideLabel: "Diapositiva {slideNumber} de {slideCount}",
},
fr: {
close: "Fermer",
connected: "Connecté",
currentSlide: "Diapositive actuelle",
download: "Télécharger",
downloadFailed: "Échec du téléchargement.",
elapsedTime: "Temps écoulé",
enterFullscreen: "Activer le plein écran",
expandedImage: "Image agrandie",
next: "Suivant",
noNotes: "Aucune note pour cette diapositive.",
pdfDocument: "Document PDF",
startPresentation: "Présenter",
popupBlocked:
"La fenêtre du mode Présentateur a été bloquée. Autorisez les fenêtres contextuelles et réessayez.",
presenter: "Mode Présentateur",
preparingDownload: "Préparation du téléchargement…",
presentation: "Présentation",
presentationControls: "Commandes de présentation",
presenterView: "Mode Présentateur",
powerPoint: "PowerPoint",
previous: "Précédent",
hideThumbnails: "Masquer les aperçus",
showThumbnails: "Afficher les aperçus",
slidePosition: "Position de la diapositive",
slidePreview: "Aperçu de la diapositive",
slides: "Diapositives",
speakerNotes: "Notes du présentateur",
upNext: "À suivre",
goToSlideNumber: "Aller à la diapositive {slideNumber}",
slideLabel: "Diapositive {slideNumber} sur {slideCount}",
},
pt: {
close: "Fechar",
connected: "Conectado",
currentSlide: "Slide atual",
download: "Baixar",
downloadFailed: "Não foi possível baixar o arquivo.",
elapsedTime: "Tempo decorrido",
enterFullscreen: "Entrar em tela cheia",
expandedImage: "Imagem ampliada",
next: "Próximo",
noNotes: "Não há anotações para este slide.",
pdfDocument: "Documento PDF",
startPresentation: "Apresentar",
popupBlocked:
"A janela do modo do apresentador foi bloqueada. Permita pop-ups e tente novamente.",
presenter: "Modo do apresentador",
preparingDownload: "Preparando o download…",
presentation: "Apresentação",
presentationControls: "Controles da apresentação",
presenterView: "Modo do apresentador",
powerPoint: "PowerPoint",
previous: "Anterior",
hideThumbnails: "Ocultar prévias",
showThumbnails: "Mostrar prévias",
slidePosition: "Posição do slide",
slidePreview: "Prévia do slide",
slides: "Slides",
speakerNotes: "Anotações do apresentador",
upNext: "A seguir",
goToSlideNumber: "Ir para o slide {slideNumber}",
slideLabel: "Slide {slideNumber} de {slideCount}",
},
ja: {
close: "閉じる",
connected: "接続済み",
currentSlide: "現在のスライド",
download: "ダウンロード",
downloadFailed: "ダウンロードに失敗しました。",
elapsedTime: "経過時間",
enterFullscreen: "全画面表示にする",
expandedImage: "拡大表示された画像",
next: "次へ",
noNotes: "このスライドにはノートがありません。",
pdfDocument: "PDF ドキュメント",
startPresentation: "プレゼンテーションを開始",
popupBlocked:
"発表者ビューのウィンドウがブロックされました。ポップアップを許可して、もう一度お試しください。",
presenter: "発表者ビュー",
preparingDownload: "ダウンロードの準備中…",
presentation: "プレゼンテーション",
presentationControls: "プレゼンテーションの操作",
presenterView: "発表者ビュー",
powerPoint: "PowerPoint",
previous: "前へ",
hideThumbnails: "スライドのプレビューを非表示",
showThumbnails: "スライドのプレビューを表示",
slidePosition: "スライド番号",
slidePreview: "スライドプレビュー",
slides: "スライド",
speakerNotes: "発表者ノート",
upNext: "次の表示内容",
goToSlideNumber: "{slideNumber}枚目のスライドに移動",
slideLabel: "全{slideCount}枚中{slideNumber}枚目のスライド",
},
ko: {
close: "닫기",
connected: "연결됨",
currentSlide: "현재 슬라이드",
download: "다운로드",
downloadFailed: "다운로드하지 못했습니다.",
elapsedTime: "경과 시간",
enterFullscreen: "전체 화면으로 전환",
expandedImage: "확대된 이미지",
next: "다음",
noNotes: "이 슬라이드에는 노트가 없습니다.",
pdfDocument: "PDF 문서",
startPresentation: "프레젠테이션 시작",
popupBlocked:
"발표자 보기 창이 차단되었습니다. 팝업을 허용한 후 다시 시도하세요.",
presenter: "발표자 보기",
preparingDownload: "다운로드 준비 중…",
presentation: "프레젠테이션",
presentationControls: "프레젠테이션 컨트롤",
presenterView: "발표자 보기",
powerPoint: "PowerPoint",
previous: "이전",
hideThumbnails: "슬라이드 미리보기 숨기기",
showThumbnails: "슬라이드 미리보기 표시",
slidePosition: "슬라이드 번호",
slidePreview: "슬라이드 미리보기",
slides: "슬라이드",
speakerNotes: "발표자 노트",
upNext: "다음",
goToSlideNumber: "{slideNumber}번 슬라이드로 이동",
slideLabel: "전체 {slideCount}장 중 {slideNumber}번째 슬라이드",
},
"zh-CN": {
close: "关闭",
connected: "已连接",
currentSlide: "当前幻灯片",
download: "下载",
downloadFailed: "下载失败。",
elapsedTime: "已用时间",
enterFullscreen: "进入全屏",
expandedImage: "放大后的图片",
next: "下一步",
noNotes: "此幻灯片没有备注。",
pdfDocument: "PDF 文档",
startPresentation: "开始放映",
popupBlocked: "浏览器阻止了演示者视图窗口。请允许弹出式窗口,然后重试。",
presenter: "演示者视图",
preparingDownload: "正在准备下载…",
presentation: "幻灯片放映",
presentationControls: "幻灯片放映控件",
presenterView: "演示者视图",
powerPoint: "PowerPoint",
previous: "上一步",
hideThumbnails: "隐藏幻灯片预览",
showThumbnails: "显示幻灯片预览",
slidePosition: "幻灯片编号",
slidePreview: "幻灯片预览",
slides: "幻灯片",
speakerNotes: "演讲者备注",
upNext: "下一步",
goToSlideNumber: "转到第 {slideNumber} 张幻灯片",
slideLabel: "第 {slideNumber} 张幻灯片,共 {slideCount} 张",
},
"zh-TW": {
close: "關閉",
connected: "已連線",
currentSlide: "目前投影片",
download: "下載",
downloadFailed: "下載失敗。",
elapsedTime: "經過時間",
enterFullscreen: "進入全螢幕",
expandedImage: "放大後的圖片",
next: "下一步",
noNotes: "此投影片沒有備忘稿。",
pdfDocument: "PDF 檔案",
startPresentation: "播放簡報",
popupBlocked: "瀏覽器封鎖了簡報者檢視視窗。請允許彈出式視窗後再試一次。",
presenter: "簡報者",
preparingDownload: "正在準備下載…",
presentation: "投影片放映",
presentationControls: "投影片放映控制項",
presenterView: "簡報者檢視",
powerPoint: "PowerPoint",
previous: "上一步",
hideThumbnails: "隱藏投影片預覽",
showThumbnails: "顯示投影片預覽",
slidePosition: "投影片編號",
slidePreview: "投影片預覽",
slides: "投影片",
speakerNotes: "演講者備忘稿",
upNext: "下一步",
goToSlideNumber: "移至第 {slideNumber} 張投影片",
slideLabel: "第 {slideNumber} 張投影片,共 {slideCount} 張",
},
};
const LocalizationContext = createContext(createMessages(translations.en));
export function LocalizationProvider({
children,
locale,
}: {
children: ReactNode;
locale: SupportedLocale;
}) {
const messages = useMemo(
() => createMessages(translations[locale]),
[locale],
);
return (
<LocalizationContext.Provider value={messages}>
{children}
</LocalizationContext.Provider>
);
}
export function useLocalization(): TranslationMessages {
return useContext(LocalizationContext);
}
function createMessages(strings: TranslationStrings): TranslationMessages {
return {
...strings,
goToSlideNumber: (slideNumber) =>
formatSlideMessage(strings.goToSlideNumber, slideNumber),
slideLabel: (slideNumber, slideCount) =>
formatSlideMessage(strings.slideLabel, slideNumber, slideCount),
};
}
function formatSlideMessage(
template: string,
slideNumber: number,
slideCount?: number,
): string {
return template
.replace("{slideNumber}", String(slideNumber))
.replace(
"{slideCount}",
slideCount === undefined ? "" : String(slideCount),
);
}
+153
View File
@@ -0,0 +1,153 @@
export type NavigationDirection = "forward" | "backward" | "jump";
export interface NavigationState {
slideIndex: number;
revealedBySlide: number[];
direction: NavigationDirection;
}
export type NavigationAction =
| { type: "next"; stepCounts: number[] }
| { type: "previous"; stepCounts: number[] }
| { type: "goTo"; slideIndex: number }
| { type: "syncStepCount"; slideIndex: number; stepCount: number }
| { type: "syncSlides"; slideCount: number; stepCounts: number[] };
export function createNavigationState(slideCount: number): NavigationState {
return {
slideIndex: 0,
revealedBySlide: Array.from({ length: slideCount }, () => 0),
direction: "jump",
};
}
export function navigationReducer(
state: NavigationState,
action: NavigationAction,
): NavigationState {
switch (action.type) {
case "next":
return advance(state, action.stepCounts);
case "previous":
return retreat(state, action.stepCounts);
case "goTo":
return goTo(state, action.slideIndex);
case "syncStepCount":
return syncStepCount(state, action.slideIndex, action.stepCount);
case "syncSlides":
return syncSlides(state, action.slideCount, action.stepCounts);
}
}
function advance(
state: NavigationState,
stepCounts: number[],
): NavigationState {
const stepCount = stepCounts[state.slideIndex] ?? 0;
const revealed = state.revealedBySlide[state.slideIndex] ?? 0;
if (revealed < stepCount) {
return {
...state,
revealedBySlide: replaceAt(
state.revealedBySlide,
state.slideIndex,
revealed + 1,
),
direction: "forward",
};
}
if (state.slideIndex >= state.revealedBySlide.length - 1) {
return state;
}
return {
...state,
slideIndex: state.slideIndex + 1,
revealedBySlide: replaceAt(state.revealedBySlide, state.slideIndex + 1, 0),
direction: "forward",
};
}
function retreat(
state: NavigationState,
stepCounts: number[],
): NavigationState {
const revealed = state.revealedBySlide[state.slideIndex] ?? 0;
if (revealed > 0) {
return {
...state,
revealedBySlide: replaceAt(
state.revealedBySlide,
state.slideIndex,
revealed - 1,
),
direction: "backward",
};
}
if (state.slideIndex === 0) {
return state;
}
const previousIndex = state.slideIndex - 1;
return {
...state,
slideIndex: previousIndex,
revealedBySlide: replaceAt(
state.revealedBySlide,
previousIndex,
stepCounts[previousIndex] ?? 0,
),
direction: "backward",
};
}
function goTo(state: NavigationState, slideIndex: number): NavigationState {
const maxIndex = Math.max(0, state.revealedBySlide.length - 1);
const target = Math.max(0, Math.min(maxIndex, Math.trunc(slideIndex)));
return {
...state,
slideIndex: target,
revealedBySlide: replaceAt(state.revealedBySlide, target, 0),
direction: "jump",
};
}
function syncStepCount(
state: NavigationState,
slideIndex: number,
stepCount: number,
): NavigationState {
const revealed = state.revealedBySlide[slideIndex];
if (revealed === undefined || revealed <= stepCount) {
return state;
}
return {
...state,
revealedBySlide: replaceAt(state.revealedBySlide, slideIndex, stepCount),
};
}
function syncSlides(
state: NavigationState,
slideCount: number,
stepCounts: number[],
): NavigationState {
const revealedBySlide = Array.from({ length: slideCount }, (_, index) =>
Math.min(state.revealedBySlide[index] ?? 0, stepCounts[index] ?? 0),
);
return {
...state,
slideIndex: Math.min(state.slideIndex, slideCount - 1),
revealedBySlide,
};
}
function replaceAt(values: number[], index: number, value: number): number[] {
const next = [...values];
next[index] = value;
return next;
}
+142
View File
@@ -0,0 +1,142 @@
import {
createElement,
Fragment,
isValidElement,
type CSSProperties,
type ReactElement,
type ReactNode,
} from "react";
import { Notes, type NotesProps } from "./Notes";
import {
Slide,
type SlideDefinition,
type SlideProps,
type SlideTransition,
} from "./Slide";
interface PendingSlide {
content: ReactNode[];
notes: ReactNode[];
className?: string;
style?: CSSProperties;
staticAssets: string[];
transition?: SlideTransition;
}
export function normalizeDeck(children: ReactNode): SlideDefinition[] {
const slides: PendingSlide[] = [];
let looseContent: ReactNode[] = [];
const flushLooseContent = () => {
if (looseContent.length > 0) {
slides.push(toPendingSlide(looseContent));
looseContent = [];
}
};
for (const child of flattenFragments(children)) {
if (isSlideElement(child)) {
flushLooseContent();
slides.push(toPendingSlide(child.props.children, child.props));
} else {
looseContent.push(child);
}
}
flushLooseContent();
if (slides.length === 0) {
slides.push(toPendingSlide([]));
}
return slides.map((slide, index) => ({
id: `slide-${index + 1}`,
content: wrapNodes(slide.content, "content"),
notes: slide.notes.length > 0 ? wrapNodes(slide.notes, "notes") : null,
className: slide.className,
style: slide.style,
staticAssets: slide.staticAssets,
transition: slide.transition,
}));
}
function toPendingSlide(children: ReactNode, props?: SlideProps): PendingSlide {
const content: ReactNode[] = [];
const notes: ReactNode[] = [];
const style = props?.style;
const staticAssets = props?.staticAssets;
for (const child of flattenFragments(children)) {
if (isNotesElement(child)) {
notes.push(...flattenFragments(child.props.children));
} else {
content.push(child);
}
}
return {
content,
notes,
className:
typeof props?.className === "string" ? props.className : undefined,
style: isStyle(style) ? style : undefined,
staticAssets: Array.isArray(staticAssets)
? staticAssets.filter(
(asset): asset is string => typeof asset === "string",
)
: [],
transition: normalizeSlideTransition(props?.transition),
};
}
function normalizeSlideTransition(value: unknown): SlideTransition | undefined {
return value === "fade" || value === "slide" || value === "none"
? value
: undefined;
}
function flattenFragments(children: ReactNode): ReactNode[] {
const flattened: ReactNode[] = [];
visit(children, flattened);
return flattened;
}
function visit(node: ReactNode, flattened: ReactNode[]): void {
if (Array.isArray(node)) {
for (const child of node) {
visit(child, flattened);
}
return;
}
if (
isValidElement<{ children?: ReactNode }>(node) &&
node.type === Fragment
) {
visit(node.props.children, flattened);
return;
}
if (
typeof node === "string" ||
typeof node === "number" ||
isValidElement(node)
) {
flattened.push(node);
}
}
function isSlideElement(node: ReactNode): node is ReactElement<SlideProps> {
return isValidElement<SlideProps>(node) && node.type === Slide;
}
function isNotesElement(node: ReactNode): node is ReactElement<NotesProps> {
return isValidElement<NotesProps>(node) && node.type === Notes;
}
function isStyle(value: unknown): value is CSSProperties {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function wrapNodes(nodes: ReactNode[], prefix: string): ReactNode[] {
return nodes.map((node, index) =>
createElement(Fragment, { key: `${prefix}-${index + 1}` }, node),
);
}
+23
View File
@@ -0,0 +1,23 @@
import { useEffect } from "react";
import { shared, useCollaborators, type Collaborator } from "@kits/sync";
/** Tells everyone else which slide this viewer is on, by its number, for as long as the deck is open. */
export function useAnnounceSlide(slideNumber: number): void {
useEffect(() => {
shared.me.setPresence((current) => ({ ...current, slide: slideNumber }));
return () => {
shared.me.setPresence(({ slide: _, ...rest }) => rest);
};
}, [slideNumber]);
}
/** Everyone else on a slide, as their users; stable while nobody arrives or leaves. */
export function useViewersOfSlide(
slideNumber: number,
): Array<Collaborator["user"]> {
return useCollaborators((all) =>
all
.filter((collaborator) => collaborator.presence.slide === slideNumber)
.map((collaborator) => collaborator.user),
);
}
@@ -0,0 +1,250 @@
import {
type Dispatch,
type RefObject,
useCallback,
useEffect,
useRef,
} from "react";
import { flushSync } from "react-dom";
import {
type NavigationAction,
type NavigationState,
navigationReducer,
} from "./navigationReducer";
import type { SlideDefinition } from "./Slide";
import {
animateSlideTransition,
resolveSlideTransition,
STAGE_VIEW_TRANSITION_NAME,
type ResolvedSlideTransition,
type SlideTransitionDirection,
} from "../render/slideTransitions";
export type NavigationIntent =
| { type: "next" }
| { type: "previous" }
| { type: "goTo"; slideIndex: number };
interface SlideTransitionCoordinatorOptions {
dispatch: Dispatch<NavigationAction>;
getStepCounts: () => number[];
rootRef: RefObject<HTMLDivElement | null>;
slides: SlideDefinition[];
state: NavigationState;
}
const TRANSITION_ACTIVE_ATTRIBUTE = "slideKitTransition";
const SUPPRESS_HEROES_ATTRIBUTE = "slideTransitionSuppressHeroes";
const DURATION_PROPERTY = "--slide-kit-transition-duration";
const EASING_PROPERTY = "--slide-kit-transition-easing";
export function useSlideTransitionCoordinator({
dispatch,
getStepCounts,
rootRef,
slides,
state,
}: SlideTransitionCoordinatorOptions): Dispatch<NavigationIntent> {
const activeTransitionRef = useRef<ViewTransition | null>(null);
const mountedRef = useRef(true);
const pendingIntentsRef = useRef<NavigationIntent[]>([]);
const processNextRef = useRef<(() => void) | null>(null);
const skipRequestedRef = useRef<ViewTransition | null>(null);
const slidesRef = useRef(slides);
const stateRef = useRef(state);
slidesRef.current = slides;
stateRef.current = state;
const requestActiveTransitionSkip = useCallback(() => {
const transition = activeTransitionRef.current;
if (!transition || skipRequestedRef.current === transition) {
return;
}
skipRequestedRef.current = transition;
const skip = () => {
if (activeTransitionRef.current === transition) {
transition.skipTransition();
}
};
void transition.updateCallbackDone.then(skip, skip);
}, []);
const scheduleNext = useCallback(() => {
requestAnimationFrame(() => processNextRef.current?.());
}, []);
processNextRef.current = () => {
if (!mountedRef.current || activeTransitionRef.current) {
return;
}
const intent = pendingIntentsRef.current.shift()!;
const currentState = stateRef.current;
const action = toNavigationAction(intent, getStepCounts());
const nextState = navigationReducer(currentState, action);
if (nextState.slideIndex === currentState.slideIndex) {
stateRef.current = nextState;
dispatch(action);
if (pendingIntentsRef.current.length > 0) {
scheduleNext();
}
return;
}
const root = rootRef.current;
const stage = root?.querySelector(
'[data-slide-surface="stage"], [data-slide-surface="presentation"]',
);
const startViewTransition =
typeof document.startViewTransition === "function"
? document.startViewTransition.bind(document)
: undefined;
if (!root || !stage || !startViewTransition) {
stateRef.current = nextState;
dispatch(action);
if (pendingIntentsRef.current.length > 0) {
scheduleNext();
}
return;
}
const jump = nextState.direction === "jump";
const direction: SlideTransitionDirection =
nextState.direction === "backward" ? "backward" : "forward";
const boundarySlide =
direction === "backward"
? slidesRef.current[currentState.slideIndex]
: slidesRef.current[nextState.slideIndex];
const resolvedTransition = resolveSlideTransition(
jump ? "fade" : boundarySlide?.transition,
direction,
);
setDocumentTransitionState(resolvedTransition);
setHeroSuppression(root, jump || hasConflictingHeroNames(root));
const transition = startViewTransition(() => {
stateRef.current = nextState;
flushSync(() => dispatch(action));
if (hasConflictingHeroNames(root)) {
setHeroSuppression(root, true);
}
});
activeTransitionRef.current = transition;
void transition.ready.then(
() => {
if (activeTransitionRef.current !== transition) {
return;
}
setHeroSuppression(root, false);
animateSlideTransition(resolvedTransition);
},
() => setHeroSuppression(root, false),
);
const finish = () => {
if (activeTransitionRef.current !== transition) {
return;
}
activeTransitionRef.current = null;
skipRequestedRef.current = null;
clearDocumentTransitionState();
setHeroSuppression(root, false);
if (pendingIntentsRef.current.length > 0) {
scheduleNext();
}
};
void transition.finished.then(finish, finish);
if (pendingIntentsRef.current.length > 0) {
requestActiveTransitionSkip();
}
};
const dispatchIntent = useCallback(
(intent: NavigationIntent) => {
pendingIntentsRef.current.push(intent);
if (activeTransitionRef.current) {
requestActiveTransitionSkip();
} else {
processNextRef.current?.();
}
},
[requestActiveTransitionSkip],
);
useEffect(() => {
mountedRef.current = true;
return () => {
mountedRef.current = false;
pendingIntentsRef.current = [];
activeTransitionRef.current?.skipTransition();
activeTransitionRef.current = null;
clearDocumentTransitionState();
const root = rootRef.current;
if (root) {
setHeroSuppression(root, false);
}
};
}, [rootRef]);
return dispatchIntent;
}
function toNavigationAction(
intent: NavigationIntent,
stepCounts: number[],
): NavigationAction {
switch (intent.type) {
case "next":
case "previous":
return { type: intent.type, stepCounts };
case "goTo":
return intent;
}
}
function setDocumentTransitionState(transition: ResolvedSlideTransition): void {
const root = document.documentElement;
root.dataset[TRANSITION_ACTIVE_ATTRIBUTE] = "";
root.style.setProperty(DURATION_PROPERTY, `${transition.durationMs}ms`);
root.style.setProperty(EASING_PROPERTY, transition.easing);
}
function clearDocumentTransitionState(): void {
const root = document.documentElement;
delete root.dataset[TRANSITION_ACTIVE_ATTRIBUTE];
root.style.removeProperty(DURATION_PROPERTY);
root.style.removeProperty(EASING_PROPERTY);
}
function setHeroSuppression(root: HTMLElement, suppressed: boolean): void {
if (suppressed) {
root.dataset[SUPPRESS_HEROES_ATTRIBUTE] = "";
} else {
delete root.dataset[SUPPRESS_HEROES_ATTRIBUTE];
}
}
function hasConflictingHeroNames(root: HTMLElement): boolean {
const names = new Set([STAGE_VIEW_TRANSITION_NAME]);
const elements = root.querySelectorAll(
'[data-slide-surface="stage"] .slide-kit-slide, ' +
'[data-slide-surface="stage"] .slide-kit-slide *, ' +
'[data-slide-surface="presentation"] .slide-kit-slide, ' +
'[data-slide-surface="presentation"] .slide-kit-slide *',
);
for (const element of Array.from(elements)) {
const name = getComputedStyle(element).getPropertyValue(
"view-transition-name",
);
if (!name || name === "none") {
continue;
}
if (names.has(name)) {
return true;
}
names.add(name);
}
return false;
}
+1
View File
@@ -0,0 +1 @@
declare module "*.css";
+181
View File
@@ -0,0 +1,181 @@
import {
createContext,
type ReactNode,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
useState,
} from "react";
import type { SlideDefinition } from "../core/Slide";
import { StaticDeck } from "../render/StaticDeck";
import type { StaticReadyDetail } from "../render/staticReadiness";
import { downloadPdf } from "./pdfDownload";
import { downloadPptx } from "./pptxDownload";
export type DeckDownloadFormat = "pdf" | "pptx";
export interface DeckDownloadOptions {
filename?: string;
readinessTimeoutMs?: number;
}
export interface DeckDownloads {
downloadDeck: (
format: DeckDownloadFormat,
options?: DeckDownloadOptions,
) => Promise<void>;
downloadPdf: (options?: DeckDownloadOptions) => Promise<void>;
downloadPptx: (options?: DeckDownloadOptions) => Promise<void>;
}
interface SnapshotRequest {
operation: (root: HTMLElement) => Promise<void>;
readinessTimeoutMs?: number;
resolve: () => void;
reject: (error: unknown) => void;
started: boolean;
}
const DeckDownloadsContext = createContext<DeckDownloads | null>(null);
export function DeckDownloadProvider({
children,
slides,
}: {
children: ReactNode;
slides: SlideDefinition[];
}) {
const requestRef = useRef<SnapshotRequest | null>(null);
const [request, setRequest] = useState<SnapshotRequest | null>(null);
const finishRequest = useCallback(
(finishedRequest: SnapshotRequest, error?: unknown) => {
if (requestRef.current !== finishedRequest) {
return;
}
requestRef.current = null;
setRequest(null);
if (error === undefined) {
finishedRequest.resolve();
} else {
finishedRequest.reject(error);
}
},
[],
);
const handleReadiness = useCallback(
(root: HTMLElement, detail: StaticReadyDetail) => {
const activeRequest = requestRef.current;
if (!activeRequest || activeRequest.started) {
return;
}
if (detail.status === "error") {
finishRequest(
activeRequest,
new Error(
detail.error ?? "Slides could not be prepared for download.",
),
);
return;
}
activeRequest.started = true;
activeRequest.operation(root).then(
() => finishRequest(activeRequest),
(error: unknown) => finishRequest(activeRequest, error),
);
},
[finishRequest],
);
const runWithStaticDeck = useCallback(
(
operation: (root: HTMLElement) => Promise<void>,
readinessTimeoutMs?: number,
): Promise<void> => {
if (typeof document === "undefined") {
return Promise.reject(
new Error("Slide downloads are only available in a browser."),
);
}
if (requestRef.current) {
return Promise.reject(
new Error("A slide download is already in progress."),
);
}
return new Promise((resolve, reject) => {
const nextRequest: SnapshotRequest = {
operation,
readinessTimeoutMs,
resolve,
reject,
started: false,
};
requestRef.current = nextRequest;
setRequest(nextRequest);
});
},
[],
);
useEffect(
() => () => {
const activeRequest = requestRef.current;
requestRef.current = null;
activeRequest?.reject(
new Error("Slide download was cancelled because the deck unmounted."),
);
},
[],
);
const value = useMemo<DeckDownloads>(() => {
const downloadDeck = (
format: DeckDownloadFormat,
options: DeckDownloadOptions = {},
) =>
runWithStaticDeck((root) => {
if (format === "pdf") {
return downloadPdf(root, options);
}
return downloadPptx(root, options);
}, options.readinessTimeoutMs);
return {
downloadDeck,
downloadPdf: (options) => downloadDeck("pdf", options),
downloadPptx: (options) => downloadDeck("pptx", options),
};
}, [runWithStaticDeck]);
return (
<DeckDownloadsContext.Provider value={value}>
{children}
{request ? (
<div
aria-hidden="true"
className="slide-kit-download-snapshot"
data-slide-download-snapshot
>
<StaticDeck
slides={slides}
readinessTimeoutMs={request.readinessTimeoutMs}
onReadiness={handleReadiness}
/>
</div>
) : null}
</DeckDownloadsContext.Provider>
);
}
export function useDeckDownloads(): DeckDownloads {
const value = useContext(DeckDownloadsContext);
if (!value) {
throw new Error("Slide kit hooks must be used inside Deck.");
}
return value;
}
@@ -0,0 +1,19 @@
type DownloadExtension = "pdf" | "pptx";
export function resolveDownloadFilename(
requestedName: string | undefined,
extension: DownloadExtension,
): string {
const documentTitle =
typeof document === "undefined" ? "" : document.title.trim();
const fallback = documentTitle || "slides";
const withoutExtension = (requestedName?.trim() || fallback).replace(
/\.(?:pdf|pptx)$/i,
"",
);
const sanitized = withoutExtension
.replace(/[\u0000-\u001f<>:"/\\|?*]+/g, "-")
.replace(/[.\s]+$/g, "")
.trim();
return `${sanitized || "slides"}.${extension}`;
}
+11
View File
@@ -0,0 +1,11 @@
export function downloadBlob(blob: Blob, filename: string): void {
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = filename;
anchor.rel = "noopener";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 0);
}
+73
View File
@@ -0,0 +1,73 @@
import { resolveDownloadFilename } from "./downloadFilename";
interface PdfDownloadOptions {
filename?: string;
}
const PRINT_ROOT_ID = "slide-kit-print-root";
const PRINT_STYLE_ID = "slide-kit-print-style";
export async function downloadPdf(
staticRoot: HTMLElement,
{ filename }: PdfDownloadOptions = {},
): Promise<void> {
const existingRoot = document.getElementById(PRINT_ROOT_ID);
if (existingRoot) {
throw new Error("A slide PDF download is already in progress.");
}
const sourceDeckRoot = staticRoot.closest<HTMLElement>(".slide-kit-root");
const printRoot = document.createElement("div");
printRoot.id = PRINT_ROOT_ID;
printRoot.className = sourceDeckRoot?.className ?? "slide-kit-root";
printRoot.dataset.theme = sourceDeckRoot?.dataset.theme ?? "light";
if (sourceDeckRoot?.hasAttribute("style")) {
printRoot.setAttribute("style", sourceDeckRoot.getAttribute("style")!);
}
printRoot.appendChild(staticRoot.cloneNode(true));
const style = document.createElement("style");
style.id = PRINT_STYLE_ID;
style.textContent = `
@page { size: 1920px 1080px; margin: 0; }
@media screen {
#${PRINT_ROOT_ID} { position: fixed !important; left: -100000px !important; top: 0 !important; pointer-events: none !important; }
}
@media print {
html, body { width: 1920px !important; height: auto !important; margin: 0 !important; padding: 0 !important; background: #fff !important; }
body > *:not(#${PRINT_ROOT_ID}) { display: none !important; }
#${PRINT_ROOT_ID} { display: block !important; width: 1920px !important; height: auto !important; min-height: 0 !important; margin: 0 !important; background: #fff !important; }
#${PRINT_ROOT_ID} .slide-kit-static-page { width: 1920px !important; height: 1080px !important; overflow: hidden !important; break-after: page !important; page-break-after: always !important; print-color-adjust: exact; -webkit-print-color-adjust: exact; }
#${PRINT_ROOT_ID} .slide-kit-static-page:last-child { break-after: auto !important; page-break-after: auto !important; }
}`;
const previousTitle = document.title;
document.title = resolveDownloadFilename(filename, "pdf").replace(
/\.pdf$/i,
"",
);
document.head.appendChild(style);
document.body.appendChild(printRoot);
try {
const printed = waitForAfterPrint();
window.print();
await printed;
} finally {
document.title = previousTitle;
printRoot.remove();
style.remove();
}
}
function waitForAfterPrint(timeoutMs = 60_000): Promise<void> {
return new Promise((resolve) => {
const finish = () => {
window.removeEventListener("afterprint", finish);
window.clearTimeout(timeout);
resolve();
};
const timeout = window.setTimeout(finish, timeoutMs);
window.addEventListener("afterprint", finish, { once: true });
});
}
+116
View File
@@ -0,0 +1,116 @@
import { zipSync, strToU8 } from "fflate";
const EMU_WIDTH = 12_192_000;
const EMU_HEIGHT = 6_858_000;
const XML_DECLARATION =
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n';
const RELATIONSHIPS_NAMESPACE =
"http://schemas.openxmlformats.org/package/2006/relationships";
const OFFICE_RELATIONSHIPS_NAMESPACE =
"http://schemas.openxmlformats.org/officeDocument/2006/relationships";
export function buildImagePptx(images: readonly Uint8Array[]): Uint8Array {
if (images.length === 0) {
throw new Error("A PowerPoint download requires at least one slide.");
}
const files: Record<string, Uint8Array> = {
"[Content_Types].xml": strToU8(contentTypesXml(images.length)),
"_rels/.rels": strToU8(rootRelationshipsXml()),
"ppt/presentation.xml": strToU8(presentationXml(images.length)),
"ppt/_rels/presentation.xml.rels": strToU8(
presentationRelationshipsXml(images.length),
),
"ppt/presProps.xml": strToU8(presentationPropertiesXml()),
"ppt/theme/theme1.xml": strToU8(themeXml()),
"ppt/slideMasters/slideMaster1.xml": strToU8(slideMasterXml()),
"ppt/slideMasters/_rels/slideMaster1.xml.rels": strToU8(
slideMasterRelationshipsXml(),
),
"ppt/slideLayouts/slideLayout1.xml": strToU8(slideLayoutXml()),
"ppt/slideLayouts/_rels/slideLayout1.xml.rels": strToU8(
slideLayoutRelationshipsXml(),
),
};
images.forEach((image, index) => {
const slideNumber = index + 1;
files[`ppt/slides/slide${slideNumber}.xml`] = strToU8(slideXml());
files[`ppt/slides/_rels/slide${slideNumber}.xml.rels`] = strToU8(
slideRelationshipsXml(slideNumber),
);
files[`ppt/media/image${slideNumber}.png`] = image;
});
return zipSync(files);
}
function contentTypesXml(slideCount: number): string {
const slides = Array.from(
{ length: slideCount },
(_, index) =>
`<Override PartName="/ppt/slides/slide${index + 1}.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slide+xml"/>`,
).join("");
return `${XML_DECLARATION}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="png" ContentType="image/png"/><Override PartName="/ppt/presentation.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml"/><Override PartName="/ppt/presProps.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.presProps+xml"/><Override PartName="/ppt/slideMasters/slideMaster1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml"/><Override PartName="/ppt/slideLayouts/slideLayout1.xml" ContentType="application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml"/><Override PartName="/ppt/theme/theme1.xml" ContentType="application/vnd.openxmlformats-officedocument.theme+xml"/>${slides}</Types>`;
}
function rootRelationshipsXml(): string {
return `${XML_DECLARATION}<Relationships xmlns="${RELATIONSHIPS_NAMESPACE}"><Relationship Id="rId1" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/officeDocument" Target="ppt/presentation.xml"/></Relationships>`;
}
function presentationXml(slideCount: number): string {
const slides = Array.from(
{ length: slideCount },
(_, index) => `<p:sldId id="${256 + index}" r:id="rId${index + 3}"/>`,
).join("");
return `${XML_DECLARATION}<p:presentation xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="${OFFICE_RELATIONSHIPS_NAMESPACE}" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:sldMasterIdLst><p:sldMasterId id="2147483648" r:id="rId1"/></p:sldMasterIdLst><p:sldIdLst>${slides}</p:sldIdLst><p:sldSz cx="${EMU_WIDTH}" cy="${EMU_HEIGHT}"/><p:notesSz cx="6858000" cy="9144000"/></p:presentation>`;
}
function presentationRelationshipsXml(slideCount: number): string {
const relationships = [
`<Relationship Id="rId1" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/slideMaster" Target="slideMasters/slideMaster1.xml"/>`,
`<Relationship Id="rId2" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/presProps" Target="presProps.xml"/>`,
];
for (let index = 0; index < slideCount; index += 1) {
relationships.push(
`<Relationship Id="rId${index + 3}" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/slide" Target="slides/slide${index + 1}.xml"/>`,
);
}
return `${XML_DECLARATION}<Relationships xmlns="${RELATIONSHIPS_NAMESPACE}">${relationships.join("")}</Relationships>`;
}
function presentationPropertiesXml(): string {
return `${XML_DECLARATION}<p:presentationPr xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="${OFFICE_RELATIONSHIPS_NAMESPACE}" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"/>`;
}
function slideMasterXml(): string {
return `${XML_DECLARATION}<p:sldMaster xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="${OFFICE_RELATIONSHIPS_NAMESPACE}" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr></p:spTree></p:cSld><p:clrMap bg1="lt1" tx1="dk1" bg2="lt2" tx2="dk2" accent1="accent1" accent2="accent2" accent3="accent3" accent4="accent4" accent5="accent5" accent6="accent6" hlink="hlink" folHlink="folHlink"/><p:sldLayoutIdLst><p:sldLayoutId id="2147483649" r:id="rId1"/></p:sldLayoutIdLst></p:sldMaster>`;
}
function slideMasterRelationshipsXml(): string {
return `${XML_DECLARATION}<Relationships xmlns="${RELATIONSHIPS_NAMESPACE}"><Relationship Id="rId1" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/slideLayout" Target="../slideLayouts/slideLayout1.xml"/><Relationship Id="rId2" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/theme" Target="../theme/theme1.xml"/></Relationships>`;
}
function slideLayoutXml(): string {
return `${XML_DECLARATION}<p:sldLayout xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="${OFFICE_RELATIONSHIPS_NAMESPACE}" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main" type="blank" preserve="1"><p:cSld name="Blank"><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr></p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sldLayout>`;
}
function slideLayoutRelationshipsXml(): string {
return `${XML_DECLARATION}<Relationships xmlns="${RELATIONSHIPS_NAMESPACE}"><Relationship Id="rId1" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/slideMaster" Target="../slideMasters/slideMaster1.xml"/></Relationships>`;
}
function slideXml(): string {
return `${XML_DECLARATION}<p:sld xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:r="${OFFICE_RELATIONSHIPS_NAMESPACE}" xmlns:p="http://schemas.openxmlformats.org/presentationml/2006/main"><p:cSld><p:spTree><p:nvGrpSpPr><p:cNvPr id="1" name=""/><p:cNvGrpSpPr/><p:nvPr/></p:nvGrpSpPr><p:grpSpPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="0" cy="0"/><a:chOff x="0" y="0"/><a:chExt cx="0" cy="0"/></a:xfrm></p:grpSpPr><p:pic><p:nvPicPr><p:cNvPr id="2" name="Slide"/><p:cNvPicPr><a:picLocks noChangeAspect="1"/></p:cNvPicPr><p:nvPr/></p:nvPicPr><p:blipFill><a:blip r:embed="rId2"/><a:stretch><a:fillRect/></a:stretch></p:blipFill><p:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${EMU_WIDTH}" cy="${EMU_HEIGHT}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></p:spPr></p:pic></p:spTree></p:cSld><p:clrMapOvr><a:masterClrMapping/></p:clrMapOvr></p:sld>`;
}
function slideRelationshipsXml(slideNumber: number): string {
return `${XML_DECLARATION}<Relationships xmlns="${RELATIONSHIPS_NAMESPACE}"><Relationship Id="rId1" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/slideLayout" Target="../slideLayouts/slideLayout1.xml"/><Relationship Id="rId2" Type="${OFFICE_RELATIONSHIPS_NAMESPACE}/image" Target="../media/image${slideNumber}.png"/></Relationships>`;
}
function themeXml(): string {
const solidFill = '<a:solidFill><a:schemeClr val="phClr"/></a:solidFill>';
const line = (width: number) =>
`<a:ln w="${width}" cap="flat" cmpd="sng" algn="ctr">${solidFill}<a:prstDash val="solid"/></a:ln>`;
const effect = "<a:effectStyle><a:effectLst/></a:effectStyle>";
return `${XML_DECLARATION}<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Slide Kit"><a:themeElements><a:clrScheme name="Slide Kit"><a:dk1><a:sysClr val="windowText" lastClr="000000"/></a:dk1><a:lt1><a:sysClr val="window" lastClr="FFFFFF"/></a:lt1><a:dk2><a:srgbClr val="202124"/></a:dk2><a:lt2><a:srgbClr val="F4F5F7"/></a:lt2><a:accent1><a:srgbClr val="5B5BD6"/></a:accent1><a:accent2><a:srgbClr val="ED7D31"/></a:accent2><a:accent3><a:srgbClr val="A5A5A5"/></a:accent3><a:accent4><a:srgbClr val="FFC000"/></a:accent4><a:accent5><a:srgbClr val="5B9BD5"/></a:accent5><a:accent6><a:srgbClr val="70AD47"/></a:accent6><a:hlink><a:srgbClr val="0563C1"/></a:hlink><a:folHlink><a:srgbClr val="954F72"/></a:folHlink></a:clrScheme><a:fontScheme name="Slide Kit"><a:majorFont><a:latin typeface="Arial"/><a:ea typeface=""/><a:cs typeface=""/></a:majorFont><a:minorFont><a:latin typeface="Arial"/><a:ea typeface=""/><a:cs typeface=""/></a:minorFont></a:fontScheme><a:fmtScheme name="Slide Kit"><a:fillStyleLst>${solidFill}${solidFill}${solidFill}</a:fillStyleLst><a:lnStyleLst>${line(6350)}${line(12700)}${line(19050)}</a:lnStyleLst><a:effectStyleLst>${effect}${effect}${effect}</a:effectStyleLst><a:bgFillStyleLst>${solidFill}${solidFill}${solidFill}</a:bgFillStyleLst></a:fmtScheme></a:themeElements></a:theme>`;
}
+88
View File
@@ -0,0 +1,88 @@
import { CANVAS_HEIGHT, CANVAS_WIDTH } from "../render/CanvasScaler";
import { resolveDownloadFilename } from "./downloadFilename";
import { downloadBlob } from "./fileDownload";
import { buildImagePptx } from "./pptxArchive";
interface PptxDownloadOptions {
filename?: string;
}
const CAPTURE_STYLE_ID = "slide-kit-pptx-capture-style";
const FROZEN_PROPERTIES = [
"opacity",
"transform",
"filter",
"clip-path",
] as const;
export async function downloadPptx(
staticRoot: HTMLElement,
{ filename }: PptxDownloadOptions = {},
): Promise<void> {
const pages = Array.from(
staticRoot.querySelectorAll<HTMLElement>("[data-slide-static-page]"),
);
if (pages.length === 0) {
throw new Error("A PowerPoint download requires at least one slide.");
}
const captureStyle = document.createElement("style");
captureStyle.id = CAPTURE_STYLE_ID;
captureStyle.textContent = `
[data-slide-download-snapshot] *, [data-slide-download-snapshot] *::before, [data-slide-download-snapshot] *::after {
animation-delay: -1s !important;
animation-duration: 1ms !important;
animation-iteration-count: 1 !important;
animation-fill-mode: forwards !important;
transition: none !important;
}`;
document.head.appendChild(captureStyle);
try {
const { toBlob } = await import("html-to-image");
const images: Uint8Array[] = [];
for (const [index, page] of pages.entries()) {
freezeForCapture(page);
const blob = await toBlob(page, {
width: CANVAS_WIDTH,
height: CANVAS_HEIGHT,
pixelRatio: 2,
backgroundColor: "#ffffff",
cacheBust: true,
});
if (!blob) {
throw new Error(`Failed to capture slide ${index + 1}.`);
}
images.push(new Uint8Array(await blob.arrayBuffer()));
}
const archive = buildImagePptx(images);
downloadBlob(
new Blob([archive as BlobPart], {
type: "application/vnd.openxmlformats-officedocument.presentationml.presentation",
}),
resolveDownloadFilename(filename, "pptx"),
);
} finally {
captureStyle.remove();
}
}
function freezeForCapture(root: HTMLElement): void {
const elements = [
root,
...Array.from(root.querySelectorAll<HTMLElement>("*")),
];
for (const element of elements) {
const computedStyle = getComputedStyle(element);
for (const property of FROZEN_PROPERTIES) {
element.style.setProperty(
property,
computedStyle.getPropertyValue(property),
"important",
);
}
element.style.setProperty("animation", "none", "important");
element.style.setProperty("transition", "none", "important");
}
}
File diff suppressed because it is too large Load Diff
+34
View File
@@ -0,0 +1,34 @@
import type {} from "react";
export interface ViewTransitionStyle {
viewTransitionName?: string;
}
declare module "react" {
interface CSSProperties extends ViewTransitionStyle {}
}
export type { DeckCursors, DeckProps } from "./core/Deck";
export { Deck } from "./core/Deck";
export type { SlideNavigation } from "./core/deckContext";
export {
useSlideCount,
useSlideNavigation,
useSlideNumber,
} from "./core/deckContext";
export type { NotesProps } from "./core/Notes";
export { Notes } from "./core/Notes";
export type { SupportedLocale } from "./core/locale";
export type { SlideTransition, SlideProps } from "./core/Slide";
export { Slide } from "./core/Slide";
export type { SlideStepsState, StepProps, StepState } from "./core/Step";
export { Step, useSlideSteps, useStep } from "./core/Step";
export type {
DeckDownloadFormat,
DeckDownloadOptions,
DeckDownloads,
} from "./download/deckDownloads";
export { useDeckDownloads } from "./download/deckDownloads";
export { CANVAS_HEIGHT, CANVAS_WIDTH } from "./render/CanvasScaler";
export type { StaticReadyDetail } from "./render/staticReadiness";
export { STATIC_READY_EVENT } from "./render/staticReadiness";
+376
View File
@@ -0,0 +1,376 @@
import { type ReactNode, useEffect, useMemo, useState } from "react";
import { SlidePositionProvider, useDeckContext } from "../core/deckContext";
import {
handleKeyboardNavigation,
shouldIgnoreKeyboardEvent,
} from "../core/keyboardNavigation";
import { useLocalization } from "../core/localization";
import type { SlideDefinition } from "../core/Slide";
import { StepRegistry } from "../core/Step";
import { CanvasScaler } from "../render/CanvasScaler";
import { ControlButton } from "../render/ControlButton";
import { ControlIcon } from "../render/ControlIcon";
import { PresentationInteractionSurface } from "../render/PresentationInteractionLayer";
import type { PresentationInteractionController } from "../render/presentationInteraction";
import { SlideFrame } from "../render/SlideFrame";
export function PresenterMode({
controller,
presenterWindow,
slides,
startedAt,
}: {
controller: PresentationInteractionController;
presenterWindow: Window;
slides: SlideDefinition[];
startedAt: number;
}) {
const deck = useDeckContext();
const messages = useLocalization();
const [slideGridOpen, setSlideGridOpen] = useState(false);
usePresenterKeyboard({
enabled: !slideGridOpen,
first: () => deck.goToSlide(1),
last: () => deck.goToSlide(deck.slideCount),
next: deck.next,
presenterWindow,
previous: deck.previous,
});
const slideIndex = Math.min(Math.max(0, deck.slideIndex), slides.length - 1);
const current = slides[slideIndex]!;
const revealed = deck.revealedBySlide[slideIndex] ?? 0;
const stepCount = deck.stepCounts[slideIndex] ?? 0;
const hasNextStep = revealed < stepCount;
const nextSlideIndex = hasNextStep ? slideIndex : slideIndex + 1;
const next = slides[nextSlideIndex] ?? null;
const nextRevealed = hasNextStep ? revealed + 1 : 0;
const hasPreviousStep = revealed > 0;
const previousSlideIndex = hasPreviousStep ? slideIndex : slideIndex - 1;
const previous = slides[previousSlideIndex] ?? null;
const previousRevealed = hasPreviousStep
? revealed - 1
: (deck.stepCounts[previousSlideIndex] ?? Number.MAX_SAFE_INTEGER);
const previousDisabled = slideIndex === 0 && revealed === 0;
const nextDisabled =
slideIndex === deck.slideCount - 1 && revealed >= stepCount;
return (
<main className="slide-kit-presenter">
<PresenterHeader />
<div className="slide-kit-presenter-workspace">
<section className="slide-kit-presenter-current-panel">
<PresentationInteractionSurface
className="slide-kit-presenter-current"
role="region"
aria-label={messages.currentSlide}
controller={controller}
expandedImageLabel={messages.expandedImage}
slideIndex={slideIndex}
>
<CanvasScaler fit="cover" surface="presenter-current">
<SlideFrame
definition={current}
slideIndex={slideIndex}
revealedCount={revealed}
surface="presenter"
/>
</CanvasScaler>
</PresentationInteractionSurface>
<div className="slide-kit-presenter-preview-strip">
<PresenterPreview
definition={previous}
direction="previous"
disabled={previousDisabled}
revealedCount={previousRevealed}
slideIndex={previousSlideIndex}
label={messages.previous}
onSelect={deck.previous}
/>
<PresenterPreview
definition={next}
direction="next"
disabled={nextDisabled}
revealedCount={nextRevealed}
slideIndex={nextSlideIndex}
label={messages.upNext}
onSelect={deck.next}
/>
</div>
<div className="slide-kit-presenter-utility">
<ElapsedTime
presenterWindow={presenterWindow}
startedAt={startedAt}
/>
<ControlButton
className="slide-kit-presenter-count"
aria-label={messages.slides}
onClick={() => setSlideGridOpen(true)}
>
<ControlIcon name="grid" />
<span>
{deck.slideIndex + 1} / {deck.slideCount}
</span>
</ControlButton>
</div>
</section>
<SpeakerNotes slideIndex={slideIndex}>{current.notes}</SpeakerNotes>
</div>
{slideGridOpen ? (
<PresenterSlideGrid
activeSlideIndex={slideIndex}
presenterWindow={presenterWindow}
slides={slides}
onClose={() => setSlideGridOpen(false)}
onSelect={(slideNumber) => {
deck.goToSlide(slideNumber);
setSlideGridOpen(false);
}}
/>
) : null}
</main>
);
}
function usePresenterKeyboard({
enabled,
first,
last,
next,
presenterWindow,
previous,
}: {
enabled: boolean;
first: () => void;
last: () => void;
next: () => void;
presenterWindow: Window;
previous: () => void;
}) {
useEffect(() => {
if (!enabled) {
return;
}
const onKeyDown = (event: KeyboardEvent) => {
if (shouldIgnoreKeyboardEvent(event)) {
return;
}
handleKeyboardNavigation(event, {
first,
last,
next,
previous,
});
};
presenterWindow.addEventListener("keydown", onKeyDown);
return () => presenterWindow.removeEventListener("keydown", onKeyDown);
}, [enabled, first, last, next, presenterWindow, previous]);
}
function PresenterPreview({
definition,
direction,
disabled,
label,
revealedCount,
slideIndex,
onSelect,
}: {
definition: SlideDefinition | null;
direction: "next" | "previous";
disabled: boolean;
label: string;
revealedCount: number;
slideIndex: number;
onSelect: () => void;
}) {
return (
<section
className="slide-kit-presenter-preview"
aria-label={label}
data-available={definition ? "true" : "false"}
>
<div className="slide-kit-presenter-preview-frame">
{definition ? (
<CanvasScaler fit="cover" surface="presenter-preview">
<SlideFrame
definition={definition}
slideIndex={slideIndex}
revealedCount={revealedCount}
surface="preview"
/>
</CanvasScaler>
) : (
<span
className="slide-kit-presenter-preview-empty"
aria-hidden="true"
>
<span
className={`slide-kit-triangle slide-kit-triangle-${direction}`}
/>
</span>
)}
</div>
<span className="slide-kit-presenter-preview-label" aria-hidden="true">
<span>{label}</span>
</span>
<button
type="button"
aria-label={label}
disabled={disabled || !definition}
onClick={onSelect}
/>
</section>
);
}
function PresenterSlideGrid({
activeSlideIndex,
presenterWindow,
slides,
onClose,
onSelect,
}: {
activeSlideIndex: number;
presenterWindow: Window;
slides: SlideDefinition[];
onClose: () => void;
onSelect: (slideNumber: number) => void;
}) {
const messages = useLocalization();
useEffect(() => {
const closeFromKeyboard = (event: KeyboardEvent) => {
if (event.key === "Escape") {
onClose();
}
};
presenterWindow.addEventListener("keydown", closeFromKeyboard);
return () =>
presenterWindow.removeEventListener("keydown", closeFromKeyboard);
}, [onClose, presenterWindow]);
return (
<div
className="slide-kit-presenter-grid-overlay"
onPointerDown={(event) => {
if (event.target === event.currentTarget) {
onClose();
}
}}
>
<section
className="slide-kit-presenter-grid-panel"
role="dialog"
aria-modal="true"
aria-label={messages.slides}
>
<header>
<strong>{messages.slides}</strong>
<ControlButton iconOnly aria-label={messages.close} onClick={onClose}>
<ControlIcon name="close" />
</ControlButton>
</header>
<div className="slide-kit-presenter-grid">
{slides.map((slide, index) => (
<div
key={slide.id}
className="slide-kit-presenter-grid-item"
data-active={index === activeSlideIndex ? "true" : undefined}
>
<span>
<CanvasScaler fit="cover" surface="presenter-grid">
<SlideFrame
definition={slide}
slideIndex={index}
revealedCount={Number.MAX_SAFE_INTEGER}
surface="thumbnail"
/>
</CanvasScaler>
</span>
<button
type="button"
aria-label={messages.goToSlideNumber(index + 1)}
aria-current={index === activeSlideIndex ? "page" : undefined}
onClick={() => onSelect(index + 1)}
/>
</div>
))}
</div>
</section>
</div>
);
}
function PresenterHeader() {
const messages = useLocalization();
return (
<header className="slide-kit-presenter-header">
<strong>{messages.presenterView}</strong>
<span className="slide-kit-presenter-status">
<span aria-hidden="true" />
{messages.connected}
</span>
</header>
);
}
function ElapsedTime({
presenterWindow,
startedAt,
}: {
presenterWindow: Window;
startedAt: number;
}) {
const messages = useLocalization();
const [now, setNow] = useState(() => Date.now());
useEffect(() => {
const interval = presenterWindow.setInterval(
() => setNow(Date.now()),
1_000,
);
return () => presenterWindow.clearInterval(interval);
}, [presenterWindow]);
const formatted = useMemo(() => {
const seconds = Math.max(0, Math.floor((now - startedAt) / 1_000));
const minutes = Math.floor(seconds / 60);
return `${String(minutes).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`;
}, [now, startedAt]);
return (
<time
className="slide-kit-presenter-time"
aria-label={messages.elapsedTime}
>
{formatted}
</time>
);
}
function SpeakerNotes({
children,
slideIndex,
}: {
children: ReactNode;
slideIndex: number;
}) {
const messages = useLocalization();
return (
<SlidePositionProvider slideIndex={slideIndex}>
<aside
className="slide-kit-presenter-notes-column"
role="region"
aria-label={messages.speakerNotes}
>
<div className="slide-kit-presenter-notes">
<StepRegistry mode="static" revealedCount={Number.MAX_SAFE_INTEGER}>
<div>{children ?? <span>{messages.noNotes}</span>}</div>
</StepRegistry>
</div>
</aside>
</SlidePositionProvider>
);
}
@@ -0,0 +1,111 @@
import { type ReactNode, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
export interface PresenterPopupTarget {
popupWindow: Window;
root: HTMLDivElement;
sourceWindow: Window;
}
const PRESENTER_WINDOW_NAME = "slide-kit-presenter";
const PRESENTER_WINDOW_FEATURES = "popup,width=1280,height=800";
export function openPresenterPopup(
sourceRoot: HTMLDivElement,
title: string,
): PresenterPopupTarget | null {
const sourceWindow = sourceRoot.ownerDocument.defaultView;
if (!sourceWindow) {
return null;
}
const popupWindow = sourceWindow.open(
"about:blank",
PRESENTER_WINDOW_NAME,
PRESENTER_WINDOW_FEATURES,
);
if (!popupWindow) {
return null;
}
try {
const popupDocument = popupWindow.document;
popupDocument.title = title;
popupDocument.documentElement.lang =
sourceRoot.lang || sourceRoot.ownerDocument.documentElement.lang;
copyViewportMetadata(sourceRoot.ownerDocument, popupDocument);
copyStyles(sourceRoot.ownerDocument, popupDocument);
const root = popupDocument.importNode(sourceRoot, false);
popupDocument.body.replaceChildren(root);
return { popupWindow, root, sourceWindow };
} catch {
popupWindow.close();
return null;
}
}
export function PresenterPopupPortal({
children,
onClose,
target,
}: {
children: ReactNode;
onClose: (target: PresenterPopupTarget) => void;
target: PresenterPopupTarget;
}) {
const closeTimerRef = useRef<number | null>(null);
useEffect(() => {
if (closeTimerRef.current !== null) {
target.sourceWindow.clearTimeout(closeTimerRef.current);
closeTimerRef.current = null;
}
const handlePopupClose = () => onClose(target);
const handleSourceClose = () => target.popupWindow.close();
const closedCheck = target.sourceWindow.setInterval(() => {
if (target.popupWindow.closed) {
handlePopupClose();
}
}, 250);
target.popupWindow.addEventListener("pagehide", handlePopupClose);
target.sourceWindow.addEventListener("pagehide", handleSourceClose);
return () => {
target.popupWindow.removeEventListener("pagehide", handlePopupClose);
target.sourceWindow.removeEventListener("pagehide", handleSourceClose);
target.sourceWindow.clearInterval(closedCheck);
closeTimerRef.current = target.sourceWindow.setTimeout(() => {
if (!target.popupWindow.closed) {
target.popupWindow.close();
}
}, 0);
};
}, [onClose, target]);
return createPortal(children, target.root);
}
function copyViewportMetadata(
sourceDocument: Document,
popupDocument: Document,
): void {
const viewport = sourceDocument.querySelector<HTMLMetaElement>(
'meta[name="viewport"]',
);
if (viewport) {
popupDocument.head.append(popupDocument.importNode(viewport, true));
}
}
function copyStyles(sourceDocument: Document, popupDocument: Document): void {
const styles = sourceDocument.querySelectorAll<
HTMLStyleElement | HTMLLinkElement
>('style, link[rel~="stylesheet"]');
for (const style of styles) {
const copy = popupDocument.importNode(style, true);
if (style instanceof HTMLLinkElement) {
copy.setAttribute("href", style.href);
}
popupDocument.head.append(copy);
}
}
@@ -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]);
}