UNPKG

@tsparticles/engine

Version:

Easily create highly customizable particle, confetti and fireworks animations and use them as animated backgrounds for your website. Ready to use components available also for React, Vue.js (2.x and 3.x), Angular, Svelte, jQuery, Preact, Riot.js, Inferno.

326 lines (325 loc) • 13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.safeDocument = safeDocument; exports.safeMatchMedia = safeMatchMedia; exports.safeMutationObserver = safeMutationObserver; exports.isInArray = isInArray; exports.itemFromArray = itemFromArray; exports.isPointInside = isPointInside; exports.areBoundsInside = areBoundsInside; exports.calculateBounds = calculateBounds; exports.deepExtend = deepExtend; exports.circleBounceDataFromParticle = circleBounceDataFromParticle; exports.circleBounce = circleBounce; exports.executeOnSingleOrMultiple = executeOnSingleOrMultiple; exports.itemFromSingleOrMultiple = itemFromSingleOrMultiple; exports.getPosition = getPosition; exports.cloneStyle = cloneStyle; exports.getFullScreenStyle = getFullScreenStyle; exports.manageListener = manageListener; exports.getItemsFromInitializer = getItemsFromInitializer; exports.getItemMapFromInitializer = getItemMapFromInitializer; exports.getDataFromUrl = getDataFromUrl; exports.getCanvasFromContainer = getCanvasFromContainer; exports.getDomContainer = getDomContainer; const Constants_js_1 = require("../Core/Utils/Constants.js"); const MathUtils_js_1 = require("./MathUtils.js"); const TypeUtils_js_1 = require("./TypeUtils.js"); const OutModeDirection_js_1 = require("../Enums/Directions/OutModeDirection.js"); const PixelMode_js_1 = require("../Enums/Modes/PixelMode.js"); const Vectors_js_1 = require("../Core/Utils/Vectors.js"); const LogUtils_js_1 = require("./LogUtils.js"); function isForbiddenKey(key) { return key === "__proto__" || key === "constructor" || key === "prototype"; } function hasMatchMedia() { return typeof matchMedia !== "undefined"; } function safeDocument() { return globalThis.document; } function safeMatchMedia(query) { if (!hasMatchMedia()) { return; } return matchMedia(query); } function safeMutationObserver(callback) { if (typeof MutationObserver === "undefined") { return; } return new MutationObserver(callback); } function isInArray(value, array) { return value === array || ((0, TypeUtils_js_1.isArray)(array) && array.includes(value)); } function itemFromArray(array, index, useIndex = true) { return array[index !== undefined && useIndex ? index % array.length : Math.floor((0, MathUtils_js_1.getRandom)() * array.length)]; } function isPointInside(point, size, offset, radius, direction) { return areBoundsInside(calculateBounds(point, radius ?? Constants_js_1.minRadius), size, offset, direction); } function areBoundsInside(bounds, size, offset, direction) { let inside = true; if (!direction || direction === OutModeDirection_js_1.OutModeDirection.bottom) { inside = bounds.top < size.height + offset.x; } if (inside && (!direction || direction === OutModeDirection_js_1.OutModeDirection.left)) { inside = bounds.right > offset.x; } if (inside && (!direction || direction === OutModeDirection_js_1.OutModeDirection.right)) { inside = bounds.left < size.width + offset.y; } if (inside && (!direction || direction === OutModeDirection_js_1.OutModeDirection.top)) { inside = bounds.bottom > offset.y; } return inside; } function calculateBounds(point, radius) { return { bottom: point.y + radius, left: point.x - radius, right: point.x + radius, top: point.y - radius, }; } function deepExtend(destination, ...sources) { for (const source of sources) { if ((0, TypeUtils_js_1.isNull)(source)) { continue; } if (!(0, TypeUtils_js_1.isObject)(source)) { destination = source; continue; } if (Array.isArray(source)) { if (!Array.isArray(destination)) { destination = []; } } else if (!(0, TypeUtils_js_1.isObject)(destination) || Array.isArray(destination)) { destination = Object.create(null); } const sourceKeys = Object.keys(source), hasNested = sourceKeys.some(k => { const v = source[k]; return (0, TypeUtils_js_1.isObject)(v) || Array.isArray(v); }); if (!hasNested) { const sourceDict = source, destDict = destination; for (const key of sourceKeys) { if (isForbiddenKey(key)) { continue; } const v = sourceDict[key]; if (v !== undefined) { destDict[key] = v; } } continue; } for (const key of sourceKeys) { if (isForbiddenKey(key)) { continue; } const sourceDict = source, destDict = destination, value = sourceDict[key]; destDict[key] = Array.isArray(value) ? value.map(v => deepExtend(undefined, v)) : deepExtend(destDict[key], value); } } return destination; } function circleBounceDataFromParticle(p) { return { position: p.getPosition(), radius: p.getRadius(), mass: p.getMass(), velocity: p.velocity, factor: Vectors_js_1.Vector.create((0, MathUtils_js_1.getRangeValue)(p.options.bounce.horizontal.value), (0, MathUtils_js_1.getRangeValue)(p.options.bounce.vertical.value)), }; } function circleBounce(p1, p2) { const { x: xVelocityDiff, y: yVelocityDiff } = p1.velocity.sub(p2.velocity), [pos1, pos2] = [p1.position, p2.position], xDist = pos2.x - pos1.x, yDist = pos2.y - pos1.y, minimumDistance = 0; if (xVelocityDiff * xDist + yVelocityDiff * yDist < minimumDistance) { return; } const angle = -Math.atan2(yDist, xDist), m1 = p1.mass, m2 = p2.mass, u1 = p1.velocity.rotate(angle), u2 = p2.velocity.rotate(angle), v1 = (0, MathUtils_js_1.collisionVelocity)(u1, u2, m1, m2), v2 = (0, MathUtils_js_1.collisionVelocity)(u2, u1, m1, m2), vFinal1 = v1.rotate(-angle), vFinal2 = v2.rotate(-angle); p1.velocity.x = vFinal1.x * p1.factor.x; p1.velocity.y = vFinal1.y * p1.factor.y; p2.velocity.x = vFinal2.x * p2.factor.x; p2.velocity.y = vFinal2.y * p2.factor.y; } function executeOnSingleOrMultiple(obj, callback) { const defaultIndex = 0; return (0, TypeUtils_js_1.isArray)(obj) ? obj.map((item, index) => callback(item, index)) : callback(obj, defaultIndex); } function itemFromSingleOrMultiple(obj, index, useIndex) { return (0, TypeUtils_js_1.isArray)(obj) ? itemFromArray(obj, index, useIndex) : obj; } function getPositionOrSize(positionOrSize, canvasSize) { const isPercent = positionOrSize.mode === PixelMode_js_1.PixelMode.percent; if (!isPercent) { const { mode: _, ...rest } = positionOrSize; return rest; } const isPosition = "x" in positionOrSize; if (isPosition) { return { x: (positionOrSize.x / Constants_js_1.percentDenominator) * canvasSize.width, y: (positionOrSize.y / Constants_js_1.percentDenominator) * canvasSize.height, }; } else { return { width: (positionOrSize.width / Constants_js_1.percentDenominator) * canvasSize.width, height: (positionOrSize.height / Constants_js_1.percentDenominator) * canvasSize.height, }; } } function getPosition(position, canvasSize) { return getPositionOrSize(position, canvasSize); } function cloneStyle(style) { const clonedStyle = safeDocument().createElement("div").style; for (const key in style) { const styleKey = style[key]; if (!(key in style) || (0, TypeUtils_js_1.isNull)(styleKey)) { continue; } const styleValue = style.getPropertyValue?.(styleKey); if (!styleValue) { continue; } const stylePriority = style.getPropertyPriority?.(styleKey); if (stylePriority) { clonedStyle.setProperty(styleKey, styleValue, stylePriority); } else { clonedStyle.setProperty(styleKey, styleValue); } } return clonedStyle; } let _cachedZIndex, _cachedStyle; function getFullScreenStyle(zIndex) { if (_cachedZIndex !== zIndex || !_cachedStyle) { _cachedZIndex = zIndex; const fullScreenStyle = safeDocument().createElement("div").style, radix = 10, style = { width: "100%", height: "100%", margin: "0", padding: "0", borderWidth: "0", position: "fixed", zIndex: zIndex.toString(radix), "z-index": zIndex.toString(radix), top: "0", left: "0", "pointer-events": "none", }; for (const key in style) { const value = style[key]; if (value === undefined) { continue; } fullScreenStyle.setProperty(key, value); } _cachedStyle = fullScreenStyle; } return _cachedStyle; } function manageListener(element, event, handler, add, options) { if (add) { let addOptions = { passive: true }; if ((0, TypeUtils_js_1.isBoolean)(options)) { addOptions.capture = options; } else if (options !== undefined) { addOptions = options; } element.addEventListener(event, handler, addOptions); } else { const removeOptions = options; element.removeEventListener(event, handler, removeOptions); } } async function getItemsFromInitializer(container, initializers) { return await Promise.all([...initializers.values()].map(t => t(container))); } async function getItemMapFromInitializer(container, initializers) { const entries = await Promise.all([...initializers.entries()].map(([key, initializer]) => initializer(container).then(item => [key, item]))); return new Map(entries); } async function getDataFromUrl(data) { const url = itemFromSingleOrMultiple(data.url, data.index); if (!url) { return data.fallback; } try { const response = await fetch(url); if (response.ok) { const current = (await response.json()); if (isSourceOptionsValue(current)) { return current; } (0, LogUtils_js_1.getLogger)().error("invalid configuration data while retrieving config file"); } else { (0, LogUtils_js_1.getLogger)().error(`${response.status.toString()} while retrieving config file`); } } catch (error) { (0, LogUtils_js_1.getLogger)().error(`error while retrieving config file: ${error}`); } return data.fallback; } function isSourceOptionsValue(value) { if ((0, TypeUtils_js_1.isArray)(value)) { return value.every((entry) => (0, TypeUtils_js_1.isObject)(entry) && !(0, TypeUtils_js_1.isArray)(entry)); } return (0, TypeUtils_js_1.isObject)(value) && !(0, TypeUtils_js_1.isArray)(value); } function getCanvasFromContainer(domContainer) { let canvasEl; const documentSafe = safeDocument(), isCanvas = domContainer instanceof HTMLCanvasElement || domContainer.tagName.toLowerCase() === Constants_js_1.canvasTag; if (isCanvas) { canvasEl = domContainer; canvasEl.dataset[Constants_js_1.generatedAttribute] ??= Constants_js_1.generatedFalse; if (canvasEl.dataset[Constants_js_1.generatedAttribute] === Constants_js_1.generatedTrue) { canvasEl.style.width ||= Constants_js_1.fullPercent; canvasEl.style.height ||= Constants_js_1.fullPercent; canvasEl.style.pointerEvents = "none"; canvasEl.style.setProperty("pointer-events", "none"); } } else { const existingCanvases = domContainer.getElementsByTagName(Constants_js_1.canvasTag), foundCanvas = existingCanvases.item(Constants_js_1.canvasFirstIndex); if (foundCanvas) { canvasEl = foundCanvas; canvasEl.dataset[Constants_js_1.generatedAttribute] = Constants_js_1.generatedFalse; } else { canvasEl = documentSafe.createElement(Constants_js_1.canvasTag); canvasEl.dataset[Constants_js_1.generatedAttribute] = Constants_js_1.generatedTrue; domContainer.appendChild(canvasEl); } canvasEl.style.width ||= Constants_js_1.fullPercent; canvasEl.style.height ||= Constants_js_1.fullPercent; canvasEl.style.pointerEvents = "none"; canvasEl.style.setProperty("pointer-events", "none"); } return canvasEl; } function getDomContainer(id, source) { const documentSafe = safeDocument(); let domContainer = source ?? documentSafe.getElementById(id); if (domContainer) { return domContainer; } domContainer = documentSafe.createElement("canvas"); domContainer.id = id; domContainer.dataset[Constants_js_1.generatedAttribute] = Constants_js_1.generatedTrue; documentSafe.body.append(domContainer); return domContainer; }