main repo

This commit is contained in:
Basilosaurusrex
2025-11-24 18:09:40 +01:00
parent b636ee5e70
commit f027651f9b
34146 changed files with 4436636 additions and 0 deletions

View File

@@ -0,0 +1,42 @@
import { DOMKeyframesResolver, isMotionValue } from 'motion-dom';
import { VisualElement } from '../VisualElement.mjs';
class DOMVisualElement extends VisualElement {
constructor() {
super(...arguments);
this.KeyframeResolver = DOMKeyframesResolver;
}
sortInstanceNodePosition(a, b) {
/**
* compareDocumentPosition returns a bitmask, by using the bitwise &
* we're returning true if 2 in that bitmask is set to true. 2 is set
* to true if b preceeds a.
*/
return a.compareDocumentPosition(b) & 2 ? 1 : -1;
}
getBaseTargetFromProps(props, key) {
return props.style
? props.style[key]
: undefined;
}
removeValueFromRenderState(key, { vars, style }) {
delete vars[key];
delete style[key];
}
handleChildMotionValue() {
if (this.childSubscription) {
this.childSubscription();
delete this.childSubscription;
}
const { children } = this.props;
if (isMotionValue(children)) {
this.childSubscription = children.on("change", (latest) => {
if (this.current) {
this.current.textContent = `${latest}`;
}
});
}
}
}
export { DOMVisualElement };

View File

@@ -0,0 +1,14 @@
import { Fragment } from 'react';
import { HTMLVisualElement } from '../html/HTMLVisualElement.mjs';
import { SVGVisualElement } from '../svg/SVGVisualElement.mjs';
import { isSVGComponent } from './utils/is-svg-component.mjs';
const createDomVisualElement = (Component, options) => {
return isSVGComponent(Component)
? new SVGVisualElement(options)
: new HTMLVisualElement(options, {
allowProjection: Component !== Fragment,
});
};
export { createDomVisualElement };

View File

@@ -0,0 +1,15 @@
"use client";
import { animations } from '../../motion/features/animations.mjs';
import { gestureAnimations } from '../../motion/features/gestures.mjs';
import { createDomVisualElement } from './create-visual-element.mjs';
/**
* @public
*/
const domAnimation = {
renderer: createDomVisualElement,
...animations,
...gestureAnimations,
};
export { domAnimation };

View File

@@ -0,0 +1,15 @@
"use client";
import { drag } from '../../motion/features/drag.mjs';
import { layout } from '../../motion/features/layout.mjs';
import { domAnimation } from './features-animation.mjs';
/**
* @public
*/
const domMax = {
...domAnimation,
...drag,
...layout,
};
export { domMax };

View File

@@ -0,0 +1,13 @@
"use client";
import { animations } from '../../motion/features/animations.mjs';
import { createDomVisualElement } from './create-visual-element.mjs';
/**
* @public
*/
const domMin = {
renderer: createDomVisualElement,
...animations,
};
export { domMin };

View File

@@ -0,0 +1,18 @@
import { observeTimeline } from 'motion-dom';
import { getTimeline } from './utils/get-timeline.mjs';
function attachToAnimation(animation, options) {
const timeline = getTimeline(options);
return animation.attachTimeline({
timeline: options.target ? undefined : timeline,
observe: (valueAnimation) => {
valueAnimation.pause();
return observeTimeline((progress) => {
valueAnimation.time =
valueAnimation.iterationDuration * progress;
}, timeline);
},
});
}
export { attachToAnimation };

View File

@@ -0,0 +1,23 @@
import { observeTimeline } from 'motion-dom';
import { scrollInfo } from './track.mjs';
import { getTimeline } from './utils/get-timeline.mjs';
/**
* If the onScroll function has two arguments, it's expecting
* more specific information about the scroll from scrollInfo.
*/
function isOnScrollWithInfo(onScroll) {
return onScroll.length === 2;
}
function attachToFunction(onScroll, options) {
if (isOnScrollWithInfo(onScroll)) {
return scrollInfo((info) => {
onScroll(info[options.axis].progress, info);
}, options);
}
else {
return observeTimeline(onScroll, getTimeline(options));
}
}
export { attachToFunction };

