/* eslint-disable @typescript-eslint/no-base-to-string */ import { DOMWindow } from "jsdom"; import { cssEscape } from "./cssEscape.js"; const keyFrameAttributes = [ 'styler-on-enter', 'styler-on-enter-effect-1', 'styler-on-enter-effect-2', 'styler-on-hover', 'styler-on-hover-effect-1', 'styler-on-hover-effect-2', 'styler-on-leave', 'styler-on-leave-effect-1', 'styler-on-leave-effect-2', 'styler-on-scroll', 'styler-on-scroll-effect-1', 'styler-on-scroll-effect-2', 'styler-on-scroll-above', 'styler-on-scroll-above-effect-1', 'styler-on-scroll-above-effect-2', 'styler-on-scroll-top-half', 'styler-on-scroll-top-half-effect-1', 'styler-on-scroll-top-half-effect-2', ]; export default class DynamicStyles { private added: Set; private readonly style: HTMLStyleElement; private aId: number; private animations = new Map(); constructor(win: DOMWindow) { this.style = win.document.createElement("style"); this.added = new Set(); win.document.head.appendChild(this.style); this.aId = 1; } setAttribute(e: Element, a, value: string) { if (!value) { return; } value = value.trim(); const key = `[${a}="${cssEscape(value)}"]`; if (keyFrameAttributes.includes(a)) { // replace with animation... if (/[\{]/.test(value)) { return; // value = this.setAnimation(e, a, value); // if (!value) { // return; // } } } if (value === "custom") { return; } if (this.added.has(key)) { return; } this.added.add(key); this.style.append(` ${key} { --${a}: ${value}; } `); } setAnimation(e: Element, a: any, value: string) { try { const animationObj = JSON.parse(value); const minJson = JSON.stringify(animationObj); let v = this.animations.get(minJson); if (!v) { const frames = animationObj.keyframes ?? animationObj.keyFrames; if (!frames || !Array.isArray(frames)) { return; } const total = frames.length; let i = 0; for (const frame of frames) { frame.attributes = { ... frame }; delete frame.attributes.offset; frame.offset ??= i === 0 ? "0%" : (i === total - 1 ? "100%" : `${Math.floor(i * 100 / (total - 1))}%` ); i++; } const defaults = Object.entries(frames[0].attributes) as [string,string][]; v = { id: `internal-style-generated-${animationObj.title}-${this.aId++}`, defaults }; this.animations.set(minJson, v); const styleText = `@keyframes ${v.id} { ${frames.map((f) => `${f.offset} { ${Object.entries(f.attributes).map(([k,v1]) => `${k}: ${v1};`).join("\n")} }`).join("\n")} } `; this.style.append(styleText); } return v.id; } catch (error) { console.error(error); } } }