UNPKG

lottie-color-manager

Version:

A library for managing colors in Lottie animations

80 lines (79 loc) 2.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorTransformer = void 0; /** * Transforms colors in Lottie animations */ class ColorTransformer { /** * Recursively traverses the Lottie data and replaces colors */ static traverseAndReplaceColors(obj, colorMapping) { if (!obj || typeof obj !== 'object') return; // Check if this is a fill or stroke object with a color if ((obj.ty === 'fl' || obj.ty === 'st') && obj.c && obj.c.k) { this.replaceColorValue(obj.c.k, colorMapping); } // Recursively traverse arrays if (Array.isArray(obj)) { obj.forEach(item => this.traverseAndReplaceColors(item, colorMapping)); return; } // Recursively traverse object properties Object.keys(obj).forEach(key => { this.traverseAndReplaceColors(obj[key], colorMapping); }); } /** * Apply direct color transformations to Lottie data */ static applyColorTransformations(lottieData, transformations) { const clone = JSON.parse(JSON.stringify(lottieData)); // Create a color mapping format that works with existing traverseAndReplaceColors const colorMapping = new Map(); transformations.forEach(([source, target]) => { // Use string key for the map (convert array to string) const key = source.join(','); colorMapping.set(key, target); }); // Apply transformation to all colors in the data this.traverseAndReplaceColors(clone, colorMapping); return clone; } /** * Helper to convert a color to string key for mapping */ static colorToKey(color) { if (!color || !Array.isArray(color) || color.length !== 4) { return null; } return color.join(','); } /** * Helper to replace color values in Lottie data * Modify the existing replaceColorValue method to work with direct transformations */ static replaceColorValue(colorData, colorMapping) { // If it's not an array or doesn't have 4 elements (RGBA), do nothing if (!Array.isArray(colorData) || colorData.length !== 4) { return; } // Convert the color to a key for our mapping const colorKey = this.colorToKey(colorData); if (!colorKey) return; // Check if this color should be replaced if (colorMapping.has(colorKey)) { const newColor = colorMapping.get(colorKey); if (newColor) { // Update the color values colorData[0] = newColor[0]; colorData[1] = newColor[1]; colorData[2] = newColor[2]; colorData[3] = newColor[3]; } } } } exports.ColorTransformer = ColorTransformer;