View File

@@ -0,0 +1,14 @@
import { noop } from 'motion-utils';
import { attachToAnimation } from './attach-animation.mjs';
import { attachToFunction } from './attach-function.mjs';
function scroll(onScroll, { axis = "y", container = document.scrollingElement, ...options } = {}) {
if (!container)
return noop;
const optionsWithDefaults = { axis, container, ...options };
return typeof onScroll === "function"
? attachToFunction(onScroll, optionsWithDefaults)
: attachToAnimation(onScroll, optionsWithDefaults);
}
export { scroll };

View File

@@ -0,0 +1,55 @@
import { progress, velocityPerSecond } from 'motion-utils';
/**
* A time in milliseconds, beyond which we consider the scroll velocity to be 0.
*/
const maxElapsed = 50;
const createAxisInfo = () => ({
current: 0,
offset: [],
progress: 0,
scrollLength: 0,
targetOffset: 0,
targetLength: 0,
containerLength: 0,
velocity: 0,
});
const createScrollInfo = () => ({
time: 0,
x: createAxisInfo(),
y: createAxisInfo(),
});
const keys = {
x: {
length: "Width",
position: "Left",
},
y: {
length: "Height",
position: "Top",
},
};
function updateAxisInfo(element, axisName, info, time) {
const axis = info[axisName];
const { length, position } = keys[axisName];
const prev = axis.current;
const prevTime = info.time;
axis.current = element[`scroll${position}`];
axis.scrollLength = element[`scroll${length}`] - element[`client${length}`];
axis.offset.length = 0;
axis.offset[0] = 0;
axis.offset[1] = axis.scrollLength;
axis.progress = progress(0, axis.scrollLength, axis.current);
const elapsed = time - prevTime;
axis.velocity =
elapsed > maxElapsed
? 0
: velocityPerSecond(axis.current - prev, elapsed);
}
function updateScrollInfo(element, info, time) {
updateAxisInfo(element, "x", info, time);
updateAxisInfo(element, "y", info, time);
info.time = time;
}
export { createScrollInfo, updateScrollInfo };

View File

@@ -0,0 +1,45 @@
const namedEdges = {
start: 0,
center: 0.5,
end: 1,
};
function resolveEdge(edge, length, inset = 0) {
let delta = 0;
/**
* If we have this edge defined as a preset, replace the definition
* with the numerical value.
*/
if (edge in namedEdges) {
edge = namedEdges[edge];
}
/**
* Handle unit values
*/
if (typeof edge === "string") {
const asNumber = parseFloat(edge);
if (edge.endsWith("px")) {
delta = asNumber;
}
else if (edge.endsWith("%")) {
edge = asNumber / 100;
}
else if (edge.endsWith("vw")) {
delta = (asNumber / 100) * document.documentElement.clientWidth;
}
else if (edge.endsWith("vh")) {
delta = (asNumber / 100) * document.documentElement.clientHeight;
}
else {
edge = asNumber;
}
}
/**
* If the edge is defined as a number, handle as a progress value.
*/
if (typeof edge === "number") {
delta = length * edge;
}
return inset + delta;
}
export { namedEdges, resolveEdge };

View File

