UNPKG

@atlaskit/icon

Version:

An icon is a symbol representing a command, device, directory, or common action.

172 lines (164 loc) • 7.48 kB
import _slicedToArray from "@babel/runtime/helpers/slicedToArray"; import { useCallback, useEffect, useImperativeHandle, useRef, useState } from 'react'; import { useAnimatedIconTrigger } from './use-animated-icon-trigger'; var prefersReducedMotion = function prefersReducedMotion() { return typeof window !== 'undefined' && typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches; }; /** * One step of a motion timeline: `phase` is returned by the hook for `durationMs`. */ // Goes idle while remembering which phase was active. Returns the same state if already idle, so no render. var toIdle = function toIdle(state) { return state.phase === undefined ? state : { phase: undefined, lastPhase: state.phase }; }; /** * Shared playback control for animated icons: "play once, guarded, interruptible". * * - `reanimate()` on the ref starts a motion. It is ignored while one is already playing. * - When an `AnimatedIconTrigger` above becomes active, the icon plays once, then tells the trigger it is done. * The trigger clears once every icon it started is done, so icons of different durations all play through. * - When the trigger goes inactive mid-motion, the motion is cancelled immediately, unless the icon passes * `{ nonInterruptible: true }`, in which case the whole timeline plays and the trigger is told at the end. * * A motion is a timeline of steps that run back to back. The hook returns the name of the current step's * phase, or `undefined` when idle, and the icon maps each phase to styles. The second value, `lastPhase`, is the * phase that was active when the motion finished or was interrupted (`undefined` before the first motion), for * the rare icon that must keep part of a phase's styles after going idle. Most icons only need `[phase]`. A hold is just a step whose * phase the icon styles the same as the one before it. * * ```ts * const TIMELINE = [ * { phase: 'shade', durationMs: 700 }, * { phase: 'hold', durationMs: 100 }, * { phase: 'redraw', durationMs: 600 }, * ] as const; * ``` * * When the user prefers reduced motion nothing plays: the phase stays `undefined`, so icons never need their own * reduced motion CSS. The trigger is still told the icon is done straight away so it doesn't stay active. * * Call this once per icon. A second call with the same ref overwrites `reanimate()` and starts a second timer; * model overlapping effects as phases of one timeline instead. * * `timeline` must be a module-level constant. A new array on every render would change `play`, re-run the * trigger effect and cancel the motion. * * To write a new animated icon: define the glyph, the timeline, and a style for each phase. */ export var useAnimatedIconPlayback = function useAnimatedIconPlayback(ref, timeline) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}, _ref$nonInterruptible = _ref.nonInterruptible, nonInterruptible = _ref$nonInterruptible === void 0 ? false : _ref$nonInterruptible; var motion = useAnimatedIconTrigger(); var isMotionActive = motion === null || motion === void 0 ? void 0 : motion.isActive; var startMotion = motion === null || motion === void 0 ? void 0 : motion.start; // `lastPhase` is the most recent phase that was active. It survives the phase going back to `undefined` // (the motion finished or was interrupted), and is replaced when the next motion starts. Both change in // the one state update, so tracking it costs no extra render. var _useState = useState({ phase: undefined, lastPhase: undefined }), _useState2 = _slicedToArray(_useState, 2), _useState2$ = _useState2[0], phase = _useState2$.phase, lastPhase = _useState2$.lastPhase, setState = _useState2[1]; // Holds the timer of the step that is currently running. Defined for as long as a motion is playing. var timeoutRef = useRef(undefined); // Called when the motion that is currently playing finishes. Cleared if the motion is cancelled. var onCompleteRef = useRef(undefined); var runStep = useCallback(function (index) { var step = timeline[index]; if (!step) { timeoutRef.current = undefined; setState(toIdle); var complete = onCompleteRef.current; onCompleteRef.current = undefined; complete === null || complete === void 0 || complete(); return; } setState({ phase: step.phase, lastPhase: step.phase }); timeoutRef.current = setTimeout(function () { return runStep(index + 1); }, step.durationMs); }, [timeline]); // Does nothing while a motion is already playing, so spamming `reanimate()` can't restart or stack // motions. A caller that supplies `onComplete` while one is playing still gets it called at the end. var play = useCallback(function (onComplete) { if (prefersReducedMotion()) { onComplete === null || onComplete === void 0 || onComplete(); return; } if (onComplete) { onCompleteRef.current = onComplete; } if (timeoutRef.current !== undefined) { return; } runStep(0); }, [runStep]); // Removes the phase immediately and clears the pending timeout, which stops the rest of the timeline. var cancel = useCallback(function () { clearTimeout(timeoutRef.current); timeoutRef.current = undefined; onCompleteRef.current = undefined; setState(toIdle); }, []); useImperativeHandle(ref, function () { return { reanimate: function reanimate() { return play(); } }; }, [play]); // The trigger's `done` for the motion this icon started, so it can be called if the icon unmounts first. var doneRef = useRef(undefined); useEffect(function () { if (!isMotionActive || !startMotion) { return; } // The trigger stays active until every icon it started has called its own `done`. var _startMotion = startMotion(), done = _startMotion.done, cancelMotion = _startMotion.cancel; doneRef.current = done; play(done); // Runs when the trigger deactivates before the motion completes (and on unmount), so the // motion is interruptible rather than finishing after the pointer has left. The trigger stops // waiting for it without counting it as finished. // A non-interruptible motion keeps its timer and plays on; the effect below clears it on unmount. if (nonInterruptible) { return undefined; } return function () { cancel(); cancelMotion(); }; }, [isMotionActive, play, cancel, startMotion, nonInterruptible]); // A ref-driven motion has no cleanup of its own, so clear its timer on unmount. An icon that unmounts // part way through must still tell the trigger it is done, or the trigger would wait for it forever. var isMountedRef = useRef(false); useEffect(function () { isMountedRef.current = true; return function () { isMountedRef.current = false; clearTimeout(timeoutRef.current); var done = doneRef.current; // React Strict Mode unmounts and remounts straight away. Waiting a microtask lets that remount // win, so the trigger isn't told the icon is done before it has played. void Promise.resolve().then(function () { if (!isMountedRef.current) { done === null || done === void 0 || done(); } }); }; }, []); return [phase, lastPhase]; };