UNPKG

lottie-color-manager

Version:

A library for managing colors in Lottie animations

74 lines (73 loc) 2.82 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.ColorExtractor = void 0; const logger_1 = require("../core/logger"); /** * Extracts colors from Lottie animations */ class ColorExtractor { /** * Extracts all unique colors from a Lottie animation */ static extractColors(lottieData) { const colors = []; const colorSet = new Set(); logger_1.Logger.debug('Extracting colors from Lottie animation'); this.searchForColors(lottieData, colorSet, colors); logger_1.Logger.debug(`Found ${colors.length} unique colors`); // Sort colors by brightness return colors.sort((a, b) => { const brightnessA = 0.299 * a[0] + 0.587 * a[1] + 0.114 * a[2]; const brightnessB = 0.299 * b[0] + 0.587 * b[1] + 0.114 * b[2]; return brightnessB - brightnessA; }); } /** * Recursively searches for colors in Lottie data */ static searchForColors(obj, colorSet, colors) { 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.extractColorFromProperty(obj.c.k, colorSet, colors); } // Recursively traverse arrays if (Array.isArray(obj)) { obj.forEach(item => this.searchForColors(item, colorSet, colors)); return; } // Recursively traverse object properties Object.keys(obj).forEach(key => { this.searchForColors(obj[key], colorSet, colors); }); } /** * Extracts colors from a property value, handling both static and animated colors */ static extractColorFromProperty(colorProperty, colorSet, colors) { // Static color: [r, g, b, a] if (Array.isArray(colorProperty) && colorProperty.length === 4 && typeof colorProperty[0] === 'number') { this.addUniqueColor(colorProperty, colorSet, colors); } // Animated color: array of keyframes with 's' property containing color values else if (Array.isArray(colorProperty) && colorProperty.length > 0 && colorProperty[0].s) { colorProperty.forEach((keyframe) => { if (keyframe.s && Array.isArray(keyframe.s)) { this.addUniqueColor(keyframe.s, colorSet, colors); } }); } } /** * Adds a color to the collection if it's unique */ static addUniqueColor(color, colorSet, colors) { const colorStr = JSON.stringify(color); if (!colorSet.has(colorStr)) { colorSet.add(colorStr); colors.push([...color]); } } } exports.ColorExtractor = ColorExtractor;