@@ -0,0 +1,59 @@
import { interpolate, defaultOffset } from 'motion-dom';
import { clamp } from 'motion-utils';
import { calcInset } from './inset.mjs';
import { resolveOffset } from './offset.mjs';
import { ScrollOffset } from './presets.mjs';
const point = { x: 0, y: 0 };
function getTargetSize(target) {
return "getBBox" in target && target.tagName !== "svg"
? target.getBBox()
: { width: target.clientWidth, height: target.clientHeight };
}
function resolveOffsets(container, info, options) {
const { offset: offsetDefinition = ScrollOffset.All } = options;
const { target = container, axis = "y" } = options;
const lengthLabel = axis === "y" ? "height" : "width";
const inset = target !== container ? calcInset(target, container) : point;
/**
* Measure the target and container. If they're the same thing then we
* use the container's scrollWidth/Height as the target, from there
* all other calculations can remain the same.
*/
const targetSize = target === container
? { width: container.scrollWidth, height: container.scrollHeight }
: getTargetSize(target);
const containerSize = {
width: container.clientWidth,
height: container.clientHeight,
};
/**
* Reset the length of the resolved offset array rather than creating a new one.
* TODO: More reusable data structures for targetSize/containerSize would also be good.
*/
info[axis].offset.length = 0;
/**
* Populate the offset array by resolving the user's offset definition into
* a list of pixel scroll offets.
*/
let hasChanged = !info[axis].interpolate;
const numOffsets = offsetDefinition.length;
for (let i = 0; i < numOffsets; i++) {
const offset = resolveOffset(offsetDefinition[i], containerSize[lengthLabel], targetSize[lengthLabel], inset[axis]);
if (!hasChanged && offset !== info[axis].interpolatorOffsets[i]) {
hasChanged = true;
}
info[axis].offset[i] = offset;
}
/**
* If the pixel scroll offsets have changed, create a new interpolator function
* to map scroll value into a progress.
*/
if (hasChanged) {
info[axis].interpolate = interpolate(info[axis].offset, defaultOffset(offsetDefinition), { clamp: false });
info[axis].interpolatorOffsets = [...info[axis].offset];
}
info[axis].progress = clamp(0, 1, info[axis].interpolate(info[axis].current));
}
export { resolveOffsets };

View File

@@ -0,0 +1,47 @@
import { isHTMLElement } from 'motion-dom';
function calcInset(element, container) {
const inset = { x: 0, y: 0 };
let current = element;
while (current && current !== container) {
if (isHTMLElement(current)) {
inset.x += current.offsetLeft;
inset.y += current.offsetTop;
current = current.offsetParent;
}
else if (current.tagName === "svg") {
/**
* This isn't an ideal approach to measuring the offset of <svg /> tags.
* It would be preferable, given they behave like HTMLElements in most ways
* to use offsetLeft/Top. But these don't exist on <svg />. Likewise we
* can't use .getBBox() like most SVG elements as these provide the offset
* relative to the SVG itself, which for <svg /> is usually 0x0.
*/
const svgBoundingBox = current.getBoundingClientRect();
current = current.parentElement;
const parentBoundingBox = current.getBoundingClientRect();
inset.x += svgBoundingBox.left - parentBoundingBox.left;
inset.y += svgBoundingBox.top - parentBoundingBox.top;
}
else if (current instanceof SVGGraphicsElement) {
const { x, y } = current.getBBox();
inset.x += x;
inset.y += y;
let svg = null;
let parent = current.parentNode;
while (!svg) {
if (parent.tagName === "svg") {
svg = parent;
}
parent = current.parentNode;
}
current = svg;
}
else {
break;
}
}
return inset;
}
export { calcInset };

View File

@@ -0,0 +1,35 @@
import { resolveEdge, namedEdges } from './edge.mjs';
const defaultOffset = [0, 0];
function resolveOffset(offset, containerLength, targetLength, targetInset) {
let offsetDefinition = Array.isArray(offset) ? offset : defaultOffset;
let targetPoint = 0;
let containerPoint = 0;
if (typeof offset === "number") {
/**
* If we're provided offset: [0, 0.5, 1] then each number x should become
* [x, x], so we default to the behaviour of mapping 0 => 0 of both target
* and container etc.
*/
offsetDefinition = [offset, offset];
}
else if (typeof offset === "string") {
offset = offset.trim();
if (offset.includes(" ")) {
offsetDefinition = offset.split(" ");
}
else {
/**
* If we're provided a definition like "100px" then we want to apply
* that only to the top of the target point, leaving the container at 0.
* Whereas a named offset like "end" should be applied to both.
*/
offsetDefinition = [offset, namedEdges[offset] ? offset : `0`];
}
}
targetPoint = resolveEdge(offsetDefinition[0], targetLength, targetInset);
containerPoint = resolveEdge(offsetDefinition[1], containerLength);
return targetPoint - containerPoint;
}
export { resolveOffset };

