---
name: component-animation-library
description: Specialized assistant for designing and maintaining a generic, shared animation system for web components using embedded CSS in TypeScript.
title: component-animation-library
canonical_url: https://skilld.dev/gh/corey-alix/dwp-hours/component-animation-library
last_updated: 2026-10-07T01:30:59.000Z
---

> Index of every page on this site: [llms.txt](https://skilld.dev/llms.txt)

> **Skill from skilld.dev.** Follow the user's requested action.
> If the user asked to fork this Skill, follow the fork workflow below. Do not execute the Skill instructions while copying it.
> Otherwise, follow the instructions below for this session. You do not need to install anything.
>
> If the user asked to install this Skill, run `npx skilld install corey-alix/dwp-hours/component-animation-library`. Install writes the Skill files into the project, so every session loads them.
>
> ## Fork workflow
>
> A fork creates an editable local Skill with its original author and licence. The request authorizes copying and local installation.
> 1. Check `./skills/component-animation-library`, the project lockfile, and selected Agent targets together. If the local directory or installed Skill exists, stop. Never overwrite an existing directory or Agent target.
> 2. Read [source metadata](https://skilld.dev/api/v1/skills/corey-alix/dwp-hours/component-animation-library) once. Use sourceUrl, sourceCommit, skillPath, sourceGone, and license. If the source is gone or its path is missing, stop. If license is null, read licence files at the source commit.
> 3. Fetch only the source commit into a temporary Git repository. Do not clone full history. Derive repository_url from sourceUrl, including repository renames. If sourceCommit is absent, resolve the sourceUrl ref once. Set source_commit to that actual commit. Run these commands in one shell call:
>
> ```sh
> git init --quiet "$temporary_dir"
> git -C "$temporary_dir" fetch --quiet --depth=1 "$repository_url" "$source_commit"
> git -C "$temporary_dir" checkout --quiet --detach FETCH_HEAD
> ```
>
> Read applicable licence declarations and notices at that commit. If copying is not permitted, report the restriction and stop.
> 4. Inspect source entries together, then copy the directory containing skillPath into `./skills/component-animation-library`. Use the user's path if selected. Keep the original SKILL.md, relative links, scripts, binary assets, and executable modes. Exclude .git metadata. Reject symlinks and paths outside the Skill directory. After checking entries, use cp -a where available. A regular source directory needs no custom copy script. Do not save this page wrapper as SKILL.md.
> Preserve author credit, notices, and applicable licence files from repository or parent directories. Add PROVENANCE.md with the Skill page, source URL, actual commit, original path, and licence. Retain any existing PROVENANCE.md and record new provenance separately. Batch source inspection, copying, and provenance work where practical.
> 5. In the project root, run `skilld install ./skills/component-animation-library --mode copy --plain`. If skilld is unavailable, use `npx skilld install ./skills/component-animation-library --mode copy --plain`. This known command needs no help lookup. Install does not support --json. Use detected Agent targets, or add --agent for the targets the user selected. Install the local path, never the upstream selector. If installation fails, preserve the local copy and report the exact failure.
> 6. Confirm the local lockfile source and installed Agent copies once. Report the local path, actual commit, and Agent targets. After edits, reinstall the same local path. Upstream updates must not replace it. Do not publish or push unless the user asks.

# Component Animation Library

## Description

Specialized assistant for designing and maintaining a generic, shared animation system for web components using embedded CSS in TypeScript and constructable stylesheets. Provides a single source of truth for keyframes, utility classes, and tokens that multiple components can consume efficiently without duplication.

## Trigger

Activate this skill when users need to:

- Implement animations in web components
- Create or maintain component-level animation libraries
- Add new animation effects to the shared system
- Modify animation timing, easing, or behavior globally
- Integrate animations with existing web component architecture
- Optimize animation performance across components

## Response Pattern

Follow this structured approach when implementing component animations:

1. **Assess Requirements**: Determine animation needs, performance constraints, and component integration points
2. **Directory Structure**: Create the standard animation library structure under `src/animations/`
3. **CSS Source Creation**: Implement `animations.ts` with keyframes, tokens, and utility classes
4. **Shared Sheet Implementation**: Create `index.ts` with constructable stylesheet singleton
5. **Component Integration**: Show how components adopt the shared sheet and apply animations
6. **Testing & Optimization**: Validate performance, add tests, and optimize for tree-shaking
7. **Documentation**: Update component documentation with animation usage examples

## Examples

Common queries that should trigger this skill:

- "Add fade-in animation to the employee list component"
- "Create a shared animation system for web components"
- "How do I implement staggered animations in the PTO calendar"
- "Optimize component animations for better performance"
- "Add new keyframe animations to the library"
- "Integrate animations with the existing CSS theming system"

## Additional Context

### Core Constraints & Goals

- CSS embedded in TypeScript (no separate .css files at runtime)
- Use `new CSSStyleSheet()` + `replaceSync()`
- One shared sheet adopted by all components via `shadowRoot.adoptedStyleSheets`
- Leverage CSS variables for durations, easings, delays, distances
- Support staggering, variants, overrides per-instance
- Tree-shake friendly & minimal runtime cost
- Browser support: modern (Chrome/Edge 73+, Firefox 101+, Safari 16.4+)

### Directory & Package Structure

```
client/animations/
├── index.ts                # public API: shared sheet + JS animation helpers
├── animations.ts           # raw CSS string (keyframes & utility classes)
└── types.ts                # AnimationHandle interface
```

### Implementation Details

#### Design Principles

- **No `:root` redefinitions** — animation tokens (durations, easings, distances) are defined in `tokens.css`. The animation library references them via `var()`.
- **CSS for declarative animations** — keyframes and utility classes in `animations.ts`.
- **JS helpers for multi-phase animations** — `animateSlide()` and `animateCarousel()` in `index.ts` for complex sequenced transitions that CSS alone cannot express.
- **AnimationHandle pattern** — JS helpers return `{ promise, cancel }` so callers can await completion or cancel mid-flight.

#### tokens.css — Animation Tokens (source of truth)

These tokens are defined in `client/tokens.css` and inherited into shadow DOMs:

```css
/* Animation Tokens */
:root {
  --duration-fast: 150ms;
  --duration-normal: 250ms;
  --duration-slow: 400ms;
  --easing-standard: cubic-bezier(0.4, 0, 0.2, 1);
  --easing-decelerate: cubic-bezier(0, 0, 0.2, 1);
  --easing-accelerate: cubic-bezier(0.4, 0, 1, 1);
  --slide-distance: 100%;
  --slide-offset: 8px;
}
```

#### animations.ts — The CSS Source

Keyframes and utility classes reference tokens.css vars. No hardcoded durations, easings, or distances.

```typescript
export const animationCSS = `
  @keyframes fade-in {
    from { opacity: 0; }
    to   { opacity: 1; }
  }

  @keyframes slide-in-right {
    from { transform: translateX(var(--slide-distance)); opacity: 0; }
    to   { transform: translateX(0); opacity: 1; }
  }

  @keyframes slide-out-left {
    from { transform: translateX(0); opacity: 1; }
    to   { transform: translateX(calc(-1 * var(--slide-distance))); opacity: 0; }
  }

  @keyframes slide-down-in {
    from { transform: translateY(calc(-1 * var(--slide-offset))); opacity: 0; }
    to   { transform: translateY(0); opacity: 1; }
  }

  /* Utility classes */
  .anim-slide-in-right {
    animation: slide-in-right var(--duration-normal) var(--easing-decelerate) backwards;
  }

  /* Reduced motion */
  @media (prefers-reduced-motion: reduce) {
    .anim-slide-in-right, .anim-slide-out-left /* ... */ {
      animation: none;
    }
  }
`;
```

#### index.ts — Shared Sheet + JS Helpers

```typescript
import { animationCSS } from "./animations.js";
import type { AnimationHandle } from "./types.js";

// Constructable stylesheet singleton
export function getAnimationSheet(): CSSStyleSheet {
  /* ... */
}
export function adoptAnimations(root: ShadowRoot | Document): void {
  /* ... */
}

// JS animation helpers (read tokens from :root at animation time)
export function animateSlide(
  element: HTMLElement,
  show: boolean,
): AnimationHandle;
export function animateCarousel(
  container: HTMLElement,
  direction: number,
  onUpdate: () => void,
): AnimationHandle;
```

#### types.ts — AnimationHandle

```typescript
export interface AnimationHandle {
  /** Resolves when the animation completes or is cancelled. */
  promise: Promise<void>;
  /** Cancel the animation immediately, cleaning up all inline styles. */
  cancel: () => void;
}
```

#### Usage in Web Components

```typescript
import {
  adoptAnimations,
  animateCarousel,
} from "../../css-extensions/index.js";
import type { AnimationHandle } from "../../css-extensions/index.js";

export class PtoEntryForm extends BaseComponent {
  private currentAnimation: AnimationHandle | null = null;

  connectedCallback() {
    super.connectedCallback();
    adoptAnimations(this.shadowRoot);
  }

  private navigateMonth(calendar: PtoCalendar, direction: number) {
    if (this.isAnimating) return;
    this.isAnimating = true;

    const container = this.shadowRoot.querySelector(
      "#calendar-container",
    ) as HTMLDivElement;
    this.currentAnimation = animateCarousel(container, direction, () => {
      this.updateCalendarMonth(calendar, direction);
    });
    this.currentAnimation.promise.then(() => {
      this.currentAnimation = null;
      this.isAnimating = false;
    });
  }
}
```

### Maintenance Guidelines

- **Add new CSS animation**: Append `@keyframes` + utility class in `animations.ts`
- **Add new JS animation helper**: Add function to `index.ts`, return `AnimationHandle`
- **Change timing/easing globally**: Edit tokens in `tokens.css` — never hardcode in the library
- **Per-component override**: Set CSS vars on `:host` or inline via `style` attribute
- **Per-instance control**: Inline styles for dynamic values (e.g., `--stagger-idx`)
- **Testing**: Snapshot CSS string, assert sheet rules, visual regression
- **Optimization**: Keep CSS under 2-3KB, use `adoptedStyleSheets` for zero-duplication

### Integration with Project

- All animation tokens defined in `tokens.css` (single source of truth)
- Follows web component patterns (BaseComponent, shadow DOM)
- `adoptAnimations()` integrates with `adoptedStyleSheets` — no style tag pollution
- JS helpers read tokens at runtime via `getComputedStyle(document.documentElement)`
- `AnimationHandle.cancel()` enables immediate cleanup when components toggle rapidly
- Supports `prefers-reduced-motion` in both CSS (utility classes) and JS (helpers)
- Compatible with both light and dark themes (no color definitions in the library)
- Bundled automatically by esbuild from `client/app.ts`

### Known Pitfalls

#### Exit animations: hide element before cleaning up inline styles

When an element is animated to an "exit" state (e.g., scaled down, faded out) and then removed from the DOM on the next render cycle, `cleanupStyles()` must **not** restore the element to its natural visible state before removal. Clearing inline `transform`/`opacity` causes the element to snap back to full size for one or more frames — visually jarring, especially when it is the last item in a list.

**Fix**: Set `element.style.display = "none"` immediately before calling `cleanupStyles()` in any exit/dismiss animation's `onComplete` handler. This ensures the element stays invisible between style cleanup and DOM removal.

```typescript
// ✅ Correct — element stays hidden until re-render removes it
function onComplete() {
  element.style.display = "none";
  cleanupStyles(element);
  resolvePromise();
}

// ❌ Wrong — element snaps back to full size for 1+ frames
function onComplete() {
  cleanupStyles(element); // resets transform & opacity → visible flash
  resolvePromise();
}
```

This applies to `animateDismiss()` and any future exit animation helper. Show/enter animations (e.g., `animateSlide(show=true)`) are not affected because their end state matches the element's natural style.

Last updated: February 23, 2026