View File

@@ -0,0 +1,20 @@
const ScrollOffset = {
Enter: [
[0, 1],
[1, 1],
],
Exit: [
[0, 0],
[1, 0],
],
Any: [
[1, 0],
[0, 1],
],
All: [
[0, 0],
[1, 1],
],
};
export { ScrollOffset };

View File

@@ -0,0 +1,48 @@
import { warnOnce } from 'motion-utils';
import { updateScrollInfo } from './info.mjs';
import { resolveOffsets } from './offsets/index.mjs';
function measure(container, target = container, info) {
/**
* Find inset of target within scrollable container
*/
info.x.targetOffset = 0;
info.y.targetOffset = 0;
if (target !== container) {
let node = target;
while (node && node !== container) {
info.x.targetOffset += node.offsetLeft;
info.y.targetOffset += node.offsetTop;
node = node.offsetParent;
}
}
info.x.targetLength =
target === container ? target.scrollWidth : target.clientWidth;
info.y.targetLength =
target === container ? target.scrollHeight : target.clientHeight;
info.x.containerLength = container.clientWidth;
info.y.containerLength = container.clientHeight;
/**
* In development mode ensure scroll containers aren't position: static as this makes
* it difficult to measure their relative positions.
*/
if (process.env.NODE_ENV !== "production") {
if (container && target && target !== container) {
warnOnce(getComputedStyle(container).position !== "static", "Please ensure that the container has a non-static position, like 'relative', 'fixed', or 'absolute' to ensure scroll offset is calculated correctly.");
}
}
}
function createOnScrollHandler(element, onScroll, info, options = {}) {
return {
measure: (time) => {
measure(element, options.target, info);
updateScrollInfo(element, info, time);
if (options.offset || options.target) {
resolveOffsets(element, info, options);
}
},
notify: () => onScroll(info),
};
}
export { createOnScrollHandler };

View File

@@ -0,0 +1,80 @@
import { resize, frame, cancelFrame, frameData } from 'motion-dom';
import { noop } from 'motion-utils';
import { createScrollInfo } from './info.mjs';
import { createOnScrollHandler } from './on-scroll-handler.mjs';
const scrollListeners = new WeakMap();
const resizeListeners = new WeakMap();
const onScrollHandlers = new WeakMap();
const getEventTarget = (element) => element === document.scrollingElement ? window : element;
function scrollInfo(onScroll, { container = document.scrollingElement, ...options } = {}) {
if (!container)
return noop;
let containerHandlers = onScrollHandlers.get(container);
/**
* Get the onScroll handlers for this container.
* If one isn't found, create a new one.
*/
if (!containerHandlers) {
containerHandlers = new Set();
onScrollHandlers.set(container, containerHandlers);
}
/**
* Create a new onScroll handler for the provided callback.
*/
const info = createScrollInfo();
const containerHandler = createOnScrollHandler(container, onScroll, info, options);
containerHandlers.add(containerHandler);
/**
* Check if there's a scroll event listener for this container.
* If not, create one.
*/
if (!scrollListeners.has(container)) {
const measureAll = () => {
for (const handler of containerHandlers) {
handler.measure(frameData.timestamp);
}
frame.preUpdate(notifyAll);
};
const notifyAll = () => {
for (const handler of containerHandlers) {
handler.notify();
}
};
const listener = () => frame.read(measureAll);
scrollListeners.set(container, listener);
const target = getEventTarget(container);
window.addEventListener("resize", listener, { passive: true });
if (container !== document.documentElement) {
resizeListeners.set(container, resize(container, listener));
}
target.addEventListener("scroll", listener, { passive: true });
listener();
}
const listener = scrollListeners.get(container);
frame.read(listener, false, true);
return () => {
cancelFrame(listener);
/**
* Check if we even have any handlers for this container.
*/
const currentHandlers = onScrollHandlers.get(container);
if (!currentHandlers)
return;
currentHandlers.delete(containerHandler);
if (currentHandlers.size)
return;
/**
* If no more handlers, remove the scroll listener too.
*/
const scrollListener = scrollListeners.get(container);
scrollListeners.delete(container);
if (scrollListener) {
getEventTarget(container).removeEventListener("scroll", scrollListener);
resizeListeners.get(container)?.();
window.removeEventListener("resize", scrollListener);
}
};
}
export { scrollInfo };

View File

@@ -0,0 +1,30 @@
import { supportsScrollTimeline } from 'motion-dom';
import { scrollInfo } from '../track.mjs';
const timelineCache = new Map();
function scrollTimelineFallback(options) {
const currentTime = { value: 0 };
const cancel = scrollInfo((info) => {
currentTime.value = info[options.axis].progress * 100;
}, options);
return { currentTime, cancel };
}
function getTimeline({ source, container, ...options }) {
const { axis } = options;
if (source)
container = source;
const containerCache = timelineCache.get(container) ?? new Map();
timelineCache.set(container, containerCache);
const targetKey = options.target ?? "self";
const targetCache = containerCache.get(targetKey) ?? {};
const axisKey = axis + (options.offset ?? []).join(",");
if (!targetCache[axisKey]) {
targetCache[axisKey] =
!options.target && supportsScrollTimeline()
? new ScrollTimeline({ source: container, axis })
: scrollTimelineFallback({ container, ...options });
}
return targetCache[axisKey];
}
export { getTimeline };

View File

@@ -0,0 +1,29 @@
"use client";
import { isMotionValue } from 'motion-dom';
import { Fragment, useMemo, createElement } from 'react';
import { useHTMLProps } from '../html/use-props.mjs';
import { useSVGProps } from '../svg/use-props.mjs';
import { filterProps } from './utils/filter-props.mjs';
import { isSVGComponent } from './utils/is-svg-component.mjs';
function useRender(Component, props, ref, { latestValues, }, isStatic, forwardMotionProps = false) {
const useVisualProps = isSVGComponent(Component)
? useSVGProps
: useHTMLProps;
const visualProps = useVisualProps(props, latestValues, isStatic, Component);
const filteredProps = filterProps(props, typeof Component === "string", forwardMotionProps);
const elementProps = Component !== Fragment ? { ...filteredProps, ...visualProps, ref } : {};
/**
* If component has been handed a motion value as its child,
* memoise its initial value and render that. Subsequent updates
* will be handled by the onChange handler
*/
const { children } = props;
const renderedChildren = useMemo(() => (isMotionValue(children) ? children.get() : children), [children]);
return createElement(Component, {
...elementProps,
children: renderedChildren,
});
}
export { useRender };

View File

@@ -0,0 +1,6 @@
/**
* Convert camelCase to dash-case properties.
*/
const camelToDash = (str) => str.replace(/([a-z])([A-Z])/gu, "$1-$2").toLowerCase();
export { camelToDash };

View File

@@ -0,0 +1,59 @@
import { isValidMotionProp } from '../../../motion/utils/valid-prop.mjs';
let shouldForward = (key) => !isValidMotionProp(key);
function loadExternalIsValidProp(isValidProp) {
if (typeof isValidProp !== "function")
return;
// Explicitly filter our events
shouldForward = (key) => key.startsWith("on") ? !isValidMotionProp(key) : isValidProp(key);
}
/**
* Emotion and Styled Components both allow users to pass through arbitrary props to their components
* to dynamically generate CSS. They both use the `@emotion/is-prop-valid` package to determine which
* of these should be passed to the underlying DOM node.
*
* However, when styling a Motion component `styled(motion.div)`, both packages pass through *all* props
* as it's seen as an arbitrary component rather than a DOM node. Motion only allows arbitrary props
* passed through the `custom` prop so it doesn't *need* the payload or computational overhead of
* `@emotion/is-prop-valid`, however to fix this problem we need to use it.
*
* By making it an optionalDependency we can offer this functionality only in the situations where it's
* actually required.
*/
try {
/**
* We attempt to import this package but require won't be defined in esm environments, in that case
* isPropValid will have to be provided via `MotionContext`. In a 6.0.0 this should probably be removed
* in favour of explicit injection.
*/
loadExternalIsValidProp(require("@emotion/is-prop-valid").default);
}
catch {
// We don't need to actually do anything here - the fallback is the existing `isPropValid`.
}
function filterProps(props, isDom, forwardMotionProps) {
const filteredProps = {};
for (const key in props) {
/**
* values is considered a valid prop by Emotion, so if it's present
* this will be rendered out to the DOM unless explicitly filtered.
*
* We check the type as it could be used with the `feColorMatrix`
* element, which we support.
*/
if (key === "values" && typeof props.values === "object")
continue;
if (shouldForward(key) ||
(forwardMotionProps === true && isValidMotionProp(key)) ||
(!isDom && !isValidMotionProp(key)) ||
// If trying to use native HTML drag events, forward drag listeners
(props["draggable"] &&
key.startsWith("onDrag"))) {
filteredProps[key] =
props[key];
}
}
return filteredProps;
}
export { filterProps, loadExternalIsValidProp };

View File

@@ -0,0 +1,30 @@
import { lowercaseSVGElements } from '../../svg/lowercase-elements.mjs';
function isSVGComponent(Component) {
if (
/**
* If it's not a string, it's a custom React component. Currently we only support
* HTML custom React components.
*/
typeof Component !== "string" ||
/**
* If it contains a dash, the element is a custom HTML webcomponent.
*/
Component.includes("-")) {
return false;
}
else if (
/**
* If it's in our list of lowercase SVG tags, it's an SVG component
*/
lowercaseSVGElements.indexOf(Component) > -1 ||
/**
* If it contains a capital letter, it's an SVG component
*/
/[A-Z]/u.test(Component)) {
return true;
}
return false;
}
export { isSVGComponent };

View File

@@ -0,0 +1,43 @@
import { resolveElements } from 'motion-dom';
const thresholds = {
some: 0,
all: 1,
};
function inView(elementOrSelector, onStart, { root, margin: rootMargin, amount = "some" } = {}) {
const elements = resolveElements(elementOrSelector);
const activeIntersections = new WeakMap();
const onIntersectionChange = (entries) => {
entries.forEach((entry) => {
const onEnd = activeIntersections.get(entry.target);
/**
* If there's no change to the intersection, we don't need to
* do anything here.
*/
if (entry.isIntersecting === Boolean(onEnd))
return;
if (entry.isIntersecting) {
const newOnEnd = onStart(entry.target, entry);
if (typeof newOnEnd === "function") {
activeIntersections.set(entry.target, newOnEnd);
}
else {
observer.unobserve(entry.target);
}
}
else if (typeof onEnd === "function") {
onEnd(entry);
activeIntersections.delete(entry.target);
}
});
};
const observer = new IntersectionObserver(onIntersectionChange, {
root,
rootMargin,
threshold: typeof amount === "number" ? amount : thresholds[amount],
});
elements.forEach((element) => observer.observe(element));
return () => observer.disconnect();
}
export { inView };