Compare commits

..
77 changed files with 5307 additions and 4466 deletions

No files matched your search

Whitespace-only changes.
-210
View File
@@ -1,210 +0,0 @@
---
name: 60fps-animation
description: This skill should be used when the user asks to "fix janky CSS animation", "make animation 60fps", "stop layout thrashing", "animate width/height/top/left smoothly", "convert animation to transform", "animate box-shadow performantly", "animate height auto", "FLIP animation", or "why is my scroll/hover animation choppy".
version: 0.1.0
---
# Performant Web Animation
Eliminate the #1 cause of janky web animation: animating properties that force the browser to recalculate layout (reflow) or repaint on every frame. The browser renders in stages — **layout → paint → composite**. Animating `width`, `height`, `top`, `left`, `margin`, `padding`, `box-shadow`, or `filter` re-runs layout and/or paint each frame, blocking the main thread. Animating **`transform`** and **`opacity`** runs entirely on the compositor (often the GPU), skipping layout and paint, which is what makes animation smooth at 60/120fps.
## When to use
Use when an animation stutters or drops frames, when a hover/scroll effect feels heavy, when animating size/position/shadow, when a layout change needs to animate smoothly (cards reordering, an element moving between containers), when animating `height: auto`, or when reviewing animation code for performance.
## Core rule: animate only transform and opacity
Map every "expensive" animation to a cheap equivalent.
| Animating (expensive) | Triggers | Replace with (cheap) |
|---|---|---|
| `width` / `height` | Layout + Paint | `transform: scaleX()/scaleY()` (+ FLIP for true size) |
| `top` / `left` / `margin` | Layout + Paint | `transform: translate()` |
| `box-shadow` | Paint | Animate `opacity` of a pseudo-element holding the shadow |
| `filter: blur()` | Paint (heavy) | Cross-fade two layers via `opacity`, or accept sparingly |
| `background-position` | Paint | `transform: translate()` on a child layer |
| `color` / `background` | Paint | Often acceptable; or cross-fade layers |
### Position and size via transform
```css
/* BAD: animates layout every frame */
.box { transition: left 300ms, width 300ms; left: 0; width: 100px; }
.box:hover { left: 200px; width: 200px; }
/* GOOD: compositor-only */
.box {
transition: transform 300ms ease;
transform: translateX(0) scaleX(1);
transform-origin: left center;
}
.box:hover { transform: translateX(200px) scaleX(2); }
```
`scaleX` distorts inner content (text stretches). For true resizing without distortion, use **FLIP**.
## Cheap box-shadow via pseudo-element opacity
Animating `box-shadow` repaints a large blurred region every frame. Instead paint the shadow once on a `::after`, then animate only its `opacity`.
```css
.card { position: relative; }
.card::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
box-shadow: 0 12px 28px rgba(0,0,0,0.35);
opacity: 0;
transition: opacity 300ms ease;
pointer-events: none;
}
.card:hover::after { opacity: 1; }
```
The blurred shadow is rasterized once; hovering only changes a compositor opacity — smooth at any frame rate.
## FLIP: animate layout changes cheaply
FLIP (First, Last, Invert, Play) animates a *layout* change (reorder, resize, move between containers) using only `transform`. Measure where the element was (First) and will be (Last), apply an inverting transform so it visually appears unmoved, then animate the transform back to identity (Play). The DOM ends in its real final layout; the motion is pure compositor work.
```js
function flip(el, mutate) {
const first = el.getBoundingClientRect(); // First
mutate(); // change the DOM/layout
const last = el.getBoundingClientRect(); // Last
const dx = first.left - last.left;
const dy = first.top - last.top;
const sx = first.width / last.width;
const sy = first.height / last.height;
el.animate(
[
{ transformOrigin: 'top left',
transform: `translate(${dx}px, ${dy}px) scale(${sx}, ${sy})` }, // Invert
{ transformOrigin: 'top left', transform: 'none' }, // Play
],
{ duration: 300, easing: 'cubic-bezier(0.2, 0, 0, 1)' }
);
}
// usage: animate an element moving to a new grid position
flip(card, () => targetContainer.appendChild(card));
```
The Web Animations API `animate()` runs the transform on the compositor. For many elements, batch all `getBoundingClientRect()` reads *before* any mutation (see layout thrashing below).
## Animating height: auto
`height: auto` is not interpolatable historically. Modern and fallback approaches:
```css
/* Modern (Chrome 129+/supporting browsers): opt size keywords into animation */
.panel {
interpolate-size: allow-keywords; /* enables animating to/from auto */
height: 0;
overflow: clip;
transition: height 300ms ease;
}
.panel.open { height: auto; }
/* calc-size() also works: height: calc-size(auto, size); */
```
```css
/* Robust fallback today: CSS grid 1fr -> 0fr */
.wrapper {
display: grid;
grid-template-rows: 0fr; /* collapsed */
transition: grid-template-rows 300ms ease;
}
.wrapper.open { grid-template-rows: 1fr; }
.wrapper > .content { overflow: hidden; min-height: 0; }
```
The grid trick animates the track size (compositor-friendly enough and broadly supported) and needs no JS height measurement. Use `interpolate-size: allow-keywords` / `calc-size(auto, size)` where the target browsers support it; keep the grid technique as the cross-browser default.
## Avoid layout thrashing (batch reads, then writes)
Reading a layout property (`offsetWidth`, `getBoundingClientRect`, `scrollTop`, `getComputedStyle`) after a write forces a *synchronous* reflow. Interleaving reads and writes in a loop ("layout thrashing") can run dozens of forced reflows per frame.
```js
// BAD: read, write, read, write... forces reflow each iteration
items.forEach((el) => {
const w = el.offsetWidth; // read (forces layout)
el.style.width = w * 1.5 + 'px'; // write (invalidates layout)
});
// GOOD: batch all reads, then all writes
const widths = items.map((el) => el.offsetWidth); // all reads
items.forEach((el, i) => { // all writes
el.style.width = widths[i] * 1.5 + 'px';
});
```
For frame-synced work, read in a `requestAnimationFrame` callback and apply writes; libraries like fastdom formalize this read/write scheduling.
## will-change: use sparingly
`will-change: transform` promotes an element to its own compositor layer ahead of time, avoiding a hitch at animation start. But every promoted layer costs GPU memory, and over-use degrades performance.
```css
.menu { will-change: transform; } /* only on elements about to animate */
```
Rules: apply just before the animation (e.g. on hover/parent state), remove it after (`will-change: auto`) when idle, never blanket-apply to many elements, and never leave it permanently on large/numerous nodes. A single `transform: translateZ(0)` hack does the same promotion but is harder to undo — prefer `will-change`.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
The deliverable is **one self-contained `.html`** that opens directly in a browser — the markup, the CSS/JS animation, and a freeze harness in one file. For this skill, verification is two-pronged: the frame must look right *and* be cheap to produce (compositor-only).
**Output contract:**
- One `.html`, deps via CDN if any, animation driven by CSS transitions/`@keyframes` or the Web Animations API.
- A freeze mechanism so a screenshot lands on a deterministic frame:
- CSS `@keyframes` → `?t=N` sets `el.style.animationDelay = (-N)+'s'; el.style.animationPlayState = 'paused'`.
- WAAPI / JS → keep the animation object and `anim.pause(); anim.currentTime = N*1000`.
**Verify loop — freeze → screenshot, then profile for jank:**
1. Open headless at start / mid / end (`?t=0`, mid, end), screenshot each; confirm the motion is visually correct (no clipped/stretched text from `scaleX`, FLIP lands on the real layout, shadow/height transitions look right).
2. **Confirm it's compositor-only** — the whole point of this skill. Either:
- DevTools → Performance: record the animation, check there is **no purple "Layout" or green "Paint"** band per frame (only "Composite Layers").
- Or headless trace: `npx playwright screenshot` for the visual, plus a CDP/`tracing` capture, and assert no `Layout`/`Paint` events fire during the animation window.
3. Watch the FPS/“Frame Rendering Stats” overlay stays at 60 — dropped frames mean an expensive property slipped back in.
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/anim.html?t=0.3" frame.png
```
**Before you finish:**
1. Opens standalone — no console errors.
2. Only `transform` / `opacity` animate per frame; DevTools shows no per-frame Layout/Paint.
3. Screenshotted at start / mid / end — correct, no `scaleX` text distortion, FLIP lands true.
4. Holds 60fps; `will-change` applied just-in-time and removed when idle (no leftover layers).
5. `prefers-reduced-motion` honored.
## Quick reference
| Goal | Do this |
|---|---|
| Move element | `transform: translate()` |
| Resize without distortion | FLIP with `transform` |
| Shadow on hover | Animate `opacity` of shadow pseudo-element |
| Expand to content height | grid `0fr→1fr`, or `interpolate-size: allow-keywords` |
| Many elements moving | Batch `getBoundingClientRect` reads, then writes |
| Smooth animation start | `will-change` just-in-time, remove when idle |
| Verify it's compositor-only | DevTools Performance: no purple "Layout"/green "Paint" per frame |
## Gotchas
- `scaleX/scaleY` stretches text and children; use FLIP when content must stay crisp.
- `transform` percentages are relative to the element's own box, not the parent — different from `left: %`.
- Overusing `will-change` or `translateZ(0)` creates too many layers and *hurts* performance; promote only what animates.
- `filter` and `backdrop-filter` are compositor-related but still expensive; animate their presence via opacity cross-fades rather than animating the blur radius.
- The grid `1fr→0fr` content must have `overflow: hidden` and `min-height: 0` or it won't collapse.
- Always gate non-essential motion behind `@media (prefers-reduced-motion: reduce)`.
## Reference files
- `references/patterns-and-profiling.md` — full runnable examples (accordion, reorder list, parallax), DevTools profiling walkthrough to confirm compositor-only frames, reduced-motion patterns, and a property-cost cheat sheet.
@@ -1,132 +0,0 @@
# Patterns, profiling, and cost cheat sheet
## Property cost cheat sheet
| Property | Pipeline stage triggered | Verdict |
|---|---|---|
| `transform` | Composite only | Cheap — animate freely |
| `opacity` | Composite only | Cheap — animate freely |
| `filter` | Paint (+composite) | Expensive — avoid animating radius |
| `box-shadow` | Paint (large area) | Expensive — use pseudo + opacity |
| `width`, `height` | Layout + Paint | Avoid — use scale/FLIP |
| `top`, `left`, `right`, `bottom` | Layout + Paint | Avoid — use translate |
| `margin`, `padding` | Layout + Paint | Avoid |
| `border-width` | Layout + Paint | Avoid |
| `color`, `background-color` | Paint | Acceptable in moderation |
| `background-position` | Paint | Prefer translate on child |
| `clip-path` | Paint | Moderate; cheaper than filter |
## Accordion with grid height (no JS measurement)
```html
<button class="acc-trigger" aria-expanded="false">Details</button>
<div class="acc-wrap"><div class="acc-content">…content…</div></div>
```
```css
.acc-wrap {
display: grid;
grid-template-rows: 0fr;
transition: grid-template-rows 280ms cubic-bezier(0.2,0,0,1);
}
.acc-wrap.open { grid-template-rows: 1fr; }
.acc-content { overflow: hidden; min-height: 0; }
@media (prefers-reduced-motion: reduce) {
.acc-wrap { transition: none; }
}
```
```js
trigger.addEventListener('click', () => {
const open = wrap.classList.toggle('open');
trigger.setAttribute('aria-expanded', String(open));
});
```
## FLIP reorder list (batched reads)
```js
function flipReorder(container, mutate) {
const items = [...container.children];
const firsts = new Map(items.map((el) => [el, el.getBoundingClientRect()])); // all reads
mutate(); // e.g. sort/reinsert children
items.forEach((el) => {
const first = firsts.get(el);
const last = el.getBoundingClientRect();
const dx = first.left - last.left;
const dy = first.top - last.top;
if (dx || dy) {
el.animate(
[{ transform: `translate(${dx}px, ${dy}px)` }, { transform: 'none' }],
{ duration: 300, easing: 'cubic-bezier(0.2,0,0,1)' }
);
}
});
}
```
Reading every rect *before* mutating, and using `animate()` (compositor), keeps a 50-item reorder smooth.
## Just-in-time will-change
```js
el.addEventListener('pointerenter', () => { el.style.willChange = 'transform'; });
el.addEventListener('transitionend', () => { el.style.willChange = 'auto'; });
```
Promote on intent, demote when the animation ends, so layers don't accumulate.
## Reduced-motion gate
```css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.001ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.001ms !important;
scroll-behavior: auto !important;
}
}
```
For JS: `const reduce = matchMedia('(prefers-reduced-motion: reduce)').matches;` and skip/shorten animations when true.
## Profiling: prove it's compositor-only
1. Open DevTools > **Performance**. Record while the animation runs.
2. Inspect the flame chart frames during the animation:
- **Purple "Layout"** or **green "Paint"** bars on every frame → still hitting layout/paint; the animation is not compositor-only. Find the offending property.
- Only **"Composite Layers"** / GPU work per frame → success.
3. Use **Rendering** tab tools:
- **Paint flashing** — green flashes show repainted regions; a good transform/opacity animation flashes nothing.
- **Layer borders** — confirms which elements are on their own compositor layer (watch for too many from over-using `will-change`).
- **Frame Rendering Stats / FPS meter** — confirm a stable 60/120fps.
4. The **Layers** panel shows layer count and memory; excessive layers indicate `will-change` overuse.
## Parallax without scroll-jank
Drive parallax with `transform: translate3d()` updated inside a single `requestAnimationFrame` loop reading `scrollY` once per frame — never read layout per element per frame.
```js
let ticking = false;
addEventListener('scroll', () => {
if (!ticking) {
requestAnimationFrame(() => {
const y = window.scrollY; // single read
layers.forEach((l, i) => { // writes only
l.style.transform = `translate3d(0, ${y * (0.1 * (i + 1))}px, 0)`;
});
ticking = false;
});
ticking = true;
}
}, { passive: true });
```
`{ passive: true }` lets the browser scroll without waiting on the handler.
---
Stay on transform and opacity, profile the jank away, and motion holds 60fps. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=60fps-animation)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
@@ -1,231 +0,0 @@
---
name: accessible-animation
description: This skill should be used when the user asks to "respect prefers-reduced-motion", "honor reduced motion", "make my animations accessible", "fix vestibular / motion-sickness issues", "add a useReducedMotion hook", "gate GSAP / Framer Motion / Lenis for reduced motion", or "meet WCAG 2.3.3 / C39". Provides tiered (not all-or-nothing) reduced-motion patterns in CSS and JS.
version: 0.1.0
---
# Accessible Animation (Reduced Motion, Tiered)
Honor `prefers-reduced-motion: reduce` as a *graceful degradation*, not a kill switch. The OS-level setting (macOS: Settings > Accessibility > Display > Reduce motion; Windows: Settings > Accessibility > Visual effects > Animation effects; iOS/Android equivalents) signals that *vestibular-triggering* motion causes nausea, dizziness, or migraines. The correct response is to remove the dangerous motion while keeping orientation cues.
## When to use
Use when adding or auditing animation in a web UI, when a user reports motion sickness or WCAG findings, or when integrating animation libraries (GSAP, Framer Motion, Lenis smooth scroll, Anime.js, CSS keyframes) into an accessible product.
## The core principle: tier motion, do not nuke it
Removing *all* animation is a common over-correction. An instant state change with no transition can be more disorienting (elements teleport) and removes useful affordances (focus rings, loading spinners that communicate progress). Sort every animation into three tiers:
- **Tier 1 — Remove entirely (vestibular triggers).** Parallax; large-area slides/translates across the viewport; scale/zoom of large elements; 3D rotation and spin; continuous auto-playing carousels and marquees; smooth-scroll hijacking (Lenis/Locomotive); scroll-jacked pinned scenes; motion-path animation; anything that moves a large portion of the screen or implies depth/self-motion.
- **Tier 2 — Soften / shorten.** Replace movement with a short opacity fade (≤200ms). Reduce distance and duration. Keep the *fact* of a transition (so elements don't teleport) but strip the displacement. Replace a 600ms slide-in-from-left with a 150ms cross-fade.
- **Tier 3 — Always keep.** Opacity fades, color/background transitions, focus-ring transitions, loading indicators, and motion that is *essential* to meaning (WCAG allows essential animation). These rarely trigger vestibular responses because they imply no self-motion.
## CSS layer: media-query gating
Write motion as the default, then override under the reduce query. Prefer a global safety net plus targeted overrides.
```css
/* Global safety net: neutralize runaway motion but DO NOT set 0s blindly,
which can break JS that waits for transitionend/animationend. Use 0.01ms. */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important; /* stop infinite spins/marquees */
transition-duration: 0.01ms !important;
scroll-behavior: auto !important; /* kill smooth scroll */
}
}
```
The global net is a backstop. Layer *intentional, tiered* overrides on top so Tier 3 motion survives:
```css
.card {
transition: transform 400ms ease, opacity 400ms ease, background-color 200ms ease;
}
@media (prefers-reduced-motion: reduce) {
.card {
/* Tier 2: drop the transform (movement), keep opacity + color (Tier 3) */
transition: opacity 150ms ease, background-color 150ms ease;
}
.parallax-layer { transform: none !important; } /* Tier 1: remove */
.hero-zoom { animation: none !important; } /* Tier 1: remove */
}
```
Use the *positive* query `(prefers-reduced-motion: no-preference)` to opt motion IN, which is the safest pattern for elaborate effects:
```css
.hero { opacity: 1; } /* visible, static by default */
@media (prefers-reduced-motion: no-preference) {
.hero { animation: zoom-in 1.2s ease both; } /* only animate when allowed */
}
```
## JS layer: matchMedia gating
CSS cannot gate JS-driven animation (GSAP timelines, Framer's `animate`, canvas/WebGL, Lenis). Read the same signal via `matchMedia` and react to live changes (users toggle the OS setting without reloading).
```js
const REDUCE_QUERY = '(prefers-reduced-motion: reduce)';
export function prefersReducedMotion() {
return typeof window !== 'undefined'
&& window.matchMedia
&& window.matchMedia(REDUCE_QUERY).matches;
}
// Live updates: listen so toggling the OS setting takes effect immediately.
export function onReducedMotionChange(cb) {
const mq = window.matchMedia(REDUCE_QUERY);
const handler = (e) => cb(e.matches);
mq.addEventListener('change', handler); // modern API
return () => mq.removeEventListener('change', handler);
}
```
### Library gating, applied as one reusable layer
```js
// GSAP — use matchMedia(): GSAP reverts conditional setups on change.
import gsap from 'gsap';
const mm = gsap.matchMedia();
mm.add({
motionOK: '(prefers-reduced-motion: no-preference)',
motionReduce: '(prefers-reduced-motion: reduce)',
}, (ctx) => {
const { motionOK } = ctx.conditions;
if (motionOK) {
gsap.from('.hero', { y: 80, opacity: 0, duration: 1 }); // Tier 1 move
} else {
gsap.from('.hero', { opacity: 0, duration: 0.15 }); // Tier 2 fade
}
});
// Lenis smooth scroll — do not instantiate at all when reduced.
import Lenis from 'lenis';
let lenis = null;
if (!prefersReducedMotion()) {
lenis = new Lenis();
const raf = (t) => { lenis.raf(t); requestAnimationFrame(raf); };
requestAnimationFrame(raf);
}
```
## React: a `useReducedMotion` hook
```jsx
import { useState, useEffect } from 'react';
export function useReducedMotion() {
const query = '(prefers-reduced-motion: reduce)';
const get = () =>
typeof window !== 'undefined' && window.matchMedia
? window.matchMedia(query).matches
: false;
const [reduced, setReduced] = useState(get);
useEffect(() => {
const mq = window.matchMedia(query);
const onChange = () => setReduced(mq.matches);
onChange(); // sync after hydration
mq.addEventListener('change', onChange);
return () => mq.removeEventListener('change', onChange);
}, []);
return reduced;
}
```
```jsx
// Framer Motion has its own useReducedMotion(); the hook above also works.
import { motion } from 'framer-motion';
function Card() {
const reduced = useReducedMotion();
return (
<motion.div
initial={reduced ? { opacity: 0 } : { opacity: 0, y: 40 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: reduced ? 0.15 : 0.5 }}
/>
);
}
```
Initialize SSR-rendered state to `false` (motion) and re-sync in `useEffect` to avoid a hydration mismatch; the OS value is only known client-side.
## WCAG mapping
- **2.3.3 Animation from Interactions (AAA).** Motion triggered by interaction (scroll, hover) must be disable-able unless essential. Honoring `prefers-reduced-motion` is the standard technique.
- **C39 (CSS technique).** Use the `prefers-reduced-motion` query to prevent motion. This is the named sufficient technique.
- **2.2.2 Pause, Stop, Hide (A).** Any auto-playing motion lasting >5s must offer pause/stop. Auto-carousels and marquees fail this regardless of the media query — give a control too.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained demo the deliverable is **one HTML file that opens directly in a browser** — markup, CSS, and any JS (GSAP/`matchMedia` from CDN) inline, no build step. For *this* skill the verification is the point: you must screenshot **both** the normal and the reduced-motion path and confirm the tiering is correct.
**Output contract:**
- One `.html` file with the full motion AND its tiered reduced-motion overrides (CSS query + `matchMedia`/`gsap.matchMedia()` for JS-driven motion).
- A seek harness to freeze a frame, plus a way to force the reduced-motion code path for screenshots.
**Seek harness — freeze a frame, force the preference.** `?t=N` freezes the timeline; `?reduce=1` forces the reduced path even when the OS setting is off (CSS can't be toggled from JS, so query the same flag you gate JS on, and screenshot with the OS/browser preference emulated for the CSS layer):
```html
<script>
const q = new URLSearchParams(location.search);
const reduce = q.get("reduce") === "1"
|| window.matchMedia("(prefers-reduced-motion: reduce)").matches;
// build motion conditionally on `reduce` (Tier-1 removed, Tier-2 softened, Tier-3 kept)
const t = q.get("t");
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // GSAP; CSS: el.style.animationDelay=(-t)+"s"; playState="paused"
window.__ready = true;
</script>
```
**Verify loop — screenshot BOTH states:** capture the normal path AND the reduced path, mid-animation each, and confirm Tier-1 motion is gone, Tier-2 is a short fade, Tier-3 survives. Emulate the preference for the CSS layer (Playwright `--reduced-motion=reduce`; the agent's browser tool can emulate it too):
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/demo.html?t=0.6" normal.png
npx playwright screenshot --reduced-motion=reduce --wait-for-timeout=500 "file://$PWD/demo.html?t=0.6&reduce=1" reduced.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN (if any) loads.
2. The freeze + `?reduce=1` (and `--reduced-motion=reduce`) reliably exercises both code paths.
3. Screenshotted in BOTH states, mid-animation — normal looks intentional, reduced strips Tier-1/softens Tier-2.
4. `prefers-reduced-motion` honored as *tiering*, not a kill switch — no teleporting, Tier-3 fades/focus rings/spinners kept; any >5s auto-motion still has a pause control (2.2.2).
5. Easing is intentional in both paths — no accidental `linear`, durations sane (reduced fades ≤200ms, `0.01ms` not `0s`).
## Quick reference
| Motion type | Tier | Reduced behavior |
|---|---|---|
| Parallax / depth | 1 | Remove (`transform: none`) |
| Large slide / translate | 1 | Remove or replace with fade |
| Scale / zoom (large) | 1 | Remove |
| Spin / 3D rotate | 1 | Remove (`animation: none`) |
| Auto carousel / marquee | 1 | Stop + provide pause control (2.2.2) |
| Smooth-scroll (Lenis) | 1 | Don't instantiate |
| Small slide / pop-in | 2 | Cross-fade ≤200ms |
| Opacity fade | 3 | Keep (shorten if long) |
| Color / focus-ring transition | 3 | Keep |
| Loading spinner | 3 | Keep (essential feedback) |
## Gotchas
- `animation-duration: 0s` can break code waiting on `animationend`/`transitionend`; use `0.01ms` so the event still fires.
- The global `*` reset alone over-removes Tier 3 motion; always layer intentional overrides.
- Forgetting `animation-iteration-count: 1` leaves infinite spins running at near-zero duration (CPU churn, still animating).
- No media query covers JS/canvas/WebGL — gate those with `matchMedia` or the loop never stops.
- Toggling the OS setting fires no page reload; without a `change` listener the page keeps its stale state.
- SSR: reading `matchMedia` during render throws or mismatches; default to motion and sync in an effect.
- Auto-playing motion needs a visible pause control even when reduced-motion is off (2.2.2 is Level A).
## Reference files
- `references/patterns.md` — Full GSAP `matchMedia` teardown, Framer Motion `MotionConfig`, Lenis start/stop on live toggle, a reusable `animateWithMotionPreference` wrapper, marquee with pause control, and a tier-classification audit checklist.
@@ -1,196 +0,0 @@
# Reduced Motion — Detailed Patterns
## Reusable wrapper: animate with motion preference
A single helper that picks a "full" or "reduced" variant and stays live-reactive.
```js
const REDUCE = '(prefers-reduced-motion: reduce)';
export function createMotionController() {
const mq = window.matchMedia(REDUCE);
const listeners = new Set();
mq.addEventListener('change', () => listeners.forEach((fn) => fn(mq.matches)));
return {
get reduced() { return mq.matches; },
subscribe(fn) { listeners.add(fn); fn(mq.matches); return () => listeners.delete(fn); },
// Pick a variant object: { full, reduced }
pick(variants) { return mq.matches ? variants.reduced : variants.full; },
};
}
// Usage
const motion = createMotionController();
const opts = motion.pick({
full: { translateY: ['40px', '0'], opacity: [0, 1], duration: 500 },
reduced: { opacity: [0, 1], duration: 150 },
});
```
## GSAP: full matchMedia with teardown
`gsap.matchMedia()` automatically reverts (kills tweens, restores inline styles) when a condition stops matching, so toggling the OS setting cleans up correctly.
```js
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const mm = gsap.matchMedia();
mm.add({
motionOK: '(prefers-reduced-motion: no-preference)',
motionReduce: '(prefers-reduced-motion: reduce)',
}, (ctx) => {
const { motionOK } = ctx.conditions;
if (motionOK) {
// Tier 1 parallax — only when allowed
gsap.to('.parallax-layer', {
yPercent: -30,
ease: 'none',
scrollTrigger: { trigger: '.section', scrub: true },
});
gsap.from('.card', {
y: 60, opacity: 0, stagger: 0.1,
scrollTrigger: { trigger: '.grid', start: 'top 80%' },
});
} else {
// Reduced: no parallax at all; cards cross-fade in place (Tier 2)
gsap.from('.card', {
opacity: 0, duration: 0.15, stagger: 0.03,
scrollTrigger: { trigger: '.grid', start: 'top 80%' },
});
}
return () => { /* optional extra cleanup; mm reverts tweens automatically */ };
});
// Tear everything down (e.g. SPA route change)
// mm.revert();
```
## Framer Motion: MotionConfig for app-wide reduction
`MotionConfig reducedMotion="user"` makes every child `motion` component automatically drop transform/layout animations while keeping opacity. Set it once at the root.
```jsx
import { MotionConfig, motion } from 'framer-motion';
export function App() {
return (
<MotionConfig reducedMotion="user">
{/* All descendant motion components honor the OS setting */}
<motion.section
initial={{ opacity: 0, y: 80 }} // y is auto-dropped when reduced
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.6 }}
/>
</MotionConfig>
);
}
```
For per-component control, Framer's own hook:
```jsx
import { useReducedMotion } from 'framer-motion';
function Hero() {
const reduced = useReducedMotion();
const variants = reduced
? { hidden: { opacity: 0 }, show: { opacity: 1, transition: { duration: 0.15 } } }
: { hidden: { opacity: 0, scale: 0.9 }, show: { opacity: 1, scale: 1, transition: { duration: 0.8 } } };
return <motion.div variants={variants} initial="hidden" animate="show" />;
}
```
## Lenis: start/stop on live toggle
Lenis hijacks scroll (Tier 1). Destroy it when reduced motion turns on, recreate when it turns off.
```js
import Lenis from 'lenis';
let lenis = null;
let rafId = null;
function startLenis() {
if (lenis) return;
lenis = new Lenis({ smoothWheel: true });
const loop = (t) => { lenis.raf(t); rafId = requestAnimationFrame(loop); };
rafId = requestAnimationFrame(loop);
}
function stopLenis() {
if (!lenis) return;
cancelAnimationFrame(rafId);
lenis.destroy();
lenis = null;
// Restore native scroll so the page is still usable
document.documentElement.style.removeProperty('scroll-behavior');
}
const mq = window.matchMedia('(prefers-reduced-motion: reduce)');
function sync() { mq.matches ? stopLenis() : startLenis(); }
mq.addEventListener('change', sync);
sync();
```
## Auto-carousel / marquee with a pause control (WCAG 2.2.2)
Auto-playing motion longer than 5s needs a pause/stop control regardless of the media query. Reduced-motion users get it stopped by default; everyone gets the control.
```html
<div class="marquee" data-playing="true">
<button class="marquee__toggle" aria-pressed="false">Pause</button>
<ul class="marquee__track"><!-- items --></ul>
</div>
```
```css
.marquee__track { animation: scroll-left 20s linear infinite; }
.marquee[data-playing="false"] .marquee__track { animation-play-state: paused; }
@media (prefers-reduced-motion: reduce) {
.marquee__track { animation-play-state: paused; } /* paused by default */
}
@keyframes scroll-left { to { transform: translateX(-50%); } }
```
```js
const root = document.querySelector('.marquee');
const btn = root.querySelector('.marquee__toggle');
// Respect the OS setting for the initial state
if (window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
root.dataset.playing = 'false';
btn.textContent = 'Play';
btn.setAttribute('aria-pressed', 'true');
}
btn.addEventListener('click', () => {
const playing = root.dataset.playing === 'true';
root.dataset.playing = String(!playing);
btn.textContent = playing ? 'Play' : 'Pause';
btn.setAttribute('aria-pressed', String(playing));
});
```
## Tier classification audit checklist
For each animation in the codebase, ask in order:
1. Is it essential to meaning (e.g. a progress bar, a diagram step)? -> Tier 3, keep.
2. Does a large area move, scale, spin, or imply depth/self-motion (parallax, zoom hero, slide-over)? -> Tier 1, remove under reduce.
3. Is it a small entrance with displacement (pop-in, slide-up)? -> Tier 2, replace displacement with a ≤200ms opacity fade.
4. Is it only opacity/color/focus? -> Tier 3, keep (shorten if >300ms).
5. Does it auto-play >5s (carousel, marquee, looping video bg)? -> Add a pause control (2.2.2) on top of any tier handling.
## Testing
- macOS: System Settings > Accessibility > Display > Reduce motion.
- Windows 11: Settings > Accessibility > Visual effects > Animation effects (off).
- Chrome DevTools: Rendering panel > "Emulate CSS media feature prefers-reduced-motion".
- Verify the `change` listener: toggle the OS setting with the page open and confirm motion stops without reload.
- Confirm `transitionend`/`animationend`-dependent flows still complete (the `0.01ms` rule).
---
Honor prefers-reduced-motion at every tier and motion stays inclusive by default. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=accessible-animation)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
-179
View File
@@ -1,179 +0,0 @@
---
name: ascii-animation
description: This skill should be used when the user asks to "make an ASCII animation", "build a terminal/CLI intro or loader", "convert an image or video to ASCII art", "add an ASCII shader/post-effect to a canvas or Three.js scene", "create retro/hacker text-character motion", or "animate text characters with a brightness ramp". Covers generative ASCII fields, image/video/3D-to-ASCII, and animated character art for both web and terminal.
version: 0.1.0
---
# ASCII Animation
Render motion entirely with text characters. ASCII output is extremely lightweight, distinctive, and works in browsers (`<pre>`/canvas), terminals (ANSI), and over any 3D scene (Three.js `AsciiEffect`).
## When to use
- Build terminal/CLI intros, loaders, banners, or a retro/hacker aesthetic.
- Convert an image, video frame, or 3D scene into animated ASCII.
- Add an ASCII post-effect over an existing canvas/WebGL render.
- Create generative text fields (plasma, sine waves, noise, tunnels).
## Core concept: the brightness ramp
Map luminance (0..1) to a character whose ink density matches. Order characters dark-to-light. Pick the index with `Math.round(lum * (ramp.length - 1))`.
Common ramps (dark to light):
- Short (10): ` .:-=+*#%@`
- Medium (16): ` .'\`^",:;Il!i><~+_-?][}{1)(|/tfjrxnuvczXYUJCLQ0OZmwqpdbkhao*#MW&8%B@$` truncated — see table below.
- Standard 70-level (Paul Bourke), best for photos:
`` $@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'. `` (reverse for dark-on-light).
Compute relative luminance from sRGB (perceptual):
```js
const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; // 0..1
```
Invert when drawing dark text on a light background: `lum = 1 - lum`.
## Character cell aspect correction (the #1 gotcha)
Monospace character cells are taller than wide — roughly **0.5 width:height**. Sampling a square pixel grid produces a vertically stretched image. Correct by sampling **fewer rows than columns**: for a target of `cols` characters wide, use `rows = Math.round(cols * (imgH / imgW) * fontAspect)` where `fontAspect ≈ 0.5`. Equivalently, when drawing to an offscreen canvas, set its height to `cols * aspect * 0.5`.
## Web rendering: `<pre>` vs canvas
- **`<pre>` + textContent**: simplest. One string with `\n` per row. Fine up to ~120×60 chars at 30fps. Set `white-space: pre; font-family: monospace; line-height: 1;`.
- **Canvas `fillText`**: needed for per-character color, larger grids, or 60fps. Draw each char at `x * cellW, y * cellH`. Faster than thousands of DOM nodes.
Generative `<pre>` field (plasma):
```js
const pre = document.querySelector('pre');
const COLS = 100, ROWS = 50, ramp = ' .:-=+*#%@';
function frame(t) {
let out = '';
for (let y = 0; y < ROWS; y++) {
for (let x = 0; x < COLS; x++) {
const v = Math.sin(x * 0.2 + t * 0.001)
+ Math.sin(y * 0.3 + t * 0.0013)
+ Math.sin((x + y) * 0.15 + t * 0.0007);
const lum = (v + 3) / 6; // normalize -3..3 to 0..1
out += ramp[Math.round(lum * (ramp.length - 1))];
}
out += '\n';
}
pre.textContent = out;
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);
```
## Image / video to ASCII
Draw the source to a small offscreen canvas at `cols × rows`, read pixels with `getImageContext().getImageData`, then map each pixel to a character. For video, repeat per frame from a `<video>` element.
```js
function videoToAscii(video, cols = 120) {
const aspect = video.videoHeight / video.videoWidth;
const rows = Math.round(cols * aspect * 0.5); // cell aspect correction
const cv = document.createElement('canvas');
cv.width = cols; cv.height = rows;
const ctx = cv.getContext('2d', { willReadFrequently: true });
const ramp = ' .:-=+*#%@', pre = document.querySelector('pre');
(function tick() {
ctx.drawImage(video, 0, 0, cols, rows);
const { data } = ctx.getImageData(0, 0, cols, rows);
let out = '';
for (let i = 0; i < data.length; i += 4) {
const lum = (0.2126*data[i] + 0.7152*data[i+1] + 0.0722*data[i+2]) / 255;
out += ramp[Math.round(lum * (ramp.length - 1))];
if (((i / 4) + 1) % cols === 0) out += '\n';
}
pre.textContent = out;
requestAnimationFrame(tick);
})();
}
```
For Node image→ASCII, see `scripts/img-to-ascii.mjs`.
## 3D-to-ASCII with Three.js
`AsciiEffect` wraps a renderer and renders any scene as ASCII into a DOM element. Render through the effect, not the renderer.
```js
import { AsciiEffect } from 'three/addons/effects/AsciiEffect.js';
const effect = new AsciiEffect(renderer, ' .:-=+*#%@', { invert: true });
effect.setSize(innerWidth, innerHeight);
effect.domElement.style.color = '#0f0';
effect.domElement.style.backgroundColor = 'black';
document.body.appendChild(effect.domElement);
// in loop: effect.render(scene, camera); // NOT renderer.render
```
## Terminal / CLI animation
Loop with ANSI escape codes: hide the cursor, move to home, print the frame, throttle to 12–24 fps. Show the cursor again on exit.
```js
const ESC = '\x1b[';
process.stdout.write(ESC + '?25l'); // hide cursor
function frame(t) {
process.stdout.write(ESC + 'H'); // cursor to top-left
// build and write rows...
}
const id = setInterval(() => frame(Date.now()), 1000 / 20);
process.on('SIGINT', () => {
clearInterval(id);
process.stdout.write(ESC + '?25h' + ESC + '2J'); // show cursor, clear
process.exit();
});
```
Use `ESC + '2J'` to clear the whole screen, `ESC + 'H'` for home (cheaper per frame than clearing). Color with `\x1b[38;2;R;G;Bm` (truecolor) and reset with `\x1b[0m`.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained web ASCII piece (generative field, image/video→ASCII, `AsciiEffect` scene) the deliverable is **one HTML file that opens directly in a browser** — the `<pre>`/canvas, the ramp, and the rAF loop inline (Three.js from CDN if used). No build step. One file is the right tier; don't reach for a bundler. (Terminal/CLI pieces verify differently — capture stdout or a screenshot of the terminal.)
**Output contract:**
- One `.html` file: the render target, the brightness ramp, and the `requestAnimationFrame` loop in one inline `<script>`.
- Drive frames from an **injectable time** (not `Date.now()`/`performance.now()` directly) and seed any randomness, so a frame is reproducible.
**Seek harness — freeze the rAF loop on a deterministic frame.** `?t=N` renders exactly one frame at simulated time `N` instead of looping, so a screenshot is reproducible. Feed `N` where the loop reads time, and fix the seed:
```html
<script>
const t = new URLSearchParams(location.search).get("t");
// your frame(time){…} reads `time`, not Date.now(); RNG uses a fixed seed
if (t !== null) { frame(parseFloat(t)); } // render ONE frame, no rAF
else { (function loop(now){ frame(now); requestAnimationFrame(loop); })(0); }
window.__ready = true;
</script>
```
**Verify loop — render → freeze → screenshot → check:** render at a few simulated times (`?t=0`, `?t=1000`, `?t=2000`), screenshot each, and check **fidelity** (ramp reads dark→light correctly, motion evolves) plus **artifacts** (vertical stretch from missing cell-aspect correction, wrong invert on a light bg, clipped grid, FOUC before the monospace font loads — fonts settle the cell metrics, so wait). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/ascii.html?t=1000" frame-mid.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN (Three.js, if used) loads, monospace font applied.
2. `?t=N` renders one deterministic frame (injected time + fixed seed), no live loop.
3. Screenshotted at 3 simulated times — matches the brief, no vertical stretch or wrong-invert.
4. `prefers-reduced-motion` honored — stop/slow the rAF loop, show a static frame.
5. Easing is intentional — frame rate throttled on purpose (12–24fps for retro feel), ramp ordering deliberate.
## Quick reference
| Need | Approach |
|------|----------|
| Simple generative field | `<pre>` + `textContent`, sine/noise → ramp |
| Photo fidelity | 70-level Bourke ramp, luminance from sRGB weights |
| Per-char color / 60fps | Canvas `fillText` per cell |
| Video | `<video>` → offscreen canvas → `getImageData` per frame |
| 3D scene | Three.js `AsciiEffect.render(scene, camera)` |
| Terminal | ANSI `\x1b[H` home + throttle 12–24fps, hide cursor |
| Aspect fix | `rows = cols * imgAspect * 0.5` |
## Reference files
- `references/rendering.md` — Full brightness ramp tables (10/70/extended), pixel sampling math and cell aspect correction, `<pre>` vs canvas tradeoffs with code, ANSI terminal frame loop with truecolor, and complete `AsciiEffect` wiring.
- `scripts/img-to-ascii.mjs` — Runnable Node script that converts a PNG/JPG file to ASCII text, with `--cols`, `--invert`, and `--ramp` flags.
@@ -1,194 +0,0 @@
# ASCII Rendering Reference
Detailed tables, sampling math, and complete renderers for ASCII animation.
## Brightness ramp tables
Order is **dark → light**. Index into the ramp with `Math.round(lum * (ramp.length - 1))` where `lum` is 0..1.
### 10-level (compact, generative)
```
.:-=+*#%@
```
Good for low-resolution generative fields and terminals. Distinct steps, low banding artifacts.
### 70-level Paul Bourke ramp (photo fidelity)
```
$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,"^`'.
```
This is ordered **light → dark** (densest first). For luminance mapping, either reverse the string or use `index = Math.round((1 - lum) * (len - 1))`. Best results for grayscale photos; whitespace at the end represents black/empty.
### 16-level extended (balance)
```
.'`,^:";~-_+<>i!lI?/\|()1{}[]rcvunxzjftLCJUYXZO0Qoahkbdpqwm*WMB8&%$#@
```
Truncate or downsample to taste. For UI/loaders a hand-picked 8–12 char ramp usually looks cleaner than a 70-char ramp because the steps are visually distinct.
### Block / shade characters (Unicode, smoother gradient)
```
░▒▓█
```
Or with the 1/8 block fills for vertical bars: `▁▂▃▄▅▆▇█`. Renders as a near-continuous gradient in monospace fonts; great for waveforms, meters, and smooth fades. Requires a font with box-drawing glyphs (most monospace fonts have them).
## Luminance computation
Perceptual (sRGB-weighted, recommended):
```js
const lum = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255; // 0..1
```
Fast average (acceptable for stylized output):
```js
const lum = (r + g + b) / (3 * 255);
```
Invert for dark-on-light surfaces: `lum = 1 - lum`. Apply gamma to spread midtones: `lum = Math.pow(lum, 0.8)` (lower exponent brightens).
## Pixel sampling and cell aspect correction
Monospace cells are about twice as tall as wide. Real cell aspect depends on the font: measure once.
```js
function measureCellAspect(fontFamily = 'monospace', fontPx = 16) {
const cv = document.createElement('canvas');
const ctx = cv.getContext('2d');
ctx.font = `${fontPx}px ${fontFamily}`;
const w = ctx.measureText('M').width; // glyph advance width
const h = fontPx * 1.0; // with line-height: 1
return w / h; // ~0.5 for most fonts
}
```
Compute the character grid for a source image, correcting aspect so the picture is not vertically stretched:
```js
function gridSize(imgW, imgH, cols, cellAspect = 0.5) {
const rows = Math.round(cols * (imgH / imgW) * cellAspect);
return { cols, rows };
}
```
Draw the source into an offscreen canvas at exactly `cols × rows`, then read all pixels once with `getImageData(0, 0, cols, rows)`. One `getImageData` call per frame is far cheaper than per-pixel reads.
## `<pre>` vs canvas
| Aspect | `<pre>` + textContent | Canvas `fillText` |
|--------|----------------------|-------------------|
| Setup | trivial, one string | per-cell draw loop |
| Color | single color (or per-span, slow) | per-char color cheap |
| Max size | ~120×60 @ 30fps | thousands of cells @ 60fps |
| Selectable text | yes | no |
| Best for | generative fields, loaders | video, per-char color, large grids |
`<pre>` styling that avoids gaps and stretching:
```css
pre { font-family: ui-monospace, monospace; line-height: 1; letter-spacing: 0;
margin: 0; white-space: pre; }
```
Canvas per-char color renderer:
```js
function drawAsciiCanvas(ctx, chars, colors, cols, rows, cellW, cellH) {
ctx.clearRect(0, 0, cols * cellW, rows * cellH);
ctx.textBaseline = 'top';
ctx.font = `${cellH}px monospace`;
for (let y = 0; y < rows; y++) {
for (let x = 0; x < cols; x++) {
const i = y * cols + x;
ctx.fillStyle = colors[i]; // e.g. `rgb(r,g,b)`
ctx.fillText(chars[i], x * cellW, y * cellH);
}
}
}
```
## ANSI terminal frame loop (Node)
```js
const ESC = '\x1b[';
const out = process.stdout;
function start(render, fps = 20) {
out.write(ESC + '?25l'); // hide cursor
out.write(ESC + '2J'); // clear screen once
const interval = 1000 / fps;
let start = Date.now();
const id = setInterval(() => {
const t = Date.now() - start;
out.write(ESC + 'H'); // home (cheap, no full clear)
out.write(render(t, out.columns || 80, out.rows || 24));
}, interval);
const stop = () => {
clearInterval(id);
out.write(ESC + '0m' + ESC + '?25h' + ESC + '2J' + ESC + 'H');
process.exit(0);
};
process.on('SIGINT', stop);
return stop;
}
// Truecolor per character: foreground `\x1b[38;2;R;G;Bm`, reset `\x1b[0m`.
function colored(ch, r, g, b) {
return `${ESC}38;2;${r};${g};${b}m${ch}${ESC}0m`;
}
// Example: plasma using full terminal size
start((t, cols, rows) => {
const ramp = ' .:-=+*#%@';
let s = '';
for (let y = 0; y < rows - 1; y++) {
for (let x = 0; x < cols; x++) {
const v = Math.sin(x * 0.15 + t * 0.001)
+ Math.sin(y * 0.25 + t * 0.0015)
+ Math.sin((x + y) * 0.1 + t * 0.0008);
const lum = (v + 3) / 6;
s += ramp[Math.round(lum * (ramp.length - 1))];
}
s += '\n';
}
return s;
});
```
Notes: writing `ESC + 'H'` (home) and overwriting is much smoother than clearing the screen every frame, which causes flicker. Avoid printing a trailing newline on the last row or the terminal scrolls. `out.columns`/`out.rows` give the live terminal size; recompute the grid on `process.stdout.on('resize', ...)`.
## Three.js AsciiEffect — complete wiring
```js
import * as THREE from 'three';
import { AsciiEffect } from 'three/addons/effects/AsciiEffect.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
const renderer = new THREE.WebGLRenderer();
renderer.setSize(innerWidth, innerHeight);
const effect = new AsciiEffect(renderer, ' .:-=+*#%@', { invert: true, resolution: 0.2 });
effect.setSize(innerWidth, innerHeight);
effect.domElement.style.color = 'white';
effect.domElement.style.backgroundColor = 'black';
document.body.appendChild(effect.domElement); // append the EFFECT's DOM, not renderer.domElement
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(70, innerWidth / innerHeight, 1, 1000);
camera.position.z = 4;
scene.add(new THREE.PointLight(0xffffff, 3).position.set(5, 5, 5));
scene.add(new THREE.AmbientLight(0x808080));
const mesh = new THREE.Mesh(
new THREE.TorusKnotGeometry(1, 0.3, 100, 16),
new THREE.MeshStandardMaterial({ flatShading: true })
);
scene.add(mesh);
const controls = new OrbitControls(camera, effect.domElement); // attach to effect DOM
function animate(t) {
mesh.rotation.y = t * 0.0005;
effect.render(scene, camera); // render through the effect
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
addEventListener('resize', () => {
camera.aspect = innerWidth / innerHeight; camera.updateProjectionMatrix();
effect.setSize(innerWidth, innerHeight);
});
```
Key gotchas: append `effect.domElement` (not the renderer's canvas) and call `effect.render`, not `renderer.render`. `resolution` (default ~0.15) controls character density; lower = fewer, larger characters. Lighting matters — ASCII reads luminance, so use strong directional contrast and `flatShading` for crisp edges.
---
Map brightness to the right glyph ramp and the characters come alive. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=ascii-animation)** — the AI motion agent for editable, on-brand motion graphics.
@@ -1,64 +0,0 @@
#!/usr/bin/env node
// img-to-ascii.mjs — Convert a PNG/JPG image to ASCII text.
//
// Usage:
// node img-to-ascii.mjs <image> [--cols 120] [--invert] [--ramp " .:-=+*#%@"]
//
// Dependency: sharp (npm i sharp). Sharp decodes PNG/JPG/WebP and resizes.
//
// Notes:
// - Applies monospace cell-aspect correction (cells are ~2x taller than wide),
// so rows = cols * (imgH/imgW) * 0.5.
// - Luminance uses sRGB perceptual weights (0.2126/0.7152/0.0722).
import sharp from 'sharp';
function parseArgs(argv) {
const args = { cols: 120, invert: false, ramp: ' .:-=+*#%@', file: null };
for (let i = 2; i < argv.length; i++) {
const a = argv[i];
if (a === '--cols') args.cols = parseInt(argv[++i], 10);
else if (a === '--invert') args.invert = true;
else if (a === '--ramp') args.ramp = argv[++i];
else if (!a.startsWith('--')) args.file = a;
}
return args;
}
async function main() {
const { cols, invert, ramp, file } = parseArgs(process.argv);
if (!file) {
console.error('Usage: node img-to-ascii.mjs <image> [--cols N] [--invert] [--ramp "..."]');
process.exit(1);
}
const CELL_ASPECT = 0.5; // monospace width:height
const meta = await sharp(file).metadata();
const rows = Math.max(1, Math.round(cols * (meta.height / meta.width) * CELL_ASPECT));
// Resize to the character grid, drop alpha, get raw RGB bytes.
const { data } = await sharp(file)
.resize(cols, rows, { fit: 'fill' })
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const last = ramp.length - 1;
const lines = [];
for (let y = 0; y < rows; y++) {
let line = '';
for (let x = 0; x < cols; x++) {
const i = (y * cols + x) * 3;
let lum = (0.2126 * data[i] + 0.7152 * data[i + 1] + 0.0722 * data[i + 2]) / 255;
if (invert) lum = 1 - lum;
line += ramp[Math.round(lum * last)];
}
lines.push(line);
}
process.stdout.write(lines.join('\n') + '\n');
}
main().catch((err) => {
console.error('Error:', err.message);
process.exit(1);
});
Whitespace-only changes.
-177
View File
@@ -1,177 +0,0 @@
---
name: glassmorphism
description: This skill should be used when the user asks to "add a glassmorphism effect", "frosted glass UI", "Apple liquid glass style", "frosted blur card", "translucent glass panel animation", "make a frosted nav bar", "build a glass modal/dialog", "animate a glass card on hover", or "add a refracting liquid-glass hero". Covers frosted translucent panels with backdrop-filter blur, edge/specular highlights, SVG liquid-glass refraction, motion on hover/scroll/enter, and accessible reduced-transparency fallbacks.
version: 0.1.0
---
# Glassmorphism (Frosted & Liquid Glass)
Translucent, frosted UI: panels you can see through, blurred so the backdrop reads as soft color, rimmed by a bright edge of light, floating on layered shadow. The 2026 "liquid glass" evolution adds refraction — the background visibly bends through the panel — plus moving specular highlights. The goal is depth and material, not just opacity.
## When to use
- Frosted cards, nav bars, sidebars, modals/dialogs, and toolbars over busy/photo backgrounds
- Login/hero panels and overlays that should feel layered above the page
- Apple-style "liquid glass" heroes: refracting, slowly churning surfaces with a specular sweep
- Hover/scroll/enter motion on glass — frost deepening, highlight brightening, the panel lifting
- Any place where content needs to read as floating glass while staying legible
## The four ingredients of believable glass
Glass is never one property. Every panel needs all four, or it reads as a plain translucent box:
1. **Frost** — `backdrop-filter: blur()` plus `saturate()` to keep backdrop color vivid through the blur.
2. **Translucency** — a `background` with alpha (~0.08–0.18), never fully opaque, never fully clear.
3. **Edge of glass** — a hairline border *brighter* than the fill, ideally a lit top-left → dim bottom-right highlight, so the rim catches light.
4. **Depth** — layered `box-shadow`: an ambient drop shadow to float it, plus an `inset` top highlight and bottom shade to round the surface.
```css
.glass {
background: rgba(255, 255, 255, 0.12);
backdrop-filter: blur(16px) saturate(160%);
-webkit-backdrop-filter: blur(16px) saturate(160%); /* Safari needs the prefix */
border-radius: 20px;
border: 1px solid rgba(255, 255, 255, 0.25);
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.25), /* float */
inset 0 1px 0 rgba(255, 255, 255, 0.35), /* top highlight */
inset 0 -1px 0 rgba(0, 0, 0, 0.12); /* bottom shade */
}
```
Frost tiers: light UI chrome `blur(8–12px)` / alpha `0.08–0.14`; heavy modal/login `blur(24–40px)` / alpha `0.10–0.18`. Dark glass: fill `rgba(0,0,0,0.3)`, softer top highlight.
**`backdrop-filter` only blurs content that sits behind the element.** Over a flat background color it does nothing visible — glass needs a busy backdrop (image, gradient, video) to frost.
## Specular edge highlight and anti-banding grain
A flat border is dead. Draw a masked 1px ring with a lit corner via `::before`, and dither away gradient **banding** (stepped contour lines under heavy blur) with a faint `feTurbulence` noise overlay via `::after` at `opacity ≤ 0.06`. Full masked-border and inline-noise recipes are in `references/glass-recipes.md`.
## Motion: animate the glass, not the geometry
Animate the *qualities* of the glass — frost deepening, highlight brightening, the panel lifting — so it reads as the surface "leaning into the light."
```css
.glass {
transition: backdrop-filter .4s ease, background .4s ease,
box-shadow .4s ease, transform .4s cubic-bezier(.16,1,.3,1);
}
.glass:hover {
backdrop-filter: blur(24px) saturate(180%);
background: rgba(255,255,255,.18);
transform: translateY(-4px);
box-shadow: 0 16px 48px rgba(0,0,0,.3), inset 0 1px 0 rgba(255,255,255,.5);
}
```
- **Entrance** (frost resolving from clear): pair a `[data-enter]` transition with `@starting-style { backdrop-filter: blur(0); opacity: 0; transform: translateY(16px) }`.
- **Specular sweep**: a skewed white gradient animated across the surface on hover or as a slow ambient loop.
- **Caveat**: animating the blur *radius* is the most expensive thing here — the backdrop is re-blurred every frame. If hover janks, animate `transform`/`box-shadow`/`background` (cheap) and keep the blur delta small or snap it.
## Liquid glass — SVG refraction (the 2026 look)
Bend the background through the panel like a thick lens: drive `feDisplacementMap` from animated `feTurbulence`, applied via `filter` (it distorts the element's own pixels) layered over a `backdrop-filter` frost.
```html
<svg width="0" height="0" style="position:absolute"><filter id="liquid-glass">
<feTurbulence type="fractalNoise" baseFrequency="0.008 0.012" numOctaves="2" seed="3" result="n">
<animate attributeName="baseFrequency" dur="18s"
values="0.008 0.012;0.012 0.008;0.008 0.012" repeatCount="indefinite"/>
</feTurbulence>
<feDisplacementMap in="SourceGraphic" in2="n" scale="22" xChannelSelector="R" yChannelSelector="G"/>
</filter></svg>
```
`scale` = refraction strength (8–14 subtle, 20–30 pronounced, >40 molten). Lower `baseFrequency` = larger, slower waves (more liquid). Keep the `animate` `dur` long (12–20s) so it breathes. These filters are heavy — use on **one** hero element, not a grid.
## Performance — backdrop-filter is expensive
- Each glass element re-samples and blurs everything behind it. **Limit the count**; a dozen on screen tanks scroll FPS.
- Promote heavy glass to its own layer (`transform: translateZ(0)` or `will-change: transform`), and remove `will-change` after the animation.
- Don't stack `backdrop-filter` elements over each other — nested blur re-blurs the blur (quadratic cost).
- Big radii (>40px) over large areas are the worst case; cap radius and panel size.
## Accessibility — non-negotiable
Glass is decoration; content must stay legible and the effect must be defeatable.
```css
@media (prefers-reduced-transparency: reduce) {
.glass { background: #1a1a2e; backdrop-filter: none; -webkit-backdrop-filter: none; }
.glass::after { display: none; } /* drop grain */
}
@media (prefers-reduced-motion: reduce) {
.glass { transition: none; }
.liquid { filter: none; } /* stop the refraction churn */
}
@supports not (backdrop-filter: blur(1px)) {
.glass { background: rgba(30,30,50,.85); } /* opaque-enough fallback */
}
```
**Contrast over busy backgrounds**: translucent panels over photos can drop text below WCAG. Add a semi-opaque scrim or darkening gradient *under* the text, optionally `text-shadow: 0 1px 2px rgba(0,0,0,.4)`, and verify ≥ 4.5:1 body / ≥ 3:1 large against the *brightest* region of the backdrop.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained glass demo (card, nav, modal, liquid-glass hero) the deliverable is **one HTML file that opens directly in a browser** — markup, CSS, and (if liquid) one inline SVG filter, no build step. A single file is the right tier for a glass surface; don't reach for a bundler. The panel **must overlap a real backdrop** (drop in a photo or gradient) or there is nothing to frost and the demo lies.
**Output contract:**
- One `.html` file: a busy backdrop, your glass markup, the CSS (frost + edge highlight + grain + shadows), and any inline SVG `feDisplacementMap` filter.
- A way to land on the **resolved state** *and* a **frozen frame** of any loop — glass verifies by both state (rest/hover/enter) and time (the sweep/refraction).
- Include the freeze harness below so any moment can be pinned for inspection.
**Seek harness — pin a deterministic state + frame.** `?state=hover` forces the hover look; `?t=N` freezes CSS animations and the SVG refraction at `N` seconds, so a screenshot lands on a still, deterministic frame:
```html
<script>
const p = new URLSearchParams(location.search);
const state = p.get("state");
if (state) document.documentElement.dataset.state = state; // CSS keys off :root[data-state="hover"]
const t = p.get("t");
if (t !== null) {
document.getAnimations().forEach(a => { a.currentTime = parseFloat(t)*1000; a.pause(); }); // freeze CSS sweep
const svg = document.querySelector("svg");
svg?.pauseAnimations?.(); svg?.setCurrentTime?.(parseFloat(t)); // freeze refraction
}
window.__ready = true;
</script>
```
**Verify loop — render → set state/freeze → screenshot → check:** open each meaningful state (`?state=rest`, `?state=hover`) and a frozen loop frame (`?t=2`), screenshot, and confirm the glass **reads as glass** — blur and edge highlight visibly present, no color banding, text contrast holds over the backdrop — plus check **artifacts** (flat box because the backdrop is plain color, missing `-webkit-` prefix in Safari, refraction too strong/molten, jank from animating blur). Then load `prefers-reduced-transparency` and confirm the **solid fallback renders** legibly. Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/glass.html?state=hover" hover.png
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/glass.html?t=2" loop.png
```
To check the fallback headlessly, emulate the media feature (e.g. Playwright `--color-scheme`-style flags, or a `?reduced=1` query that toggles a class mirroring the media query) and screenshot that the panel is solid and readable.
**Before you finish:**
1. Opens standalone — no console errors; the glass overlaps a real busy backdrop, not a flat color.
2. Reads as glass — blur + bright edge highlight both visible, layered shadow floats it, no banding (grain present).
3. Text contrast holds over the brightest part of the backdrop (≥ 4.5:1 body).
4. `?state=` / `?t=N` freeze lands a deterministic, settled frame.
5. `prefers-reduced-transparency` → solid opaque panel; `prefers-reduced-motion` → refraction/sweep stopped; `@supports` fallback for no `backdrop-filter`.
6. Performance sane — glass count limited, blur not animated on a janky path, liquid refraction on one element only.
## Quick reference
| Need | Approach |
|------|----------|
| Base frost | `backdrop-filter: blur(16px) saturate(160%)` + alpha bg |
| Edge of glass | brighter `border` + masked `::before` lit-corner ring |
| Float / depth | `box-shadow` drop + `inset` top highlight & bottom shade |
| Kill banding | `feTurbulence` noise `::after`, `opacity ≤ .06` |
| Hover motion | transition `transform`/`box-shadow`/`background`, small blur delta |
| Entrance | `@starting-style { backdrop-filter: blur(0); opacity:0 }` |
| Liquid refraction | `feDisplacementMap` ← animated `feTurbulence`, via `filter` |
| Specular sweep | skewed white gradient animated across surface |
| Safari | always pair `-webkit-backdrop-filter` |
| Reduced transparency | solid opaque panel, drop grain |
| No backdrop-filter | `@supports not (...)` opaque-enough fallback |
## Reference files
- `references/glass-recipes.md` — full copy-paste recipes: base glass card with tiers, the masked specular edge ring, anti-banding grain, hover/enter/scroll motion, the specular sweep, the SVG `feDisplacementMap`/`feTurbulence` liquid-glass filter with tuning knobs, performance rules, the reduced-transparency/reduced-motion/`@supports` fallbacks, contrast defenses, and the standalone freeze harness.
@@ -1,242 +0,0 @@
# Glassmorphism Recipes
Copy-paste recipes for frosted translucent panels, the "edge of glass" highlight, animated liquid-glass refraction, and the reduced-transparency fallback. All standalone CSS + optional inline SVG — no build step.
## 1. The base glass card
The four ingredients of believable glass: **blur** (frost), **translucency** (you see through it), **edge highlight** (light catches the rim), **layered shadow** (it floats). Plus a touch of `saturate()` so the backdrop reads vivid through the frost.
```css
.glass {
/* translucency — never fully opaque, never fully clear */
background: rgba(255, 255, 255, 0.12);
/* frost: blur the backdrop, lift saturation so color survives the blur */
backdrop-filter: blur(16px) saturate(160%);
-webkit-backdrop-filter: blur(16px) saturate(160%); /* Safari still needs the prefix */
border-radius: 20px;
/* edge of glass: a hairline border slightly brighter than the fill */
border: 1px solid rgba(255, 255, 255, 0.25);
/* depth: ambient drop + a top inner highlight + a bottom inner shade */
box-shadow:
0 8px 32px rgba(0, 0, 0, 0.25),
inset 0 1px 0 rgba(255, 255, 255, 0.35),
inset 0 -1px 0 rgba(0, 0, 0, 0.12);
}
```
Tuning by tier:
- **Light frost** (UI chrome over content): `blur(8–12px)`, alpha `0.08–0.14`.
- **Heavy frost** (modal scrim, login card): `blur(24–40px)`, alpha `0.10–0.18`.
- Dark glass: swap the fill to `rgba(0,0,0,0.3)` and the top inner highlight to a softer white.
`backdrop-filter` only has anything to blur if there is content **behind** the element — it must overlap a busy background (image, gradient, video). On a flat color it looks like a plain translucent box.
## 2. The specular edge highlight (the rim of light)
A single border is flat. Real glass catches a bright sweep along the top-left edge and falls off. Layer a soft conic/linear highlight via a pseudo-element with a masked border.
```css
.glass {
position: relative;
isolation: isolate; /* keep the highlight blend local */
}
.glass::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
padding: 1px; /* border thickness */
background: linear-gradient(
135deg,
rgba(255, 255, 255, 0.7),
rgba(255, 255, 255, 0) 40%,
rgba(255, 255, 255, 0) 60%,
rgba(255, 255, 255, 0.25)
);
/* mask trick: show only the 1px ring, punch out the interior */
-webkit-mask:
linear-gradient(#000 0 0) content-box,
linear-gradient(#000 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
}
```
This gives the panel a lit top-left corner and a dim bottom-right, the cue the brain reads as "curved glass under a light."
## 3. Kill banding with grain
Heavy `blur()` over a smooth gradient produces visible color **banding** (stepped contour lines). A faint noise overlay dithers it away.
```css
.glass::after {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
pointer-events: none;
opacity: 0.04; /* barely there */
mix-blend-mode: overlay;
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='120' height='120'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
}
```
`feTurbulence` generates the noise tile inline — no asset file. Keep opacity ≤ 0.06 or it reads as texture, not dither.
## 4. Motion: animate the glass on hover / enter / scroll
Animate the *qualities* of the glass, not its geometry. Frost deepening and the highlight brightening on hover reads as the panel "leaning into the light."
```css
.glass {
transition:
backdrop-filter 0.4s ease,
background 0.4s ease,
box-shadow 0.4s ease,
transform 0.4s cubic-bezier(0.16, 1, 0.3, 1);
}
.glass:hover {
backdrop-filter: blur(24px) saturate(180%);
background: rgba(255, 255, 255, 0.18);
transform: translateY(-4px);
box-shadow:
0 16px 48px rgba(0, 0, 0, 0.3),
inset 0 1px 0 rgba(255, 255, 255, 0.5);
}
```
Caveat: animating `backdrop-filter` itself is the most expensive thing here — the backdrop is re-sampled and re-blurred every frame. If hover feels janky, animate only `transform` + `box-shadow` + `background` (cheaper) and snap the blur, or keep the blur change small.
**Entrance** (frost resolving in) reads beautifully with `@starting-style`:
```css
.glass[data-enter] {
transition: opacity 0.5s ease, backdrop-filter 0.6s ease, transform 0.5s ease;
}
@starting-style {
.glass[data-enter] {
opacity: 0;
backdrop-filter: blur(0px) saturate(100%);
transform: translateY(16px) scale(0.98);
}
}
```
**Specular sweep** — a moving glint across the surface on hover or as an ambient loop:
```css
.glass .sweep {
position: absolute; inset: 0; border-radius: inherit; overflow: hidden; pointer-events: none;
}
.glass .sweep::before {
content: ""; position: absolute; top: 0; left: -60%; width: 50%; height: 100%;
background: linear-gradient(105deg, transparent, rgba(255,255,255,0.35), transparent);
transform: skewX(-15deg);
animation: sweep 4s ease-in-out infinite;
}
@keyframes sweep { 0%,100% { left: -60%; } 50% { left: 110%; } }
```
## 5. Liquid glass — SVG refraction (the 2026 look)
Apple-style "liquid glass" bends the background as if seen through a thick, wobbling lens. Drive a `feDisplacementMap` from animated `feTurbulence` and apply it via `filter` (note: `filter`, not `backdrop-filter` — it distorts the element's own rendered content; layer it over a `backdrop-filter` frost for the full effect).
```html
<svg width="0" height="0" style="position:absolute">
<filter id="liquid-glass">
<feTurbulence type="fractalNoise" baseFrequency="0.008 0.012"
numOctaves="2" seed="3" result="noise">
<!-- animate the field so the refraction slowly churns -->
<animate attributeName="baseFrequency"
dur="18s" values="0.008 0.012; 0.012 0.008; 0.008 0.012"
repeatCount="indefinite"/>
</feTurbulence>
<feDisplacementMap in="SourceGraphic" in2="noise"
scale="22" xChannelSelector="R" yChannelSelector="G"/>
</filter>
</svg>
```
```css
.liquid {
backdrop-filter: blur(6px) saturate(150%); /* light frost under the refraction */
filter: url(#liquid-glass); /* the lens distortion */
}
```
Knobs:
- `scale` on `feDisplacementMap` = refraction strength. 8–14 = subtle ripple; 20–30 = pronounced lens; >40 = molten.
- Lower `baseFrequency` = larger, slower waves (more "liquid"); higher = tight, busy ripples.
- Animate `baseFrequency` (above) or `scale` for a living surface. Keep `dur` long (12–20s) so it breathes rather than shimmers.
Cost warning: SVG displacement filters are heavy and force off-GPU paths in some browsers. Use on **one** hero element, not a grid of cards. Test on a mid-range laptop; drop to plain `backdrop-filter` if frames stutter.
## 6. Performance — backdrop-filter is expensive
- Each `backdrop-filter` element re-samples and blurs everything behind it. **Limit the count** — a dozen glass cards on screen will tank scroll FPS.
- Promote heavy glass to its own compositor layer: `transform: translateZ(0)` or `will-change: transform` (remove `will-change` after the animation; leaving it on wastes memory).
- Avoid stacking `backdrop-filter` elements over each other (nested blur re-blurs the blur — quadratic cost).
- Prefer animating `transform`/`opacity`/`box-shadow` over animating the blur radius. If you must animate blur, keep the radius delta small.
- Big blur radii (>40px) over large areas are the single worst case; cap the radius and the panel size.
## 7. Accessibility — non-negotiable
Glass is decorative; the content on it must stay legible and the effect must be defeatable.
**Honor reduced transparency and reduced motion** — fall back to a solid, opaque panel:
```css
@media (prefers-reduced-transparency: reduce) {
.glass {
background: #1a1a2e; /* solid, accessible panel */
backdrop-filter: none;
-webkit-backdrop-filter: none;
border-color: rgba(255, 255, 255, 0.15);
}
.glass::after { display: none; } /* drop grain/noise */
}
@media (prefers-reduced-motion: reduce) {
.glass, .glass .sweep::before { transition: none; animation: none; }
.liquid { filter: none; } /* stop the churning refraction */
}
```
**Contrast over busy backgrounds.** Translucent panels over photos can drop text below WCAG contrast. Defenses:
- Put a contrast floor *under* the text: a semi-opaque scrim or a darkening gradient inside the panel.
- Add `text-shadow: 0 1px 2px rgba(0,0,0,0.4)` to body text on glass.
- Target ≥ 4.5:1 for body text, ≥ 3:1 for large text — and verify against the *brightest* region of the backdrop, not the average.
**Feature fallback** for browsers without `backdrop-filter`:
```css
@supports not (backdrop-filter: blur(1px)) {
.glass { background: rgba(30, 30, 50, 0.85); } /* opaque-enough fallback */
}
```
## 8. Standalone freeze harness
Glass demos verify by *state* (rest / hover / enter) and *time* (the sweep/refraction loop). Wire both so a screenshot lands deterministically:
```html
<script>
const p = new URLSearchParams(location.search);
const state = p.get("state"); // ?state=hover → force the hover look
if (state) document.documentElement.dataset.state = state;
const t = p.get("t"); // ?t=2 → freeze CSS animations at 2s
if (t !== null) {
document.getAnimations().forEach(a => { a.currentTime = parseFloat(t) * 1000; a.pause(); });
// SVG SMIL (the <animate>): pin the refraction frame too
document.querySelector("svg")?.pauseAnimations?.();
document.querySelector("svg")?.setCurrentTime?.(parseFloat(t));
}
window.__ready = true;
</script>
```
CSS drives the forced state: `:root[data-state="hover"] .glass { /* hover values */ }`.
---
Frosted glass that reads as glass — blur, edge light, and refraction, with a clean fallback. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=glassmorphism)** — the AI motion agent for editable, on-brand motion graphics.
View File
Whitespace-only changes.
-225
View File
@@ -1,225 +0,0 @@
---
name: gsap-web
description: This skill should be used when the user asks to "build a scroll animation", "add ScrollTrigger", "pin a section while scrolling", "scrub an animation to scroll", "create a hero timeline", "do a horizontal scroll section", "split text and animate words", "animate a layout change with GSAP Flip", "sync ScrollTrigger with Lenis", "Lenis smooth scroll jittery", "ScrollTrigger markers drift", "ScrollTrigger pins break with Lenis/Locomotive", or "set up smooth scroll with GSAP pinning". Covers GSAP timelines, ScrollTrigger, SplitText, Flip, and Lenis/Locomotive smooth-scroll sync for code-driven web motion.
version: 0.1.0
---
# GSAP for the Web
GSAP (GreenSock Animation Platform) is the workhorse for code-driven web motion: sequenced timelines, scroll-driven storytelling, text reveals, and layout transitions. As of GSAP 3.12+, every plugin (ScrollTrigger, SplitText, Flip, MotionPath, MorphSVG, Draggable, Observer) is 100% free, including for commercial use.
## When to use
- Scroll-driven storytelling: pinned sections, parallax, progress scrubbing, horizontal scroll
- Sequenced hero animations and complex multi-element timelines with precise overlap control
- Text reveals split into chars/words/lines (SplitText)
- Layout transitions where an element changes position/size/parent (Flip)
- Any motion needing fine timing control, easing precision, or imperative orchestration
## Install and register
```js
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
import { SplitText } from "gsap/SplitText";
import { Flip } from "gsap/Flip";
gsap.registerPlugin(ScrollTrigger, SplitText, Flip);
```
Plugins MUST be registered before use or they silently no-op. With a bundler, register once at app entry.
## Core techniques
### Timelines first
Prefer one timeline over many independent tweens — it gives a single playhead, relative positioning, and easy reversal.
```js
const tl = gsap.timeline({ defaults: { ease: "power3.out", duration: 0.6 } });
tl.from(".title", { yPercent: 100, opacity: 0 })
.from(".sub", { y: 20, opacity: 0 }, "-=0.3") // start 0.3s before prev ends
.from(".cta", { scale: 0.9, opacity: 0 }, "<"); // align to prev tween START
```
Position parameter cheat sheet:
- `"+=0.5"` / `"-=0.3"` — relative to the end of the timeline (gap / overlap)
- `"<"` — start of the previous tween; `">"` — end of the previous tween
- `"<0.2"` — 0.2s after the previous tween's start
- `"myLabel"` — at a named label added via `tl.addLabel("myLabel")`
Use `.from()` for entrances (animates FROM the given values TO current CSS), `.to()` for exits, `.fromTo()` when both ends must be explicit (most robust against re-runs).
### gsap.to vs set vs quickTo
```js
gsap.set(el, { autoAlpha: 0 }); // instant, no tween (autoAlpha = opacity + visibility)
const xTo = gsap.quickTo(el, "x", { duration: 0.4, ease: "power3" });
window.addEventListener("pointermove", (e) => xTo(e.clientX)); // fast repeated updates
```
`autoAlpha` is preferred over raw `opacity` because it also toggles `visibility:hidden` at 0, removing the element from hit-testing.
### ScrollTrigger basics
```js
gsap.to(".panel", {
xPercent: -100,
ease: "none",
scrollTrigger: {
trigger: ".wrap",
start: "top top", // when trigger top hits viewport top
end: "+=2000", // 2000px of scroll distance
pin: true, // freeze .wrap while the tween plays
scrub: 1, // tie progress to scrollbar (1 = 1s catch-up smoothing)
markers: true, // dev-only visual markers — remove for prod
},
});
```
Key semantics:
- `start`/`end` take `"triggerPos viewportPos"` (e.g. `"top center"`) or `"+=px"`.
- `scrub: true` locks animation progress to scroll exactly; `scrub: <number>` adds smoothing lag.
- `toggleActions: "play pause resume reverse"` controls onEnter/onLeave/onEnterBack/onLeaveBack for non-scrubbed triggers.
- Use `ease: "none"` for scrubbed tweens so motion tracks scroll linearly.
### Smooth scroll (Lenis) + ScrollTrigger
Pairing Lenis (or Locomotive) smooth scrolling with ScrollTrigger desyncs unless both run on one loop. Lenis smooths scroll on its own rAF while ScrollTrigger reads scroll on GSAP's ticker; when they tick independently ScrollTrigger samples a stale position. The fix: drive Lenis from GSAP's ticker and update ScrollTrigger on every Lenis scroll.
```js
import Lenis from "lenis";
const lenis = new Lenis({ duration: 1.2, smoothWheel: true });
lenis.on("scroll", ScrollTrigger.update); // 1. update ScrollTrigger on every Lenis scroll
gsap.ticker.add((t) => lenis.raf(t * 1000)); // 2. one loop: ticker drives Lenis (seconds → ms)
gsap.ticker.lagSmoothing(0); // 3. stop GSAP catch-up jitter on heavy frames
```
Critical: `gsap.ticker` passes time in **seconds**, `lenis.raf()` wants **milliseconds** — multiply by 1000. Do NOT also run a standalone `requestAnimationFrame(raf)` loop for Lenis; that double-drives it.
Common bugs:
- **Jitter/stutter** — a leftover `requestAnimationFrame(raf)` loop competing with the ticker, or missing `lagSmoothing(0)`. Remove the rogue loop; set lag smoothing to 0.
- **Markers drift** from their triggers — `ScrollTrigger.update` is not subscribed to `lenis.on("scroll", …)`.
- **Pins break** — under Lenis do NOT set a `scrollerProxy` (it scrolls the document). Under Locomotive you MUST wire `scrollerProxy` + `pinType` and set `scroller:` on every trigger.
- **Scroll stuck / flipped direction** — missing the `* 1000` unit conversion, or two loops out of order.
Cleanup on SPA unmount: `gsap.ticker.remove(update)` + `lenis.destroy()`, else loops stack per navigation. Gate behind `prefers-reduced-motion` (skip Lenis, run native scroll). Full Lenis + Locomotive wiring, anchor-link routing, `data-lenis-prevent`, React (`useGSAP`/`useEffect`), and a symptom→cause table are in `references/scrolltrigger-lenis.md`.
### SplitText (text reveal)
```js
const split = SplitText.create(".headline", { type: "lines, words", linesClass: "line" });
gsap.from(split.lines, { yPercent: 100, opacity: 0, stagger: 0.08, duration: 0.7, ease: "power4.out" });
```
Gotchas:
- Wrap line-mask reveals: set `overflow: hidden` on the line wrapper so `yPercent: 100` hides cleanly. Add `autoSplit: true` (GSAP 3.13+) to re-split on font load / resize.
- Call `split.revert()` before re-splitting or on unmount to restore original DOM and avoid duplicated nodes.
- Always split AFTER web fonts load (`document.fonts.ready.then(...)`) to prevent wrong line breaks.
### Flip (layout transitions)
Flip records state, lets the DOM change instantly, then animates the visual difference (FLIP technique). Ideal for grid<->list, expanding cards, and reparenting.
```js
const state = Flip.getState(".item"); // 1. capture BEFORE
container.classList.toggle("grid"); // 2. mutate DOM/CSS (instant)
Flip.from(state, { // 3. animate the delta
duration: 0.6, ease: "power2.inOut", stagger: 0.05,
absolute: true, // take items out of flow during move (prevents reflow jitter)
});
```
### Easing quick guide
- `power2/3.out` — entrances (fast then settle)
- `power2.inOut` — moves between two on-screen states
- `back.out(1.7)` — overshoot/pop (number = overshoot amount)
- `elastic.out(1, 0.3)` — bouncy, use sparingly
- `none` — scrubbed scroll tweens
- `steps(n)` — sprite/stepped motion
- Custom cubic-bezier equivalent: `CustomEase.create("x", "M0,0 C0.2,0 0,1 1,1")` (CustomEase is free)
## Performance and cleanup
- Animate `transform` (`x/y/xPercent/scale/rotation`) and `opacity` only — they are GPU-composited and skip layout/paint. Avoid animating `top/left/width/height`.
- Set `will-change: transform` on heavy/pinned elements; remove after.
- Batch many similar scroll reveals with `ScrollTrigger.batch()` instead of one trigger per element.
- After a viewport/content change, call `ScrollTrigger.refresh()`.
SPA / framework cleanup is mandatory — orphaned triggers cause memory leaks and ghost pinning. Use `gsap.context()` (or `useGSAP` from `@gsap/react`):
```js
useEffect(() => {
const ctx = gsap.context(() => {
// all gsap + ScrollTrigger code here
}, rootRef);
return () => ctx.revert(); // kills tweens, triggers, and reverts inline styles
}, []);
```
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained animation (hero, reveal, loop, micro-scene) the deliverable is **one HTML file that opens directly in a browser** — no build step, no framework, no render pipeline. Match the deliverable to the weight of the work: a single file is the right tier for web motion; don't reach for a bundler when one file does the job.
**Output contract:**
- One `.html` file: GSAP + plugins from CDN, your markup, and the animation in one inline `<script>`.
- All motion on **one master timeline** (`const tl = gsap.timeline()`) — a single playhead you can seek.
- Include the seek harness below so any moment can be frozen for inspection.
**Seek harness — freeze an exact moment for screenshots.** The web parallel of a video player's frame-pin: `?t=N` seeks the master timeline to `N` seconds and pauses, so a screenshot lands on a still, deterministic frame.
```html
<script>
// ... build your master timeline as `tl` ...
const t = new URLSearchParams(location.search).get("t");
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // frozen at t seconds
// no ?t → plays normally
window.__ready = true; // ready signal for headless wait
console.log("duration", tl.duration());
</script>
```
**Verify loop — render → freeze → screenshot → check:**
1. Open the file at three moments across the timeline — start, mid, end:
`…/anim.html?t=0`, `?t=<dur/2>`, `?t=<dur>`. Read `tl.duration()` from the console for the end time.
2. Screenshot each frozen frame.
3. Check both **fidelity** (does it match the brief?) and **artifacts** (clipped text, elements off-canvas, FOUC before fonts load, jank at seams). Output should look intentional and finished.
Any headless screenshot tool works — your agent's browser tool, or Playwright:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/anim.html?t=1.2" frame-mid.png
```
**Before you finish:**
1. Opens standalone in a browser — no console errors, no missing CDN.
2. All animation on one master timeline; `?t=N` freezes correctly.
3. Screenshotted at start / mid / end — matches the brief, no artifacts.
4. `prefers-reduced-motion` honored (timeline simplified or skipped).
5. Easing is intentional — no accidental `linear` on spatial motion.
A complete runnable template with the harness wired in is in `examples/standalone-template.html`.
## Quick reference
| Goal | API |
|------|-----|
| Sequence with overlap | `tl.from(...).from(..., "-=0.3")` |
| Pin while scrolling | `scrollTrigger:{ pin:true, end:"+=N" }` |
| Scrub to scroll | `scrollTrigger:{ scrub:1, ease:"none" }` |
| Reveal lines of text | `SplitText.create(el,{type:"lines"})` |
| Animate layout change | `Flip.getState` → mutate → `Flip.from` |
| Fast pointer follow | `gsap.quickTo(el,"x",{...})` |
| Kill everything | `ScrollTrigger.getAll().forEach(t=>t.kill())` |
## Reference files
- `references/scrolltrigger-cookbook.md` — pin, scrub, horizontal scroll, snap, `ScrollTrigger.batch()` reveals, parallax, nested triggers, and SPA cleanup patterns with full code.
- `references/scrolltrigger-lenis.md` — full ScrollTrigger + Lenis/Locomotive smooth-scroll sync: canonical wiring, `scrollerProxy`, anchor links, reduced-motion, React (`useGSAP`/`useEffect`), debugging checklist, and symptom→cause table.
- `examples/hero-timeline.js` — a complete, runnable hero entrance timeline with SplitText, staggered reveals, and reduced-motion handling.
- `examples/standalone-template.html` — the deliverable template: self-contained (CDN GSAP), one master timeline, the `?t=N` seek harness for screenshot verification, and reduced-motion handling.
@@ -1,67 +0,0 @@
/**
* hero-timeline.js — complete, runnable GSAP hero entrance.
*
* Markup expected:
* <section class="hero">
* <p class="hero__eyebrow">EYEBROW</p>
* <h1 class="hero__title">Big bold headline that wraps</h1>
* <p class="hero__sub">Supporting copy.</p>
* <div class="hero__actions"><a class="btn">Primary</a><a class="btn btn--ghost">Secondary</a></div>
* <img class="hero__art" src="art.svg" alt="" />
* </section>
*
* CSS prerequisite: each split line wrapper needs overflow:hidden for the mask reveal:
* .hero__title .line { overflow: hidden; }
*
* Install: npm i gsap @gsap/react
*/
import gsap from "gsap";
import { SplitText } from "gsap/SplitText";
gsap.registerPlugin(SplitText);
export function playHeroIntro(root = document) {
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
const q = gsap.utils.selector(root);
// Reduced motion: reveal everything instantly, no animation.
if (reduceMotion) {
gsap.set(q(".hero__eyebrow, .hero__sub, .hero__actions, .hero__art"), { autoAlpha: 1 });
gsap.set(q(".hero__title"), { autoAlpha: 1 });
return Promise.resolve();
}
// Wait for fonts so SplitText computes correct line breaks.
return document.fonts.ready.then(() => {
const titleEl = q(".hero__title")[0];
const split = new SplitText(titleEl, {
type: "lines",
linesClass: "line",
autoSplit: true, // GSAP 3.13+: re-split on resize/font swap
});
// Hidden start state (prevents flash of unstyled content).
gsap.set(q(".hero__eyebrow, .hero__sub, .hero__actions, .hero__art"), { autoAlpha: 0 });
gsap.set(titleEl, { autoAlpha: 1 });
const tl = gsap.timeline({
defaults: { ease: "power3.out", duration: 0.8 },
onComplete: () => split.revert(), // restore clean DOM once done (optional)
});
tl.from(".hero__eyebrow", { y: 16, autoAlpha: 0, duration: 0.5 })
.from(split.lines, { yPercent: 110, stagger: 0.12, duration: 0.9, ease: "power4.out" }, "-=0.2")
.from(".hero__sub", { y: 20, autoAlpha: 0 }, "-=0.6")
.from(".hero__actions .btn", { y: 12, autoAlpha: 0, stagger: 0.1, duration: 0.5 }, "-=0.4")
.from(".hero__art", { scale: 0.92, autoAlpha: 0, ease: "back.out(1.4)", duration: 1.1 }, "<0.1");
return tl;
});
}
// Auto-run on DOM ready when imported directly in a page.
if (typeof window !== "undefined" && document.querySelector(".hero")) {
if (document.readyState !== "loading") playHeroIntro();
else document.addEventListener("DOMContentLoaded", () => playHeroIntro());
}
@@ -1,59 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>loading</title>
<!-- GSAP core from CDN — no build step. Add plugins the same way if needed:
https://cdnjs.cloudflare.com/ajax/libs/gsap/3.13.0/ScrollTrigger.min.js -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.13.0/gsap.min.js"></script>
<style>
:root { color-scheme: dark; }
* { margin: 0; box-sizing: border-box; }
body {
min-height: 100svh; display: grid; place-items: center;
background: radial-gradient(120% 120% at 50% 0%, #1b1f3b 0%, #0a0a12 60%);
font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
color: #f4f5ff; overflow: hidden;
}
.stage { text-align: center; padding: 6vmin; }
.title { font-size: clamp(2.5rem, 9vw, 6rem); font-weight: 800; letter-spacing: -0.03em; line-height: 1; }
.sub { font-size: clamp(1rem, 3.2vw, 1.6rem); margin-top: 1.2rem; color: #aab; }
.cta { display: inline-block; margin-top: 2.4rem; padding: 0.9rem 1.8rem;
border-radius: 999px; background: #5b6cff; color: #fff; font-weight: 600; }
</style>
</head>
<body>
<main class="stage">
<h1 class="title">Ship it.</h1>
<p class="sub">A standalone, screenshot-verifiable GSAP scene.</p>
<a class="cta" href="#">Get started</a>
</main>
<script>
const reduce = matchMedia("(prefers-reduced-motion: reduce)").matches;
// ── One master timeline: a single playhead the harness can seek ──────────
const tl = gsap.timeline({ defaults: { ease: "power3.out", duration: 0.7 } });
if (reduce) {
// Reduced motion: no spatial movement — just make the final state visible.
gsap.set([".title", ".sub", ".cta"], { opacity: 1, y: 0 });
} else {
tl.from(".title", { yPercent: 110, opacity: 0, ease: "power4.out", duration: 0.9 })
.from(".sub", { y: 24, opacity: 0 }, "-=0.45")
.from(".cta", { scale: 0.9, opacity: 0, ease: "back.out(1.7)" }, "-=0.3");
}
// ── Seek harness: ?t=N freezes the timeline at N seconds for a clean shot ─
const t = new URLSearchParams(location.search).get("t");
if (t !== null) { tl.pause(); tl.seek(parseFloat(t)); } // deterministic frozen frame
// no ?t → plays normally on load
// ── Ready signals for headless verification ──────────────────────────────
window.__ready = true;
document.title = "ready";
console.log("duration", tl.duration()); // end time for the ?t=<dur> shot
</script>
</body>
</html>
@@ -1,181 +0,0 @@
# ScrollTrigger Cookbook
Runnable patterns for GSAP 3.12+. Register first:
```js
import gsap from "gsap";
import { ScrollTrigger } from "gsap/ScrollTrigger";
gsap.registerPlugin(ScrollTrigger);
```
## 1. Pin a section and scrub a timeline through it
The most common scrollytelling pattern: hold a section fixed and drive a multi-step timeline with scroll.
```js
const tl = gsap.timeline({
scrollTrigger: {
trigger: ".story",
start: "top top",
end: "+=3000", // total scroll distance the pin lasts
pin: true,
scrub: 1,
anticipatePin: 1, // reduces a 1-frame jump when pinning fast scroll
},
});
tl.from(".story .step-1", { autoAlpha: 0, y: 60 })
.from(".story .step-2", { autoAlpha: 0, y: 60 })
.to(".story .bg", { scale: 1.2, ease: "none" }, 0); // runs across whole timeline
```
Tips:
- Each tween occupies an equal slice of the pinned distance unless you set durations/positions.
- `pinSpacing: true` (default) adds padding so content below does not jump. Set `false` only when overlaying.
- If the pinned element is inside a transformed/`overflow` ancestor, pinning breaks — pin a top-level element or set `pinReparent: true`.
## 2. Horizontal scroll (panels move sideways as the page scrolls vertically)
```html
<section class="h-wrap"><div class="track">
<div class="panel">1</div><div class="panel">2</div><div class="panel">3</div>
</div></section>
```
```css
.track { display: flex; width: max-content; }
.panel { width: 100vw; height: 100vh; flex: 0 0 100vw; }
```
```js
const track = document.querySelector(".track");
gsap.to(track, {
x: () => -(track.scrollWidth - window.innerWidth), // function = recalculated on refresh
ease: "none",
scrollTrigger: {
trigger: ".h-wrap",
pin: true,
scrub: 1,
end: () => "+=" + (track.scrollWidth - window.innerWidth),
invalidateOnRefresh: true, // re-run the x function on resize
},
});
```
`invalidateOnRefresh: true` plus function-based values is the correct way to stay responsive.
## 3. Snap to sections
```js
gsap.to(".sections", {
scrollTrigger: {
trigger: ".sections",
pin: true,
scrub: 1,
end: "+=4000",
snap: {
snapTo: 1 / 4, // 5 evenly spaced points (labels also possible: "labels")
duration: { min: 0.2, max: 0.6 },
delay: 0.05,
ease: "power1.inOut",
},
},
});
```
To snap to timeline labels: build a labeled timeline and use `snap: "labelsDirectional"`.
## 4. Batch reveals (performant many-element fade-in)
Instead of creating one ScrollTrigger per card (expensive at scale), batch them:
```js
ScrollTrigger.batch(".card", {
start: "top 85%",
onEnter: (els) =>
gsap.from(els, { autoAlpha: 0, y: 40, stagger: 0.12, overwrite: true }),
onLeaveBack: (els) =>
gsap.to(els, { autoAlpha: 0, y: 40, stagger: 0.12, overwrite: true }),
});
```
Set the initial hidden state to avoid a flash before JS runs: `gsap.set(".card", { autoAlpha: 0 })`.
## 5. Parallax layers
```js
gsap.utils.toArray(".parallax").forEach((layer) => {
const depth = layer.dataset.depth || 0.3; // 0 = static, 1 = scrolls with page
gsap.to(layer, {
yPercent: -depth * 100,
ease: "none",
scrollTrigger: { trigger: layer.parentElement, scrub: true, start: "top bottom", end: "bottom top" },
});
});
```
## 6. Linked timelines / containerAnimation (triggers inside horizontal scroll)
To trigger animations off elements that move horizontally inside a pinned horizontal scroller, pass the horizontal tween as `containerAnimation`:
```js
const scrollTween = gsap.to(track, { x: -2000, ease: "none",
scrollTrigger: { trigger: ".h-wrap", pin: true, scrub: 1, end: "+=2000" } });
gsap.from(".panel-2 .title", {
autoAlpha: 0, y: 50,
scrollTrigger: { trigger: ".panel-2 .title", containerAnimation: scrollTween, start: "left center" },
});
```
Note `start: "left center"` uses horizontal keywords because the trigger moves horizontally.
## 7. Refresh on dynamic content
Images and lazy content change layout after triggers are computed. Refresh when ready:
```js
window.addEventListener("load", () => ScrollTrigger.refresh());
imagesLoaded(document.body, () => ScrollTrigger.refresh()); // if using imagesLoaded lib
```
For accordions/tabs that change height, call `ScrollTrigger.refresh()` after the layout settles.
## 8. SPA / React cleanup (critical)
Orphaned ScrollTriggers cause ghost pins, leaks, and stacking bugs on route changes. Always scope and revert.
React with `@gsap/react`:
```jsx
import { useGSAP } from "@gsap/react";
function Section() {
const root = useRef(null);
useGSAP(() => {
gsap.from(".item", {
autoAlpha: 0, y: 40, stagger: 0.1,
scrollTrigger: { trigger: ".item", start: "top 80%" },
});
}, { scope: root }); // auto-reverts on unmount
return <div ref={root}>...</div>;
}
```
Plain SPA / manual:
```js
const ctx = gsap.context(() => { /* all gsap code */ }, rootEl);
// on teardown / route leave:
ctx.revert();
```
Nuclear option (e.g. global router hook): `ScrollTrigger.getAll().forEach((t) => t.kill());`
## Debugging checklist
- Triggers fire at wrong scroll position → likely created before images loaded; call `ScrollTrigger.refresh()`.
- Pinned element jumps to top-left → it has a transformed/`will-change`/`overflow:hidden` ancestor; pin higher up.
- Animation plays once then never resets → set appropriate `toggleActions` or use `scrub`.
- Horizontal scroll not responsive → use function-based `x`/`end` + `invalidateOnRefresh: true`.
- Markers misaligned → leftover triggers from previous render; ensure cleanup runs.
@@ -1,255 +0,0 @@
# ScrollTrigger + Lenis / Locomotive smooth-scroll sync
Wire GSAP ScrollTrigger together with Lenis (or Locomotive) smooth scrolling so there is no jitter, no marker drift, no broken pins, and no flipped/laggy scroll direction. Every one of those bugs has the same root cause: two animation loops running independently. Lenis transforms the scroll position on its own `requestAnimationFrame` loop while ScrollTrigger reads scroll on GSAP's ticker — when they tick separately, ScrollTrigger samples a stale position and everything desyncs. The fix is to run one loop: let GSAP's ticker drive Lenis, and tell ScrollTrigger to update on every Lenis scroll.
## The one canonical wiring (Lenis)
This is the entire correct setup. Do not add a separate `requestAnimationFrame` loop for Lenis — that is the most common mistake and the source of nearly all desync.
```js
import Lenis from 'lenis';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
gsap.registerPlugin(ScrollTrigger);
const lenis = new Lenis({
duration: 1.2,
smoothWheel: true,
// do NOT enable Lenis's own rAF; GSAP's ticker drives it (below)
});
// 1. Update ScrollTrigger every time Lenis scrolls
lenis.on('scroll', ScrollTrigger.update);
// 2. Drive Lenis from GSAP's ticker (single shared loop).
// gsap.ticker time is in SECONDS; Lenis expects MILLISECONDS.
gsap.ticker.add((time) => {
lenis.raf(time * 1000);
});
// 3. Disable GSAP's lag smoothing so ScrollTrigger never defers/
// catches up against Lenis (prevents jitter on heavy frames)
gsap.ticker.lagSmoothing(0);
```
Three lines do all the work:
1. `lenis.on('scroll', ScrollTrigger.update)` — ScrollTrigger recomputes positions the instant Lenis moves the page, so triggers/markers/pins track the smoothed scroll exactly.
2. `gsap.ticker.add(time => lenis.raf(time * 1000))` — Lenis advances inside GSAP's loop, guaranteeing both run on the same frame and in the same order. Critical unit conversion: `gsap.ticker` passes seconds, `lenis.raf()` wants milliseconds, so multiply by 1000.
3. `gsap.ticker.lagSmoothing(0)` — disables GSAP's catch-up behavior that, combined with Lenis, causes visible jitter when a frame is slow.
After this, never call `requestAnimationFrame(raf)` for Lenis yourself. If any tutorial code has a standalone `function raf(time){ lenis.raf(time); requestAnimationFrame(raf) }` loop, delete it — it competes with the ticker and reintroduces jitter and direction lag.
## Locomotive Scroll variant
Locomotive needs `scrollerProxy` because it scrolls an inner element, not `window`. The principle is identical (one loop, update ScrollTrigger on scroll), but the proxy maps coordinates:
```js
const locoScroll = new LocomotiveScroll({
el: document.querySelector('[data-scroll-container]'),
smooth: true,
});
locoScroll.on('scroll', ScrollTrigger.update);
ScrollTrigger.scrollerProxy('[data-scroll-container]', {
scrollTop(value) {
return arguments.length
? locoScroll.scrollTo(value, { duration: 0, disableLerp: true })
: locoScroll.scroll.instance.scroll.y;
},
getBoundingClientRect() {
return { top: 0, left: 0, width: innerWidth, height: innerHeight };
},
pinType: document.querySelector('[data-scroll-container]').style.transform
? 'transform' : 'fixed',
});
ScrollTrigger.addEventListener('refresh', () => locoScroll.update());
ScrollTrigger.refresh();
```
Every ScrollTrigger then needs `scroller: '[data-scroll-container]'`. Lenis is simpler because it scrolls the real document, so no `scrollerProxy` is needed.
## Pins, refresh, and resize
- Pinned ScrollTriggers work without `scrollerProxy` under Lenis because Lenis scrolls the document body. If pins still jump, ensure no rogue rAF loop exists and that `ScrollTrigger.update` is wired.
- On dynamic content/resize, call `ScrollTrigger.refresh()` after layout settles. With Lenis, also call `lenis.resize()` if container size changes.
- For elements that should *not* be smoothed (e.g. a modal that scrolls natively), mark with `data-lenis-prevent` so Lenis ignores them.
## Anchor links with smooth scroll
Native `<a href="#section">` jumps bypass Lenis (instant jump, then Lenis fights it). Route anchors through `lenis.scrollTo`:
```js
document.querySelectorAll('a[href^="#"]').forEach((a) => {
a.addEventListener('click', (e) => {
const id = a.getAttribute('href');
if (id.length > 1) {
e.preventDefault();
lenis.scrollTo(id, { offset: 0 }); // accepts selector, element, or number
}
});
});
```
If a sticky header overlaps the target, pass a negative offset or an offset callback:
```js
lenis.scrollTo(targetEl, { offset: -80 }); // 80px sticky header
```
## Reduced-motion gate
Respect `prefers-reduced-motion`: skip smooth scrolling entirely (do not instantiate Lenis, or stop it) and let ScrollTrigger run on native scroll.
```js
const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
let lenis;
if (!prefersReduced) {
lenis = new Lenis({ duration: 1.2 });
lenis.on('scroll', ScrollTrigger.update);
gsap.ticker.add((time) => lenis.raf(time * 1000));
gsap.ticker.lagSmoothing(0);
}
// ScrollTrigger animations are defined normally and work with or without Lenis
```
## Cleanup (SPA / React / route changes)
Destroy Lenis and remove the ticker callback on unmount, or stacked loops accumulate:
```js
function setup() {
const update = (time) => lenis.raf(time * 1000);
lenis.on('scroll', ScrollTrigger.update);
gsap.ticker.add(update);
gsap.ticker.lagSmoothing(0);
return () => {
gsap.ticker.remove(update);
lenis.destroy();
ScrollTrigger.getAll().forEach((t) => t.kill());
};
}
```
## Debugging checklist (work top to bottom)
1. **Is there a rogue rAF loop?** Search the codebase for `requestAnimationFrame` near `lenis.raf`. If Lenis is also driven by `gsap.ticker`, delete the standalone loop. Two loops = jitter, lag, flipped feel.
2. **Unit conversion present?** Confirm `lenis.raf(time * 1000)` inside the ticker. Missing `* 1000` makes scroll feel stuck or wildly slow.
3. **Is `ScrollTrigger.update` subscribed?** `lenis.on('scroll', ScrollTrigger.update)` must exist. Without it, markers and triggers drift behind the smoothed position.
4. **Is `lagSmoothing(0)` set?** Without it, heavy frames cause GSAP to "catch up", visible as jitter.
5. **Markers on for diagnosis.** Add `markers: true` to a trigger. If markers sit at the *native* scroll position but content moves with smoothed scroll, the update subscription is missing or a proxy is mis-set.
6. **Pins jumping?** Confirm no proxy is set for Lenis (it scrolls the document). For Locomotive, confirm `pinType` and `scroller` are correct.
7. **After dynamic content / fonts / images load**, call `ScrollTrigger.refresh()`. Stale measurements cause triggers to fire at wrong offsets.
8. **Nested scroll areas** (modals, code blocks) misbehave? Add `data-lenis-prevent` to the scrollable child.
9. **Cleanup on route change?** In SPAs, verify `gsap.ticker.remove(update)`, `lenis.destroy()`, and killing ScrollTriggers — otherwise each navigation stacks another loop.
## Symptom → cause table
| Symptom | Most likely cause |
|---|---|
| General jitter/stutter | Standalone rAF loop + ticker both driving Lenis |
| Scroll stuck / barely moves | Missing `* 1000` unit conversion |
| Markers offset from triggers | `ScrollTrigger.update` not bound to `lenis.on('scroll')` |
| Jitter only on heavy frames | `lagSmoothing(0)` not set |
| Pins jump / break | Proxy wrongly set under Lenis, or wrong `pinType` (Loco) |
| Animations a frame behind | Two loops out of order; consolidate to one ticker |
| Anchor links jump then snap back | Native `#hash` jump not routed via `lenis.scrollTo` |
| Triggers fire at wrong scroll position | Missing `ScrollTrigger.refresh()` after content/layout change |
| Worse after each route change | No cleanup; loops/triggers accumulating |
| Inner scroll container won't scroll | Lenis intercepting; add `data-lenis-prevent` |
## Complete React integration (useGSAP)
```jsx
'use client';
import { useRef } from 'react';
import Lenis from 'lenis';
import gsap from 'gsap';
import { ScrollTrigger } from 'gsap/ScrollTrigger';
import { useGSAP } from '@gsap/react';
gsap.registerPlugin(ScrollTrigger, useGSAP);
export default function ScrollSection() {
const root = useRef(null);
useGSAP(() => {
const prefersReduced = matchMedia('(prefers-reduced-motion: reduce)').matches;
let lenis;
let update;
if (!prefersReduced) {
lenis = new Lenis({ duration: 1.2, smoothWheel: true });
lenis.on('scroll', ScrollTrigger.update);
update = (time) => lenis.raf(time * 1000);
gsap.ticker.add(update);
gsap.ticker.lagSmoothing(0);
}
gsap.to('.panel', {
xPercent: -100,
ease: 'none',
scrollTrigger: {
trigger: '.panel',
start: 'top top',
end: '+=1500',
scrub: true,
pin: true,
// markers: true, // enable while debugging
},
});
return () => {
if (lenis) {
gsap.ticker.remove(update);
lenis.destroy();
}
};
}, { scope: root });
return (
<div ref={root}>
<section className="panel">…</section>
</div>
);
}
```
`useGSAP` auto-reverts GSAP tweens/ScrollTriggers created in its scope on unmount; the returned function additionally tears down Lenis and the ticker callback so nothing leaks across navigations.
## Plain useEffect equivalent
```jsx
useEffect(() => {
const lenis = new Lenis({ duration: 1.2 });
lenis.on('scroll', ScrollTrigger.update);
const update = (t) => lenis.raf(t * 1000);
gsap.ticker.add(update);
gsap.ticker.lagSmoothing(0);
const ctx = gsap.context(() => {
// ...ScrollTrigger animations here...
});
return () => {
gsap.ticker.remove(update);
lenis.destroy();
ctx.revert();
};
}, []);
```
## Excluding regions from smooth scroll
```html
<div class="code-block" data-lenis-prevent>…natively scrollable…</div>
```
`data-lenis-prevent` on a scrollable element makes Lenis ignore wheel/touch there, so inner scrolling works normally while the page stays smooth.
---
Sync ScrollTrigger to smooth scroll and the timeline tracks the page perfectly. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=gsap-web)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
-180
View File
@@ -1,180 +0,0 @@
---
name: lottie-animation
description: This skill should be used when the user asks to "add a Lottie animation", "play a .lottie or .json animation", "integrate a Bodymovin/After Effects animation on web or mobile", "control Lottie playback / segments", "make a scroll-driven Lottie", "recolor a Lottie at runtime", or "export an AE animation to Lottie". Covers dotLottie/lottie-web integration, playback control, interactivity, theming, and the AE export checklist.
version: 0.1.0
---
# Lottie Animation
The bridge from After Effects to product: vector animation shipped as JSON (or zipped `.lottie`), tiny and resolution-independent, played by a runtime on web, iOS, Android, and React Native. This skill covers integrating, controlling, and exporting Lottie.
## When to use
- Ship a designer's AE animation to web/iOS/Android/React Native
- Looping illustrations, onboarding, empty states, animated icons
- Scroll-driven or interaction-driven vector playback (hover, click, cursor)
- Runtime theming/recoloring instead of re-exporting per brand
## Formats: .json vs .lottie
- `.json` — the raw Bodymovin output. Human-readable, larger.
- `.lottie` — a zipped container (often 60–80% smaller) that can bundle multiple animations, images, and theming. Preferred for shipping. Player: `@lottiefiles/dotlottie-web` (modern, canvas + WASM) supersedes the older `lottie-web`.
Prefer the **dotLottie** runtime for new work; use `lottie-web` only for legacy `.json` + SVG renderer needs.
## Core workflow (web, dotLottie)
```bash
npm i @lottiefiles/dotlottie-web # vanilla
npm i @lottiefiles/dotlottie-react # React wrapper
```
Vanilla:
```js
import { DotLottie } from "@lottiefiles/dotlottie-web";
const dotLottie = new DotLottie({
canvas: document.querySelector("#lottie"), // a <canvas> element
src: "/hero.lottie", // or .json
loop: true,
autoplay: true,
// speed: 1, mode: "forward" | "reverse" | "bounce", renderConfig: { autoResize: true }
});
```
React:
```jsx
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
function Hero() {
return <DotLottieReact src="/hero.lottie" loop autoplay style={{ width: 320 }} />;
}
```
Capture the instance to control it:
```jsx
const [dl, setDl] = useState(null);
<DotLottieReact src="/icon.lottie" dotLottieRefCallback={setDl} />;
// dl?.play(); dl?.pause(); dl?.setSpeed(2);
```
## Playback control
```js
dotLottie.play();
dotLottie.pause();
dotLottie.stop();
dotLottie.setSpeed(1.5);
dotLottie.setMode("bounce"); // forward | reverse | bounce | reverse-bounce
dotLottie.setFrame(42); // jump to a frame
dotLottie.setSegment(30, 90); // constrain playback to a frame range (e.g. a "loading" loop)
```
Events drive sequencing and UI:
```js
dotLottie.addEventListener("load", () => { /* totalFrames now available */ });
dotLottie.addEventListener("complete", () => { /* non-looping playback finished */ });
dotLottie.addEventListener("frame", ({ currentFrame }) => { /* per-frame */ });
```
State-machine style (e.g. button that plays "checked" segment then idles): play a segment, listen for `complete`, then `setSegment` to the idle loop.
## Scroll-driven Lottie (no GSAP needed)
Map scroll progress (0–1) to a frame. Pause autoplay and drive frames yourself.
```js
const dotLottie = new DotLottie({ canvas, src: "/scroll.lottie", autoplay: false });
let total = 0;
dotLottie.addEventListener("load", () => { total = dotLottie.totalFrames; });
window.addEventListener("scroll", () => {
const el = canvas.closest(".scrolly");
const rect = el.getBoundingClientRect();
const p = clamp(-rect.top / (rect.height - window.innerHeight), 0, 1); // 0..1 through the section
dotLottie.setFrame(p * (total - 1));
}, { passive: true });
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
```
For richer interaction (hover-to-play, click toggles, cursor-follow) without writing the wiring, use `@lottiefiles/lottie-interactivity`, which maps `scroll`, `hover`, `click`, `play`, and `cursor` modes to frame ranges declaratively.
## Runtime theming / recoloring
Two paths:
- **dotLottie themes**: a `.lottie` can embed named color themes; switch with `dotLottie.setTheme("dark")` / `loadTheme(...)`. Authored in LottieFiles tooling — no re-export to recolor.
- **Manual color override**: load the JSON, walk `layers[].shapes[]` and patch `c.k` color arrays (normalized 0–1 RGBA), then init the player with the modified object. Brittle (depends on layer structure) — prefer themes or CSS-driven SVG-renderer (`lottie-web` `rendererSettings`) when you must restyle by class.
## Mobile runtimes (parity)
- iOS — `lottie-ios` (`LottieAnimationView`): `.play()`, `.currentProgress`, `.play(fromFrame:toFrame:)`.
- Android — `lottie-android` (`LottieAnimationView` / Compose `LottieAnimation`): `setMinAndMaxFrame`, `progress`.
- React Native — `lottie-react-native` (`<LottieView source={...} progress={anim} />`, drive `progress` with `Animated`).
The same `.lottie`/`.json` plays across all; segments and progress concepts match the web API.
## Optimization
- Ship `.lottie` (zipped) over raw `.json`; lazy-load offscreen players and pause when not visible (`IntersectionObserver` → `play`/`pause`).
- Prefer the canvas/WASM dotLottie renderer for many simultaneous animations; SVG renderer (lottie-web) is fine for one crisp icon but costs more DOM for complex files.
- Keep AE comps small: fewer layers/keyframes, no large embedded rasters; flatten precomps where possible. File size tracks keyframe and path complexity, not duration.
- Recolor at runtime (themes) instead of exporting a file per brand/theme.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained Lottie demo (looping illustration, animated icon, empty state) the deliverable is **one HTML file that opens directly in a browser** — the dotLottie/lottie-web runtime from CDN, a `<canvas>`, and your `.lottie`/`.json` (a relative file or a data URL). No build step. One file is the right tier for shipping a player; don't reach for a bundler.
**Output contract:**
- One `.html` file: the runtime via CDN (`@lottiefiles/dotlottie-web`), the canvas, and `autoplay:false` so the frame is yours to drive.
- Include the seek harness so any frame can be frozen for a screenshot.
**Seek harness — freeze an exact frame.** `?t=N` jumps to a frame and holds it so a screenshot lands on a still, deterministic frame. Lottie's playhead is in frames, so stop on the frame directly:
```html
<script>
const dl = new DotLottie({ canvas, src: "/icon.lottie", autoplay: false });
dl.addEventListener("load", () => {
const t = new URLSearchParams(location.search).get("t");
if (t !== null) dl.setFrame(parseFloat(t)); // freeze on frame N (lottie-web: anim.goToAndStop(N, true))
else dl.play();
console.log("totalFrames", dl.totalFrames); // read for end-frame
window.__ready = true;
});
</script>
```
**Verify loop — render → freeze → screenshot → check:** open the file at first / mid / last frame (`?t=0`, `?t=<total/2>`, `?t=<total-1>`; read `totalFrames` from the console), screenshot each, and check **fidelity** (colors/theme correct, segment loops where intended) plus **artifacts** (canvas blurry from missing `autoResize`/DPR, clipped composition, FOUC before the file loads, jank). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=600 "file://$PWD/lottie.html?t=42" frame-mid.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN runtime and the `.lottie`/`.json` load.
2. `?t=N` (`setFrame`/`goToAndStop`) freezes the correct, deterministic frame.
3. Screenshotted at first / mid / last frame — matches the brief, sharp, no clipping.
4. `prefers-reduced-motion` honored — don't `autoplay` a loop; show a static frame or offer a play control.
5. Easing is intentional — playback speed/segment chosen on purpose, motion baked in AE reads as designed.
## Quick reference
| Goal | Call |
|------|------|
| Play a range | `setSegment(start, end)` |
| Jump to frame | `setFrame(n)` |
| Reverse / bounce | `setMode("reverse"|"bounce")` |
| Scroll-drive | `autoplay:false` + `setFrame(p*totalFrames)` |
| Theme swap | `setTheme("dark")` |
| Know length | `totalFrames` after `load` event |
| Declarative interactivity | `@lottiefiles/lottie-interactivity` |
## Reference files
- `references/integration-and-export.md` — full dotLottie-web + React setup and event/segment control, `lottie-interactivity` mode configs, scroll/cursor patterns, runtime theming details, and the complete After Effects → Bodymovin export checklist with the list of unsupported AE features and how to work around them.
@@ -1,233 +0,0 @@
# Lottie Integration & Export (detailed)
## 1. dotLottie-web full setup
```bash
npm i @lottiefiles/dotlottie-web
```
```js
import { DotLottie } from "@lottiefiles/dotlottie-web";
const dotLottie = new DotLottie({
canvas: document.querySelector("#lottie"),
src: "/assets/onboarding.lottie", // .lottie or .json (URL or same-origin path)
autoplay: true,
loop: true,
speed: 1,
mode: "forward", // forward | reverse | bounce | reverse-bounce
useFrameInterpolation: true, // smoother than the source frame rate
renderConfig: {
autoResize: true, // keep the canvas crisp on resize/DPR changes
devicePixelRatio: window.devicePixelRatio,
},
});
```
The canvas MUST be a real `<canvas>` element. For responsiveness, size the canvas via CSS and keep `autoResize: true`; the runtime handles the backing store.
### Lifecycle and events
```js
dotLottie.addEventListener("load", () => console.log(dotLottie.totalFrames, dotLottie.duration));
dotLottie.addEventListener("loadError", (e) => console.error("bad src", e));
dotLottie.addEventListener("play", () => {});
dotLottie.addEventListener("pause", () => {});
dotLottie.addEventListener("complete", () => {}); // fires when a non-looping play finishes
dotLottie.addEventListener("loop", ({ loopCount }) => {});
dotLottie.addEventListener("frame", ({ currentFrame }) => {});
// always clean up (SPA/unmount)
dotLottie.destroy();
```
`totalFrames`, `duration`, and segment data are only valid AFTER the `load` event — read them there, not synchronously after construction.
### Multi-animation .lottie files
A single `.lottie` can hold several animations:
```js
dotLottie.addEventListener("load", () => {
console.log(dotLottie.manifest.animations); // list of animation ids
});
dotLottie.loadAnimation("success"); // switch by id without re-fetching
```
## 2. React wrapper
```bash
npm i @lottiefiles/dotlottie-react
```
```jsx
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
import { useState, useEffect } from "react";
function PlayButton() {
const [dl, setDl] = useState(null);
const [playing, setPlaying] = useState(true);
useEffect(() => {
if (!dl) return;
const onComplete = () => setPlaying(false);
dl.addEventListener("complete", onComplete);
return () => dl.removeEventListener("complete", onComplete);
}, [dl]);
return (
<DotLottieReact
src="/play.lottie"
autoplay
loop={false}
dotLottieRefCallback={setDl} // capture instance for imperative control
onClick={() => (playing ? dl.pause() : dl.play(), setPlaying((p) => !p))}
style={{ width: 200, height: 200 }}
/>
);
}
```
Props mirror the constructor: `src, autoplay, loop, speed, mode, useFrameInterpolation, renderConfig, themeId, segment`.
## 3. Segments and state machines
```js
// Loop only the "loading" portion (frames 30–90), then jump to a success segment.
dotLottie.setSegment(30, 90);
dotLottie.setLoop(true);
dotLottie.play();
function resolveSuccess() {
dotLottie.setLoop(false);
dotLottie.setSegment(91, 140); // success burst
dotLottie.play();
}
```
Pattern for icon toggles (e.g. like button): keep distinct frame ranges for each state in one file, and `setSegment` + `play` per interaction; listen for `complete` to settle into an idle range.
dotLottie also supports embedded **state machines** (`.lottie` with a `state-machine` definition): `dotLottie.stateMachineLoad("sm_id"); dotLottie.stateMachineStart();` then fire inputs/events — useful for complex interactive icons authored in LottieFiles without writing JS state logic.
## 4. lottie-interactivity (declarative)
```bash
npm i @lottiefiles/lottie-interactivity
```
Works with a `lottie-web`/dotLottie player instance (commonly the `<dotlottie-player>` / `<lottie-player>` web component):
```html
<dotlottie-player id="firstLottie" src="/scroll.lottie" style="width:300px"></dotlottie-player>
<script>
LottieInteractivity.create({
player: "#firstLottie",
mode: "scroll",
actions: [
{ visibility: [0, 0.3], type: "stop", frames: [0] },
{ visibility: [0.3, 1.0], type: "seek", frames: [0, 120] }, // map scroll → frames 0..120
],
});
</script>
```
Modes:
- `scroll` — tie frames to scroll position / element visibility (the canonical scrolly use).
- `cursor` — drive frames from cursor position over the element (hover scrub).
- `hover` — play on hover, control `loop`/`reset` on leave.
- `click` — advance to the next sync state on each click.
- `chain` — sequence multiple animations.
Use `type: "seek"` to scrub frames, `type: "loop"` / `"play"` / `"stop"` for segment behaviors.
## 5. Manual scroll mapping (full control, no extra lib)
```js
const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v));
let total = 0;
dotLottie.addEventListener("load", () => { total = dotLottie.totalFrames - 1; });
const section = document.querySelector(".scrolly");
function update() {
const r = section.getBoundingClientRect();
const scrollable = r.height - window.innerHeight;
const p = clamp(-r.top / scrollable, 0, 1);
dotLottie.setFrame(p * total);
}
window.addEventListener("scroll", update, { passive: true });
window.addEventListener("resize", update);
```
Pause when offscreen to save CPU:
```js
new IntersectionObserver(([e]) => e.isIntersecting ? dotLottie.unfreeze() : dotLottie.freeze())
.observe(canvas);
```
## 6. Runtime theming
### Embedded themes (recommended)
A `.lottie` authored with named color themes:
```js
dotLottie.addEventListener("load", () => {
console.log(dotLottie.manifest.themes); // available theme ids
dotLottie.setTheme("dark"); // swap colors with no re-fetch / re-export
});
// or per slot:
dotLottie.setThemeData({ /* theme JSON */ });
```
### Manual color patching (last resort)
```js
const json = await fetch("/icon.json").then((r) => r.json());
// Lottie colors are normalized 0..1 [r,g,b,a] arrays at shapes[].it[].c.k
function recolor(layers, hex) {
const [r, g, b] = hexToRgb01(hex);
for (const layer of layers) {
for (const sh of layer.shapes ?? []) {
for (const it of sh.it ?? []) {
if (it.ty === "fl" || it.ty === "st") { it.c.k = [r, g, b, 1]; } // fill / stroke
}
}
if (layer.layers) recolor(layer.layers, hex); // precomps
}
}
recolor(json.layers, "#ff5500");
new DotLottie({ canvas, data: JSON.stringify(json), autoplay: true });
```
This depends on the exact layer/shape structure and breaks if the file changes — prefer embedded themes, or use the `lottie-web` SVG renderer and target paths with CSS where the markup is stable.
## 7. After Effects → Bodymovin export checklist
Plugin: **Bodymovin** (or LottieFiles plugin). `Window → Extensions → Bodymovin`. Select the comp, set destination, configure, Render.
Pre-export checklist:
1. Comp set to a sensible size and frame rate (24/30/60); avoid huge resolutions — Lottie is vector, the canvas scales.
2. Name layers/comps clearly — names survive into JSON and aid runtime theming/targeting.
3. Convert text you want crisp/animated-by-path to shapes if it uses unsupported text features; otherwise enable "Glyphs"/"Fonts" in Bodymovin settings for live text.
4. Trim the work area to exactly the frames you ship; trailing frames bloat the file.
5. In Bodymovin settings: enable **Compress assets / .lottie** output for the zipped format; enable "Glyphs" if using text; toggle "Standalone"/"Demo" only as needed.
6. Replace embedded raster images with vectors where possible; if rasters are required, they inflate `.json` (consider `.lottie` which bundles them).
7. Test the exported file in the LottieFiles preview AND your target runtime before handoff — renderers differ.
### Unsupported / partially-supported AE features (avoid or rework)
- **Expressions** — not evaluated by runtimes. Bake expression-driven motion to keyframes (Bodymovin can pre-render some) or remove. Heavy-expression rigs are the #1 source of "looks wrong in product".
- **Effects** — most AE effects (blurs, glows, distort, particle systems, CC effects) are NOT supported. Only a small set (e.g. some Gaussian blur, drop shadow, tint, fill via supported attributes) survive, and inconsistently across platforms. Recreate looks with shape layers, gradients, and mattes.
- **3D layers / camera** — not supported; fake depth with 2D scaling/position.
- **Time remapping / nested time stretch** — flaky; pre-compose and bake.
- **Auto-Orient, certain merge-paths modes, some matte combinations** — test explicitly.
- **Audio** — not part of Lottie.
- **Adjustment layers, layer styles (bevel/emboss/inner shadow)** — largely unsupported; convert to shapes/gradients.
- **Track mattes** — alpha/luma mattes generally work but increase cost; flatten when possible.
- **Gradients on strokes / complex gradient feathering** — limited; verify.
Workarounds summary: bake expressions to keyframes, replace effects with native shape/gradient/matte equivalents, flatten precomps, drop rasters, and verify on every target runtime (web/iOS/Android render slightly differently). Keep layer/keyframe count low for performance and file size.
---
Export clean from After Effects and the dotLottie plays light everywhere. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=lottie-animation)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
-173
View File
@@ -1,173 +0,0 @@
---
name: micro-interaction
description: This skill should be used when the user asks to "add a hover/press effect", "animate a toggle or switch", "build an animated like button", "make a toast/snackbar slide in", "animate a drawer or modal", "animate list reordering or add/remove", "do a shared-element layout transition", or "polish UI feedback". Covers UI motion with Framer Motion (motion/react) and modern CSS.
version: 0.1.0
---
# Micro-interactions (UI Motion)
Small, functional motion that makes an interface feel responsive and alive: hover/press/focus feedback, toggles, toasts, drawers, and list/layout animation. The goal is feedback and continuity, not decoration.
## When to use
- Hover/press/focus feedback; toggles, checkboxes, like/heart buttons
- Toasts/snackbars, drawers, modals, tooltips, accordions (enter/exit)
- List add/remove/reorder; shared-element ("magic move") layout transitions
- Loading → success → error state transitions
## Principles (apply to all of it)
- Duration: UI micro-interactions live in **100–250ms**. Anything over ~400ms feels laggy for a click response.
- Animate `transform` and `opacity` only — they are GPU-composited (no layout/paint). Avoid animating `width/height/top/left`; use `scale` or layout animation instead.
- Give **instant** press feedback: `scale: 0.96` on tap with a fast spring.
- Asymmetric timing: enter slightly slower (ease-out), exit faster (ease-in). Things should arrive gracefully and leave promptly.
- Respect `prefers-reduced-motion`: gate non-essential motion; keep opacity changes, drop large movement.
- Easing defaults: ease-out for entrances `cubic-bezier(0.16, 1, 0.3, 1)`; a tasteful overshoot is `cubic-bezier(0.34, 1.56, 0.64, 1)`; standard move `cubic-bezier(0.4, 0, 0.2, 1)`.
## Framer Motion (motion/react) essentials
As of v11+, the package is imported as `motion/react` (the `framer-motion` name still works).
### Gestures and springs
```jsx
import { motion } from "motion/react";
<motion.button
whileHover={{ scale: 1.03 }}
whileTap={{ scale: 0.96 }}
whileFocus={{ boxShadow: "0 0 0 3px rgba(59,130,246,.5)" }}
transition={{ type: "spring", stiffness: 400, damping: 30 }}
/>
```
Spring intuition: higher `stiffness` = faster; higher `damping` = less bounce. `stiffness: 400, damping: 30` is a snappy UI default. For visible bounce, lower damping (e.g. `damping: 12`).
### Enter / exit with AnimatePresence
Exit animations require `AnimatePresence` wrapping conditionally-rendered children, each with a stable `key`.
```jsx
import { AnimatePresence, motion } from "motion/react";
<AnimatePresence>
{open && (
<motion.div
key="panel"
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: 8 }}
transition={{ duration: 0.2, ease: [0.16, 1, 0.3, 1] }}
/>
)}
</AnimatePresence>
```
For toasts/lists, use `mode="popLayout"` so removed items don't hold space while exiting.
### Layout animation (the superpower)
`layout` automatically animates any layout change (position/size) using transforms — perfect for reordering, expanding cards, and grid<->list.
```jsx
<motion.li layout transition={{ type: "spring", stiffness: 500, damping: 40 }} />
```
Shared-element transition across components: give two elements the same `layoutId` and Framer Motion animates between them as one mounts and the other unmounts.
```jsx
{!open && <motion.div layoutId="card" onClick={() => setOpen(true)} />}
<AnimatePresence>
{open && <motion.div layoutId="card" />} {/* "magic moves" from the source */}
</AnimatePresence>
```
Gotcha: a plain `layout` element distorts `border-radius` and text during scale. Add `layout` to direct children that should counter-scale, and prefer `borderRadius`/`boxShadow` as motion values, or use `layout="position"` to animate position only.
## Pure CSS path (no JS, including discrete properties)
Modern CSS can animate enter/exit and even `display` toggles without a library.
```css
.toast {
transition: opacity 0.2s ease, transform 0.2s ease;
/* allow animating to/from display:none and from initial render */
transition-behavior: allow-discrete;
}
.toast[hidden] { display: none; }
/* animate FROM these values on first render / when entering */
@starting-style {
.toast { opacity: 0; transform: translateY(8px); }
}
```
`@starting-style` defines the "before-open" values so an element animates in on first appearance; `transition-behavior: allow-discrete` lets `display` (and `overlay` for popovers/dialogs) participate so exit animations run before the element is removed. Baseline in Chrome/Edge/Safari; provide a no-animation fallback for older browsers.
Always include a reduced-motion guard:
```css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
transition-duration: 0.01ms !important;
}
}
```
## State, not just decoration
Loading → success → error should be one continuous motion (e.g. a button morphs spinner → checkmark), not a jump cut. Keep the element mounted and animate between states so the eye tracks the same object.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained interaction demo (toggle, like button, toast, drawer) the deliverable is **one HTML file that opens directly in a browser**. Pure-CSS interactions ship as-is; for a Framer Motion demo, load React + `motion` from CDN (`esm.sh`) into one inline module — no build step. One file is the right tier; don't reach for a bundler.
**Output contract:**
- One `.html` file: your markup plus either CSS transitions/`@starting-style` or an inline `<script type="module">` importing `motion` from CDN.
- A way to land on the **resolved end state** for a screenshot — interactions are state-driven, not time-driven, so freeze the state rather than a clock.
**Seek harness — pin a deterministic state.** A micro-interaction's "frames" are its states (idle / hover / pressed / open). `?state=open` applies the target state on load so a screenshot captures it settled:
```html
<script>
const s = new URLSearchParams(location.search).get("state");
if (s) document.documentElement.dataset.state = s; // CSS keys off [data-state="open"]
// Framer Motion: set the controlled prop from `s` (e.g. const [open]=useState(s==="open"))
// For a CSS @keyframes loop instead, freeze it: el.style.animationDelay=(-N)+"s"; el.style.animationPlayState="paused";
window.__ready = true;
</script>
```
**Verify loop — render → set state → screenshot → check:** open each meaningful state (`?state=idle`, `?state=hover`, `?state=open`), screenshot, and check **fidelity** (press feedback reads instant, exit runs before unmount) plus **artifacts** (`layout` distorting `border-radius`/text, toast holding space after exit, FOUC, jank). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=400 "file://$PWD/demo.html?state=open" open.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN React/`motion` (if used) resolves.
2. The `?state=` (or controlled-prop) freeze lands a deterministic, settled state.
3. Screenshotted across states — idle / active / open — matches the brief, no artifacts.
4. `prefers-reduced-motion` honored — large movement dropped, opacity/feedback kept.
5. Easing is intentional — enter ease-out, exit ease-in, durations in the 100–250ms band.
## Quick reference
| Need | Approach |
|------|----------|
| Press feedback | `whileTap={{ scale: 0.96 }}` spring 400/30 |
| Enter/exit | `AnimatePresence` + `initial/animate/exit` |
| Reorder / resize | `layout` prop (spring) |
| Magic move | shared `layoutId` |
| Toast stack | `AnimatePresence mode="popLayout"` |
| No-JS enter | `@starting-style` + transition |
| Animate to display:none | `transition-behavior: allow-discrete` |
| Accessibility | `prefers-reduced-motion` guard always |
## Reference files
- `references/framer-motion-recipes.md` — variants + stagger, `AnimatePresence` modes, `layout`/`layoutId` magic move, `Reorder` drag-to-sort, drag constraints, gesture composition, and `useReducedMotion`.
- `references/css-recipes.md` — `@starting-style`, `transition-behavior: allow-discrete`, popover/dialog exit animation, keyframe spinners/toggles, `@property` for animatable custom properties, and `prefers-reduced-motion` patterns.
@@ -1,142 +0,0 @@
# CSS Micro-interaction Recipes
Modern CSS handles most UI motion with zero JavaScript, including enter/exit and `display` toggles. Baseline-available in current Chrome/Edge/Safari/Firefox (verify `@starting-style` and `allow-discrete` for your support floor; degrade to instant show/hide otherwise).
## Enter animation on first render: @starting-style
`@starting-style` supplies the values an element transitions FROM the first time it renders (or becomes shown). Without it, there is no "previous" state to transition from, so newly-inserted elements snap in.
```css
.menu {
opacity: 1;
transform: translateY(0);
transition: opacity 0.2s ease, transform 0.2s ease;
}
@starting-style {
.menu { opacity: 0; transform: translateY(-8px); }
}
```
## Animating to/from display:none: transition-behavior: allow-discrete
`display` and `content-visibility` are discrete properties — normally they flip instantly, killing exit animations. `allow-discrete` lets them flip at the correct moment (kept visible during exit, swapped at the end).
```css
.drawer {
transition:
transform 0.25s ease,
opacity 0.25s ease,
display 0.25s allow-discrete; /* keep displayed through the exit */
}
.drawer[hidden] { /* closed state */
opacity: 0;
transform: translateX(100%);
display: none;
}
@starting-style {
.drawer:not([hidden]) { opacity: 0; transform: translateX(100%); }
}
```
Shorthand alternative: `transition-behavior: allow-discrete;` applies to all discrete properties in the `transition` list.
## Popover / dialog exit animation (top-layer)
Native `popover` and `<dialog>` live in the top layer via the `overlay` property, which is also discrete — animate it too:
```css
[popover] {
opacity: 0;
transform: scale(0.95);
transition: opacity 0.2s, transform 0.2s, overlay 0.2s allow-discrete, display 0.2s allow-discrete;
}
[popover]:popover-open { opacity: 1; transform: scale(1); }
@starting-style {
[popover]:popover-open { opacity: 0; transform: scale(0.95); }
}
```
This gives a fully CSS-driven open AND close animation for `<button popovertarget>` popovers with no JS.
## Press / hover / focus feedback
```css
.btn {
transition: transform 0.12s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.2s ease;
}
.btn:hover { transform: translateY(-1px); box-shadow: 0 4px 12px rgba(0,0,0,.15); }
.btn:active { transform: translateY(0) scale(0.97); transition-duration: 0.06s; } /* snappy press */
.btn:focus-visible { outline: 2px solid #3b82f6; outline-offset: 2px; }
```
Use `:focus-visible` (not `:focus`) so keyboard users get a ring but mouse clicks don't.
## Animated toggle / switch
```css
.switch { width: 44px; height: 24px; border-radius: 999px; background: #cbd5e1;
transition: background 0.2s ease; }
.switch[aria-checked="true"] { background: #22c55e; }
.switch::after {
content: ""; width: 20px; height: 20px; border-radius: 50%; background: #fff;
transform: translateX(2px);
transition: transform 0.22s cubic-bezier(0.34, 1.56, 0.64, 1);
}
.switch[aria-checked="true"]::after { transform: translateX(22px); }
```
The `cubic-bezier(0.34, 1.56, 0.64, 1)` overshoot gives the knob a satisfying snap.
## Loading spinner and pulse
```css
@keyframes spin { to { transform: rotate(360deg); } }
.spinner { animation: spin 0.8s linear infinite; }
@keyframes pulse { 0%,100% { opacity: 1; } 50% { opacity: 0.5; } }
.skeleton { animation: pulse 1.5s ease-in-out infinite; }
```
## Animatable custom properties with @property
Plain CSS variables animate discretely. Register them with `@property` to give them a type so they interpolate smoothly — enables gradient angle, number counters, and themed motion.
```css
@property --angle { syntax: "<angle>"; inherits: false; initial-value: 0deg; }
.gradient-border {
background: conic-gradient(from var(--angle), #6366f1, #ec4899, #6366f1);
transition: --angle 0.4s ease;
}
.gradient-border:hover { --angle: 360deg; }
```
## Accordion height (modern: interpolate-size)
Animating `height: auto` historically required JS measurement. With `interpolate-size: allow-keywords`, transitions to/from intrinsic sizes work:
```css
:root { interpolate-size: allow-keywords; }
.accordion__panel {
height: 0; overflow: hidden;
transition: height 0.3s ease;
}
.accordion__panel[data-open] { height: auto; }
```
Fallback for unsupported browsers: animate `grid-template-rows: 0fr -> 1fr` on a wrapper.
## Reduced motion (always include)
```css
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
```
Then selectively re-enable essential, low-motion feedback (e.g. opacity-only fades) inside the same query if needed. The principle: never remove feedback entirely, just remove large/spatial motion.
@@ -1,187 +0,0 @@
# Framer Motion Recipes
Import from `motion/react` (v11+). All examples are React + Framer Motion.
```jsx
import { motion, AnimatePresence, Reorder, useReducedMotion, useDragControls } from "motion/react";
```
## Variants and staggered children
Variants are named animation states a parent can propagate to children, enabling orchestration like staggering without per-child timing math.
```jsx
const list = {
hidden: { opacity: 0 },
show: {
opacity: 1,
transition: { staggerChildren: 0.06, delayChildren: 0.1 },
},
};
const item = {
hidden: { opacity: 0, y: 12 },
show: { opacity: 1, y: 0, transition: { type: "spring", stiffness: 500, damping: 30 } },
};
<motion.ul variants={list} initial="hidden" animate="show">
{items.map((t) => (
<motion.li key={t.id} variants={item}>{t.label}</motion.li>
))}
</motion.ul>
```
`staggerDirection: -1` staggers from last to first. `when: "beforeChildren"` / `"afterChildren"` sequences parent vs children.
## AnimatePresence modes
```jsx
<AnimatePresence mode="wait"> {/* outgoing finishes before incoming starts (route/tab switches) */}
<motion.div key={tab} initial={{opacity:0}} animate={{opacity:1}} exit={{opacity:0}} />
</AnimatePresence>
```
Modes:
- default (`"sync"`) — incoming and outgoing animate simultaneously.
- `"wait"` — finish exit before enter (single-element swaps like tabs/pages).
- `"popLayout"` — exiting items are popped from layout flow so siblings re-flow immediately (toast stacks, removing list items). Children must be capable of `layout`.
Require a unique, stable `key` on each child. To run exit on initial mount too, that is not needed; to suppress enter animation on first render set `<AnimatePresence initial={false}>`.
## Toast stack (popLayout + layout)
```jsx
function Toasts({ toasts }) {
return (
<div className="toast-region">
<AnimatePresence mode="popLayout">
{toasts.map((t) => (
<motion.div
key={t.id}
layout
initial={{ opacity: 0, y: 24, scale: 0.9 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, scale: 0.9, transition: { duration: 0.15 } }}
transition={{ type: "spring", stiffness: 500, damping: 40 }}
>
{t.message}
</motion.div>
))}
</AnimatePresence>
</div>
);
}
```
`layout` makes remaining toasts slide up smoothly when one is dismissed.
## Magic-move / shared-element layout
```jsx
function Gallery() {
const [active, setActive] = useState(null);
return (
<>
<div className="grid">
{photos.map((p) => (
<motion.img key={p.id} layoutId={`photo-${p.id}`} src={p.thumb}
onClick={() => setActive(p)} />
))}
</div>
<AnimatePresence>
{active && (
<motion.div className="backdrop" onClick={() => setActive(null)}
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }}>
<motion.img layoutId={`photo-${active.id}`} src={active.full} />
</motion.div>
)}
</AnimatePresence>
</>
);
}
```
Matching `layoutId` makes the thumbnail visually fly to the lightbox and back.
## Drag-to-reorder list
`Reorder` handles pointer drag, axis locking, and live reordering with layout animation built in.
```jsx
function SortableList({ items, setItems }) {
return (
<Reorder.Group axis="y" values={items} onReorder={setItems}>
{items.map((item) => (
<Reorder.Item key={item} value={item}
whileDrag={{ scale: 1.03, boxShadow: "0 8px 24px rgba(0,0,0,.18)" }}>
{item}
</Reorder.Item>
))}
</Reorder.Group>
);
}
```
For a dedicated drag handle, use `useDragControls`:
```jsx
const controls = useDragControls();
<Reorder.Item value={item} dragListener={false} dragControls={controls}>
<span className="handle" onPointerDown={(e) => controls.start(e)}>⠿</span>
{item.label}
</Reorder.Item>
```
## Drag with constraints and elastic
```jsx
const ref = useRef(null);
<div ref={ref} className="bounds">
<motion.div drag dragConstraints={ref} dragElastic={0.2}
dragTransition={{ bounceStiffness: 600, bounceDamping: 20 }} />
</div>
```
`dragElastic` (0–1) controls how far past constraints it can be pulled; `dragSnapToOrigin` returns it on release.
## Gesture composition (like button)
```jsx
function Like() {
const [liked, setLiked] = useState(false);
return (
<motion.button onClick={() => setLiked((v) => !v)} whileTap={{ scale: 0.85 }}>
<motion.span
animate={liked ? { scale: [1, 1.4, 1], color: "#ef4444" } : { scale: 1, color: "#9ca3af" }}
transition={{ duration: 0.35, ease: "easeOut" }}
>♥</motion.span>
</motion.button>
);
}
```
Arrays of values (`scale: [1, 1.4, 1]`) are keyframes; control their spacing with `times: [0, 0.6, 1]`.
## Respecting reduced motion
```jsx
function Panel() {
const reduce = useReducedMotion();
return (
<motion.div
initial={reduce ? false : { opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
/>
);
}
```
Wrap an app in `<MotionConfig reducedMotion="user">` to globally strip transform/layout animations for users who prefer reduced motion while keeping opacity.
## Performance notes
- Prefer `transform`/`opacity`; Framer Motion already uses transforms for `x/y/scale/rotate`.
- For frequently-updated values (cursor follow, scroll), use `useMotionValue` + `useSpring` instead of React state to avoid re-renders.
- `layout` is powerful but measure-heavy; avoid putting it on hundreds of simultaneously-animating nodes.
---
Tune the timing and easing and a micro-interaction feels effortless. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=micro-interaction)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
@@ -1,218 +0,0 @@
---
name: page-transition-animation
description: This skill should be used when the user asks to "animate page or route transitions", "add a page transition or crossfade between views", "animate route changes in Next.js App Router", "use the View Transitions API", "AnimatePresence exit doesn't fire on navigation", or "Framer Motion exit animation not working / exit animation before unmount in Next.js". Covers enter/exit page-transition animation with the View Transitions API and Framer Motion, for Next.js App Router and general SPA routing.
version: 0.1.0
---
# Page Transition Animation (Next.js App Router)
Implement page enter/exit transitions in the Next.js **App Router**, and fix the single most common failure: **Framer Motion `AnimatePresence` exit animations never fire on navigation**. The reason is structural — in the App Router, when navigating, Next.js unmounts the old route's content and mounts the new one almost immediately. `AnimatePresence` can only animate an exit if the *exiting element stays mounted* under a *persistent* `AnimatePresence` wrapper long enough to run the animation. Because the router swaps children out from under it, the exit is skipped. Two approaches solve this: a pathname-keyed `AnimatePresence` with the **FrozenRouter** pattern, or the **View Transitions API** (native / `next-view-transitions`).
## When to use
Use when adding animated page transitions in a Next.js App Router app, when a Framer Motion `exit` prop does nothing on route change, when an old page disappears instantly instead of animating out, when choosing between Framer Motion and the View Transitions API for Next.js, or when debugging why `AnimatePresence` won't animate between routes.
## Why exit doesn't fire (the core problem)
`AnimatePresence` detects removal of a *direct keyed child*. On App Router navigation:
1. The wrapper must persist across the navigation. If `AnimatePresence` lives in a component that itself unmounts, there is nothing left to run the exit.
2. The child's `key` must change per route so AnimatePresence sees "old removed, new added".
3. During the brief overlap, the *outgoing* subtree must still render its old content — but the App Router has already swapped the route context, so the outgoing tree would otherwise render the *new* page's data. This is what **FrozenRouter** fixes.
## Solution A: template.tsx + keyed AnimatePresence + FrozenRouter
`template.tsx` is the App Router's purpose-built hook for this: unlike `layout.tsx` (which persists), a **template remounts on every navigation**, giving each route a fresh instance — ideal for per-route enter animations. Combine it with a pathname-keyed `AnimatePresence` and FrozenRouter for clean exit + enter.
```tsx
// app/template.tsx
'use client';
import { AnimatePresence } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { FrozenRouter } from './frozen-router';
import { PageTransition } from './page-transition';
export default function Template({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
return (
<AnimatePresence mode="wait" initial={false}>
{/* key on pathname so AnimatePresence sees old removed / new added */}
<PageTransition key={pathname}>
{/* FrozenRouter keeps the OUTGOING tree rendering its old content
while it animates out */}
<FrozenRouter>{children}</FrozenRouter>
</PageTransition>
</AnimatePresence>
);
}
```
```tsx
// app/page-transition.tsx
'use client';
import { motion } from 'framer-motion';
export function PageTransition({ children }: { children: React.ReactNode }) {
return (
<motion.div
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -12 }}
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
>
{children}
</motion.div>
);
}
```
```tsx
// app/frozen-router.tsx
'use client';
import { useContext, useRef } from 'react';
import {
LayoutRouterContext,
} from 'next/dist/shared/lib/app-router-context.shared-runtime';
// Freezes the router context so the exiting page keeps rendering its
// OWN content during the exit animation instead of the next route's.
export function FrozenRouter({ children }: { children: React.ReactNode }) {
const context = useContext(LayoutRouterContext ?? {});
const frozen = useRef(context).current;
return (
<LayoutRouterContext.Provider value={frozen}>
{children}
</LayoutRouterContext.Provider>
);
}
```
How it fits together:
- `mode="wait"` makes AnimatePresence fully finish the exit before mounting the new page. (Use the default mode if enter/exit should overlap/crossfade.)
- `initial={false}` skips the enter animation on first load (optional).
- `key={pathname}` is what makes AnimatePresence treat each route as a distinct presence.
- `FrozenRouter` snapshots `LayoutRouterContext` so the outgoing subtree renders the *previous* route's content throughout the exit, instead of flashing the new route's content. Without it, exit either skips or shows the wrong content.
Note: `LayoutRouterContext` is a Next.js internal; its import path can change between Next versions. If the import breaks after an upgrade, that path is the thing to update.
## Solution B: native View Transitions API
The View Transitions API animates between two DOM states with the browser capturing before/after snapshots — no per-element exit components.
```css
/* globals.css */
@view-transition { navigation: auto; } /* opt MPA-style in (where supported) */
::view-transition-old(root) { animation: fade 0.25s both reverse; }
::view-transition-new(root) { animation: fade 0.25s both; }
@keyframes fade { from { opacity: 0; } to { opacity: 1; } }
```
For SPA-style App Router navigations, wrap the router update:
```ts
if (document.startViewTransition) {
document.startViewTransition(() => router.push(href));
} else {
router.push(href);
}
```
### next-view-transitions library
`next-view-transitions` integrates the View Transitions API with the App Router's client navigation so it works out of the box:
```tsx
// app/layout.tsx
import { ViewTransitions } from 'next-view-transitions';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<ViewTransitions>
<html lang="en"><body>{children}</body></html>
</ViewTransitions>
);
}
```
```tsx
// use the library's Link instead of next/link
import { Link } from 'next-view-transitions';
<Link href="/about">About</Link>;
```
Choose View Transitions for simple cross-page fades/morphs and shared-element transitions with minimal JS; choose Framer Motion when fine-grained, orchestrated, interruptible, or staggered exit animations are needed. View Transitions API browser support is still uneven, so provide a graceful fallback (the `if (document.startViewTransition)` guard).
## AnimatePresence debug checklist
When exit still won't fire, verify in order:
1. **Wrapper stays mounted.** `AnimatePresence` must live in something persistent — ideally `template.tsx`, or a layout-level client component — not inside the page that's unmounting.
2. **Stable, changing key.** The animated child needs `key={pathname}` (or similar) so removal is detected. No key, or a key that doesn't change → no exit.
3. **Direct motion descendant.** The element with the `exit` prop must be a `motion.*` component and a child of `AnimatePresence` (a non-motion wrapper in between can block detection).
4. **`mode="wait"`** if old and new should not overlap; without it both render simultaneously and may jump.
5. **FrozenRouter present** if the outgoing page flashes the new route's content during exit.
6. **`'use client'`** on every file using AnimatePresence/usePathname/motion.
7. **Single child at a time** under `mode="wait"` — AnimatePresence expects one keyed presence to swap.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
The real target is a Next.js app, but to *prove the transition shape* (the enter/exit curve, direction, crossfade) you can ship **one HTML file that opens directly in a browser** — two stub "pages" you toggle, animated with `motion` from CDN or the native View Transitions API. One file is the right tier for validating motion before wiring the router; don't stand up Next just to eyeball a fade.
**Output contract:**
- One `.html` file: two view stubs and a toggle, animated with either an inline `<script type="module">` importing `motion`/React from CDN, or `document.startViewTransition` + `::view-transition-*` CSS.
- A way to freeze the **resolved end state** — a route transition is state-driven (which view, mid-swap), so screenshot the state, not a clock.
**Seek harness — pin a transition phase.** `?view=b` mounts the destination view (or `?phase=exit` to hold the outgoing tree mid-animation) so a screenshot lands on a settled phase:
```html
<script>
const p = new URLSearchParams(location.search);
document.documentElement.dataset.view = p.get("view") || "a"; // CSS/React keys off this
// Framer Motion: set the controlled key/route from ?view; for mode="wait" the resolved end is the new page
// View Transitions: screenshot the END state (snapshots are transient); or pause via emulate slow animations
window.__ready = true;
</script>
```
**Verify loop — render → set phase → screenshot → check:** open source, mid, and destination (`?view=a`, `?phase=exit`, `?view=b`), screenshot each, and check **fidelity** (exit actually runs, direction/crossfade matches the brief, no `mode="wait"` lag) plus **artifacts** (outgoing tree flashing the new page's content, double-mount, FOUC, jank). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/transition.html?view=b" dest.png
```
**Before you finish:**
1. Opens standalone — no console errors, CDN `motion`/React (if used) resolves, `startViewTransition` guarded.
2. The `?view=`/`?phase=` freeze lands a deterministic transition phase.
3. Screenshotted at source / mid / destination — matches the brief, no content flash or skipped exit.
4. `prefers-reduced-motion` honored — slide/translate dropped to a short crossfade.
5. Easing is intentional — entrances ease-out, exits ease-in, durations ~0.2–0.4s (not laggy under `mode="wait"`).
## Quick reference
| Need | Approach |
|---|---|
| Per-route enter animation | `app/template.tsx` (remounts each nav) |
| Exit animation on nav | keyed `AnimatePresence mode="wait"` + FrozenRouter |
| Outgoing page shows old content | FrozenRouter (snapshot `LayoutRouterContext`) |
| Detect route change | `usePathname()` as the `key` |
| Simple cross-page fade/morph | View Transitions API / next-view-transitions |
| Shared element transition | `view-transition-name` CSS |
| Skip first-load animation | `initial={false}` |
## Gotchas
- `layout.tsx` persists and will NOT remount per route — use `template.tsx` for per-route enter animations.
- Omitting FrozenRouter makes the exiting page render the *new* route's content mid-animation (visible flash) or skip exit entirely.
- `LayoutRouterContext` import path is a Next internal; it may change across versions — first thing to fix after an upgrade.
- Without `key={pathname}`, AnimatePresence sees the same child and never triggers exit.
- `mode="wait"` waits for exit before enter; overusing it on slow exits makes navigation feel laggy — tune durations (~0.2-0.4s).
- View Transitions API lacks full browser support; always guard `document.startViewTransition`.
- Every transition file needs `'use client'`; server components can't use AnimatePresence/usePathname.
## Reference files
- `references/full-examples.md` — directional/slide transitions, shared-element View Transitions with `view-transition-name`, a non-`mode="wait"` crossfade variant, loading-state transitions with `loading.tsx`, and a complete working App Router folder layout.
@@ -1,176 +0,0 @@
# Full examples and variants
## Working folder layout
```
app/
layout.tsx # persistent shell (html/body, providers)
template.tsx # remounts per route -> hosts AnimatePresence
page-transition.tsx # motion wrapper (enter/exit variants)
frozen-router.tsx # FrozenRouter (LayoutRouterContext snapshot)
page.tsx # home
about/page.tsx
globals.css
```
## Directional slide transitions
Track direction by comparing route depth or a route order map, then feed it to variants.
```tsx
// app/page-transition.tsx
'use client';
import { motion } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { useRef } from 'react';
const order = ['/', '/about', '/work', '/contact'];
export function PageTransition({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
const prev = useRef(pathname);
const dir =
order.indexOf(pathname) > order.indexOf(prev.current) ? 1 : -1;
prev.current = pathname;
return (
<motion.div
custom={dir}
variants={{
initial: (d: number) => ({ opacity: 0, x: 40 * d }),
animate: { opacity: 1, x: 0 },
exit: (d: number) => ({ opacity: 0, x: -40 * d }),
}}
initial="initial"
animate="animate"
exit="exit"
transition={{ duration: 0.3, ease: [0.22, 1, 0.36, 1] }}
>
{children}
</motion.div>
);
}
```
## Crossfade variant (no mode="wait")
Omit `mode="wait"` so old and new overlap. Stack them absolutely to avoid layout jump.
```tsx
// app/template.tsx
'use client';
import { AnimatePresence, motion } from 'framer-motion';
import { usePathname } from 'next/navigation';
import { FrozenRouter } from './frozen-router';
export default function Template({ children }: { children: React.ReactNode }) {
const pathname = usePathname();
return (
<AnimatePresence initial={false}>
<motion.div
key={pathname}
style={{ gridArea: '1 / 1' }} // overlap in a 1-cell grid parent
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.35 }}
>
<FrozenRouter>{children}</FrozenRouter>
</motion.div>
</AnimatePresence>
);
}
```
Wrap the template output's parent in `display: grid` so both stacked children occupy `grid-area: 1 / 1`.
## Shared-element transition (View Transitions API)
Give the same logical element the same `view-transition-name` on both pages; the browser morphs between them.
```tsx
// list page
<img src={cover} style={{ viewTransitionName: `cover-${id}` }} />
// detail page
<img src={cover} style={{ viewTransitionName: `cover-${id}` }} />
```
```css
::view-transition-old(root),
::view-transition-new(root) { animation-duration: 0.3s; }
/* the named element animates automatically between its two positions */
```
With `next-view-transitions`, use its `<Link>` and the morph happens on navigation. Each `view-transition-name` must be unique on the page at a time.
## loading.tsx + transitions
`loading.tsx` shows an instant Suspense fallback during server work. To animate it, make the fallback a motion component; it mounts/unmounts within the same template-driven AnimatePresence flow.
```tsx
// app/work/loading.tsx
'use client';
import { motion } from 'framer-motion';
export default function Loading() {
return (
<motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }}>
Loading…
</motion.div>
);
}
```
## Reduced-motion
```tsx
'use client';
import { useReducedMotion, motion } from 'framer-motion';
export function PageTransition({ children }: { children: React.ReactNode }) {
const reduce = useReducedMotion();
return (
<motion.div
initial={reduce ? false : { opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
exit={reduce ? { opacity: 1 } : { opacity: 0, y: -12 }}
transition={{ duration: reduce ? 0 : 0.3 }}
>
{children}
</motion.div>
);
}
```
For the View Transitions API, gate with CSS:
```css
@media (prefers-reduced-motion: reduce) {
::view-transition-old(root),
::view-transition-new(root) { animation: none; }
}
```
## FrozenRouter import note across versions
The internal context import has shifted across Next versions, e.g.:
```ts
// commonly:
import { LayoutRouterContext } from 'next/dist/shared/lib/app-router-context.shared-runtime';
```
If an upgrade breaks the import, search `node_modules/next/dist/shared/lib/` for `app-router-context` and update the path. Because it is internal, pin awareness of this in any upgrade checklist.
## Framer Motion vs View Transitions decision
| Factor | Framer Motion | View Transitions API |
|---|---|---|
| Browser support | Broad (JS lib) | Uneven; needs fallback |
| Orchestration/stagger | Excellent | Limited |
| Interruptible exits | Yes | Limited |
| Shared element morph | Manual (layoutId) | Native, simple |
| Bundle cost | Adds library | Minimal/native |
| Setup complexity | Medium (FrozenRouter) | Low (next-view-transitions) |
---
Freeze the outgoing route and exit transitions finally fire as intended. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=page-transition-animation)** — the AI motion agent for editable, on-brand motion graphics.
Whitespace-only changes.
-167
View File
@@ -1,167 +0,0 @@
---
name: svg-animation
description: This skill should be used when the user asks to "animate an SVG", "make a line draw itself on", "do a stroke draw-on / signature animation", "morph one shape into another", "move an element along a path", "animate an icon/logo", or "animate an SVG gradient or filter". Covers stroke-dashoffset draw-on, path morphing, motion-along-path, and animated icons/gradients/filters via CSS, SMIL, and GSAP.
version: 0.1.0
---
# SVG Animation
Crisp, lightweight, infinitely scalable vector motion — ideal for icons, illustrations, logos, and data marks. SVG can be animated three ways: CSS (declarative, simple), SMIL (`<animate>` inside the SVG), and JS (GSAP/Web Animations, for control and morphing). Choose per task; the techniques below say which.
## When to use
- Stroke "draw-on" of icons, illustrations, signatures, maps
- Shape/path morphing and animated icon state changes (menu ↔ close, play ↔ pause)
- Moving an element along a path (motion path)
- Animated gradients, filters (glow, displacement), and animated logos
## Core techniques
### Stroke draw-on (the staple)
Draw the dash array as long as the path, offset it fully (invisible), then animate the offset to 0.
```css
.path {
stroke-dasharray: var(--len);
stroke-dashoffset: var(--len);
animation: draw 1.4s ease forwards;
}
@keyframes draw { to { stroke-dashoffset: 0; } }
```
Getting the length:
- JS (most reliable): `const len = path.getTotalLength(); path.style.setProperty("--len", len);`
- No-JS trick: set `pathLength="1"` on the `<path>`, then `stroke-dasharray: 1; stroke-dashoffset: 1;` and animate to `0`. This normalizes any path to a 0–1 length so no measurement is needed.
Reverse (erase) by animating offset from 0 back to `len`. Stagger multiple paths with `animation-delay`. Direction of drawing follows the path's point order; reverse it in the editor or negate the offset sign if it draws "backwards".
### Morphing one path into another
Paths interpolate point-by-point, so a naive morph requires both `d` attributes to have the **same number and type of commands**. Two robust approaches:
- **GSAP MorphSVG** (free as of GSAP 3.12) — handles mismatched point counts automatically and finds a good mapping:
```js
gsap.registerPlugin(MorphSVGPlugin);
gsap.to("#start", { morphSVG: "#end", duration: 0.8, ease: "power2.inOut" });
// Convert any shape to a morph-able path:
MorphSVGPlugin.convertToPath("circle, rect, ellipse, line, polygon");
```
- **Flubber** (small standalone lib) — generates interpolators without GSAP, good with React/Framer Motion:
```js
import { interpolate } from "flubber";
const interpolator = interpolate(pathA, pathB, { maxSegmentLength: 2 });
// interpolator(0) === pathA, interpolator(1) === pathB; feed t into a tween.
```
For hand-authored morphs (icon toggles), keep both paths with identical command structure and animate `d` directly via Web Animations or CSS (`d` is animatable in modern browsers via `path("...")`).
### Motion along a path
- **GSAP MotionPath** (preferred — control, alignment, scrub):
```js
gsap.registerPlugin(MotionPathPlugin);
gsap.to("#rocket", {
duration: 4, repeat: -1, ease: "none",
motionPath: { path: "#track", align: "#track", autoRotate: true, alignOrigin: [0.5, 0.5] },
});
```
`autoRotate: true` orients the object to the path tangent; `align` makes coordinates relative to the path element.
- **SMIL** (no JS):
```svg
<path id="track" d="M10,80 C40,10 120,10 150,80" fill="none"/>
<circle r="6" fill="#3b82f6">
<animateMotion dur="3s" repeatCount="indefinite" rotate="auto">
<mpath href="#track"/>
</animateMotion>
</circle>
```
- **CSS** offset-path (modern, declarative): `offset-path: path("M10,80 C..."); animation: move 3s linear infinite;` with `@keyframes move { to { offset-distance: 100%; } }` and `offset-rotate: auto`.
### Animated gradients and filters
Gradients: animate `gradientTransform` or stop offsets. A sheen sweep:
```svg
<linearGradient id="sheen">
<stop offset="0%" stop-color="#fff" stop-opacity="0"/>
<stop offset="50%" stop-color="#fff" stop-opacity=".8"/>
<stop offset="100%" stop-color="#fff" stop-opacity="0"/>
<animateTransform attributeName="gradientTransform" type="translate"
from="-1 0" to="1 0" dur="2s" repeatCount="indefinite"/>
</linearGradient>
```
Filters: animate `feDisplacementMap` `scale` for gooey/wobble, `feGaussianBlur` `stdDeviation` for focus pulls, or `feColorMatrix`/`feFlood` for glow. Filters are paint-heavy — animate sparingly and prefer `transform`/`opacity` where possible.
## Implementation choice (pick fast)
| Need | Use |
|------|-----|
| Single declarative draw/fade | CSS |
| Self-contained, no JS bundle | SMIL (`<animate*>` in the SVG) |
| Coordinated, scrubbable, scroll-tied | GSAP |
| Mismatched-point morph | GSAP MorphSVG or Flubber |
| Path following with rotation | GSAP MotionPath / CSS offset-path |
SMIL caveat: not supported in IE/old Edge and historically deprecation-flagged; for max reach or scroll-syncing, prefer CSS or JS. SMIL is still fine for self-contained icon assets in evergreen browsers.
## Authoring and optimization
- Build/clean with **SVGO**: keep `viewBox`, drop editor metadata, but disable `cleanupIds`/`removeViewBox` and any plugin that renames IDs you reference from CSS/JS/SMIL. Disable `mergePaths` and `convertShapeToPath` if you animate individual sub-paths or shapes.
- Inline the SVG in the DOM (not `<img src>`) so CSS/JS can reach its internals; `<img>`-embedded SVG can only self-animate via internal SMIL/CSS.
- Set explicit `viewBox` and avoid fixed `width`/`height` so the asset scales fluidly.
- For draw-on, ensure paths are actual strokes (`fill:none; stroke:...`), not filled outlines — dashoffset only affects strokes.
- Respect `prefers-reduced-motion`: gate looping/large motion; keep a static final state.
## Deliver & verify (standalone HTML)
> **Packaged helper** (`scripts/`): `scripts/seek-shot.sh anim.html 0 1.5 3` freezes the `?t=N` harness and screenshots each moment; `scripts/contact-sheet.sh sheet.png frame-*.png` tiles them for one-glance review. See `scripts/README.md`.
For a self-contained icon/logo/draw-on the deliverable is **one HTML file that opens directly in a browser** — inline the SVG in the markup, drive the animation with one mechanism, no build step. One file is the right tier for a vector asset; don't reach for a bundler.
**Output contract:**
- One `.html` file: inline `<svg>`, plus CSS `@keyframes` / a `<script>` with GSAP from CDN / SMIL `<animate*>` — pick one driver.
- Include the seek harness matching that driver so any moment can be frozen for a screenshot.
**Seek harness — freeze an exact moment.** `?t=N` seeks and pauses so a screenshot lands on a still frame. Use the mechanism that matches how the SVG animates:
```html
<script>
const t = new URLSearchParams(location.search).get("t");
if (t !== null) {
const N = parseFloat(t);
// SMIL: pause the SVG's own clock and scrub it
const svg = document.querySelector("svg");
svg.pauseAnimations(); svg.setCurrentTime(N);
// CSS @keyframes draw-on: el.style.animationDelay=(-N)+"s"; el.style.animationPlayState="paused";
// GSAP timeline: tl.pause(); tl.seek(N);
}
window.__ready = true;
</script>
```
**Verify loop — render → freeze → screenshot → check:** open the file at start / mid / end (`?t=0`, `?t=<dur/2>`, `?t=<dur>`), screenshot each, and check **fidelity** (stroke draws in the right direction, morph endpoints clean) plus **artifacts** (path clipped by `viewBox`, stroke vanishing from a stale dashoffset, FOUC, jank at the morph seam). Any headless tool works:
```bash
npx playwright screenshot --wait-for-timeout=500 "file://$PWD/icon.html?t=0.7" frame-mid.png
```
**Before you finish:**
1. Opens standalone — no console errors, inline SVG reachable, CDN (if any) loads.
2. The seek mechanism for your driver freezes a deterministic frame.
3. Screenshotted at start / mid / end — matches the brief, no clipping or off-`viewBox` strokes.
4. `prefers-reduced-motion` honored — looping/large motion gated, static final state kept.
5. Easing is intentional — `ease`/GSAP ease chosen on purpose, no accidental `linear` draw-on.
## Reference files
- `references/svg-techniques.md` — full dashoffset math and `getTotalLength` gotchas, the `pathLength="1"` normalization, GSAP MorphSVG vs Flubber decision guide with code, an icon-toggle morph (hamburger↔close), MotionPath/offset-path details, SMIL-vs-CSS-vs-JS tradeoffs, and an SVGO config tuned for animation.
@@ -1,214 +0,0 @@
# SVG Animation Techniques (detailed)
## 1. Stroke draw-on: the math
`stroke-dasharray` defines a dash pattern; `stroke-dashoffset` shifts where the pattern starts. Set the dash equal to the whole path length and offset it by that same length → the visible dash is pushed entirely off the path (invisible). Animating offset to 0 slides the dash into view, revealing the stroke progressively.
```
visible fraction = 1 - (dashoffset / pathLength)
```
So offset = length → 0% drawn; offset = 0 → 100% drawn; offset = length/2 → 50% drawn (useful for scroll mapping: `offset = length * (1 - progress)`).
### getTotalLength gotchas
```js
const path = document.querySelector("#sig");
const len = path.getTotalLength(); // returns user units of the path geometry
path.style.strokeDasharray = len;
path.style.strokeDashoffset = len;
requestAnimationFrame(() => { // next frame so the transition has a start value
path.style.transition = "stroke-dashoffset 1.6s ease";
path.style.strokeDashoffset = "0";
});
```
- `getTotalLength()` measures the path's own coordinate system, ignoring CSS transforms/scaling — which is what you want for dasharray.
- It only works on geometry elements (`path, line, polyline, polygon, circle, ellipse, rect`). For `<text>` draw-on you must convert text to paths first.
- Rounding: browsers can clip the last sub-pixel; pad slightly (`len + 1`) if the end never fully closes.
- Compound paths (multiple `M` subpaths in one `d`) draw all subpaths simultaneously. Split into separate `<path>`s with staggered `animation-delay` for sequential drawing.
### No-JS normalization with pathLength
`pathLength="1"` tells the browser to treat the path's length as exactly 1, regardless of real geometry. Then dash math is unit-free:
```svg
<path d="..." pathLength="1" fill="none" stroke="#111"
style="stroke-dasharray:1; stroke-dashoffset:1; animation:draw 1.4s ease forwards"/>
```
```css
@keyframes draw { to { stroke-dashoffset: 0; } }
```
This is the cleanest pure-CSS draw-on and avoids hardcoding measured lengths that break when the path is edited. Use `pathLength="100"` if you prefer to think in percentages.
### Scroll-driven draw-on (no library, via offset)
```js
const len = path.getTotalLength();
path.style.strokeDasharray = len;
function onScroll() {
const p = Math.min(1, Math.max(0, scrollProgress())); // 0..1
path.style.strokeDashoffset = len * (1 - p);
}
document.addEventListener("scroll", onScroll, { passive: true });
```
## 2. Morphing
### Why naive morphs break
Path interpolation walks the `d` command list of A and B in lockstep. If A has 4 cubic curves and B has 7, or A uses `L` where B uses `C`, the browser/animator either refuses or produces garbage. Fixes: match commands by hand, or use a library that resamples.
### GSAP MorphSVG (best for arbitrary shapes)
```js
import gsap from "gsap";
import { MorphSVGPlugin } from "gsap/MorphSVGPlugin";
gsap.registerPlugin(MorphSVGPlugin);
// any shape -> path so it can morph
MorphSVGPlugin.convertToPath("#circ, #star");
gsap.to("#circ", {
duration: 0.9, ease: "power2.inOut",
morphSVG: { shape: "#star", shapeIndex: "auto", type: "rotational" },
});
```
- `shapeIndex` rotates the starting point mapping to minimize twisting; `"auto"` lets GSAP pick, or pass a number to tune.
- `type: "rotational"` interpolates angles/lengths instead of raw coordinates — usually smoother for organic morphs.
- `map: "size" | "position" | "complexity"` changes how sub-paths in compound shapes are matched.
### Flubber (standalone, framework-friendly)
```js
import { interpolate, separate, combine } from "flubber";
// 1 -> 1 shape
const lerp = interpolate(pathA, pathB, { maxSegmentLength: 2 });
// splitting one shape into many (or vice versa)
const split = separate(oneShape, [shape1, shape2, shape3], { single: true });
```
Drive `lerp(t)` with any tween/`requestAnimationFrame`, or inside Framer Motion:
```jsx
import { motion, useMotionValue, useTransform, animate } from "motion/react";
const progress = useMotionValue(0);
const d = useTransform(progress, [0, 1], [0, 1], { clamp: false });
const path = useTransform(d, (v) => interpolate(A, B)(v));
// animate(progress, 1, { duration: 0.6 }) then <motion.path d={path} />
```
Use Flubber when you can't add GSAP or need React-native value plumbing; use MorphSVG for the highest-quality mapping and convenience.
### Hand-authored icon toggle (hamburger ↔ close) — no morph library
When you control both shapes, give them identical structure and animate transforms instead of `d`:
```svg
<svg viewBox="0 0 24 24" class="menu" aria-label="Menu">
<line class="top" x1="3" y1="6" x2="21" y2="6"/>
<line class="mid" x1="3" y1="12" x2="21" y2="12"/>
<line class="bot" x1="3" y1="18" x2="21" y2="18"/>
</svg>
```
```css
.menu line { stroke:#111; stroke-width:2; transition: transform .25s ease, opacity .2s ease;
transform-origin: center; transform-box: fill-box; }
.menu.open .top { transform: translateY(6px) rotate(45deg); }
.menu.open .mid { opacity: 0; }
.menu.open .bot { transform: translateY(-6px) rotate(-45deg); }
```
`transform-box: fill-box` makes `transform-origin: center` resolve to the element's own bounding box — essential for SVG rotation; without it the origin is the SVG viewport origin.
## 3. Motion along a path — details
### GSAP MotionPath
```js
gsap.to("#dot", {
duration: 5, repeat: -1, ease: "none",
motionPath: {
path: "#route",
align: "#route", // coordinates relative to the path element
alignOrigin: [0.5, 0.5], // pin the object's center to the path
autoRotate: true, // or a number to add a constant offset angle
start: 0, end: 1, // animate a sub-segment, e.g. 0.2..0.8
},
});
```
Convert a series of points into a smooth path: `MotionPathPlugin.convertToPath(...)`, or pass `motionPath: [{x:0,y:0},{x:100,y:50},...]` and GSAP draws a curve through them.
### CSS offset-path (declarative, modern)
```css
.dot {
offset-path: path("M10,80 C40,10 120,10 150,80");
offset-rotate: auto; /* face direction of travel */
animation: travel 3s linear infinite;
}
@keyframes travel { to { offset-distance: 100%; } }
```
Newer syntax also accepts `offset-path: url(#route)` referencing a `<path>` id and shapes like `ray()`. Good support in evergreen browsers; no JS needed.
### SMIL animateMotion
Self-contained inside the SVG; use `rotate="auto"` and `<mpath href="#id"/>`. Best for portable icon assets where you don't want external CSS/JS. Avoid when you need scroll-sync or broad legacy support.
## 4. SMIL vs CSS vs JS — tradeoffs
| Axis | SMIL | CSS | JS (GSAP/WAAPI) |
|------|------|-----|-----------------|
| Bundle cost | none (inline) | none | library (GSAP ~JS) |
| Works in `<img>` SVG | yes | yes (internal) | no |
| Reach (legacy IE/Edge) | no | partial | yes |
| Scroll/scrub sync | hard | hard | easy |
| Morph mismatched paths | no | no | yes (MorphSVG/Flubber) |
| Timeline orchestration | limited | limited | full |
| Animate `d`/gradients/filters | yes | partial | yes |
Default: CSS for simple declarative effects, GSAP for anything coordinated/scrubbable/morphing, SMIL only for portable self-animating assets in evergreen targets.
## 5. SVGO config tuned for animation
Aggressive SVGO defaults will strip the very things you animate. Use a config like:
```js
// svgo.config.js
module.exports = {
multipass: true,
plugins: [
{ name: "preset-default", params: { overrides: {
removeViewBox: false, // keep responsive scaling
cleanupIds: false, // DO NOT rename ids referenced by CSS/JS/SMIL/gradients
mergePaths: false, // keep sub-paths separate for staggered draw-on
convertShapeToPath: false, // keep <circle>/<rect> if SMIL/CSS targets them
removeHiddenElems: false, // keep elements you toggle visible via animation
inlineStyles: false, // preserve class hooks
} } },
{ name: "removeDimensions" }, // drop width/height, keep viewBox -> fluid scaling
{ name: "prefixIds" }, // namespace ids if inlining many SVGs to avoid id collisions
],
};
```
If multiple inlined SVGs share gradient/filter ids, id collisions make the LAST definition win for everyone — `prefixIds` (or unique authoring) prevents this classic bug.
## 6. Reduced motion
```css
@media (prefers-reduced-motion: reduce) {
.path { animation: none; stroke-dashoffset: 0; } /* show final drawn state instantly */
}
```
For looping decorative SVG (spinners, ambient gradients), pause or hide them under reduced-motion; for functional icon toggles, keep the state change but drop the easing duration.
---
Pick the right method per shape and SVG draws, morphs, and travels smoothly. Built by **[iart.ai](https://iart.ai/?utm_source=github&utm_medium=readme&utm_campaign=web-animation-skills&utm_content=skill_footer&utm_term=svg-animation)** — the AI motion agent for editable, on-brand motion graphics.
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/60fps-animation
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/accessible-animation
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/ascii-animation
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/glassmorphism
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/gsap-web
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/lottie-animation
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/micro-interaction
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/page-transition-animation
-102
View File
@@ -1,102 +0,0 @@
---
name: remotion-video
description: Create videos from React code with Remotion. Use when the user asks to make, animate, preview, or render a video, motion graphic, intro, caption, or social clip using code.
---
# Remotion Video
Remotion makes videos out of React components. Each frame is a web page. Render them in order and you get an MP4.
## Core ideas
- **Composition**: one video. Has `width`, `height`, `fps`, `durationInFrames`.
- **Frame**: `useCurrentFrame()` returns the current frame number. All animation is a function of the frame.
- **`interpolate`**: maps a frame range to a value range (fade, slide).
- **`spring`**: natural bouncy motion.
- **`Sequence`**: shows children only during a frame range.
- **`AbsoluteFill`**: full-screen layer; stack them for backgrounds.
- **`Audio` / `OffthreadVideo` / `Img`**: media. Put files in `public/` and load with `staticFile("name.mp3")`.
## Workflow
1. **Plan first.** Ask or decide: length (seconds), size (1920x1080, or 1080x1920 for vertical), fps (30), and the scenes. Keep scenes to a short list.
2. **Set up** (skip if the project exists):
```
npx create-video@latest
cd <project> && npm install
```
3. **Write** compositions in `src/`, register them in `src/Root.tsx`.
4. **Preview**: `npm run dev` (opens Remotion Studio).
5. **Render**: `npx remotion render <CompositionId> out/video.mp4`
Still frame: `npx remotion still <CompositionId> out/frame.png --frame=30`
6. **Verify**: render one still first, check it looks right, then render the full video.
## Starter example
`src/Root.tsx`
```tsx
import { Composition } from "remotion";
import { Hello } from "./Hello";
export const RemotionRoot = () => (
<Composition
id="Hello"
component={Hello}
durationInFrames={150}
fps={30}
width={1920}
height={1080}
defaultProps={{ title: "Hello, world" }}
/>
);
```
`src/Hello.tsx`
```tsx
import { AbsoluteFill, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
export const Hello = ({ title }: { title: string }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const opacity = interpolate(frame, [0, 30], [0, 1], { extrapolateRight: "clamp" });
const scale = spring({ frame, fps, config: { damping: 12 } });
return (
<AbsoluteFill style={{ backgroundColor: "#0b1020", justifyContent: "center", alignItems: "center" }}>
<h1 style={{ color: "white", fontSize: 120, opacity, transform: `scale(${scale})` }}>{title}</h1>
</AbsoluteFill>
);
};
```
## Rules of thumb
- Never animate with CSS transitions, `setTimeout`, or CSS animations. They don't render per frame. Drive everything from `useCurrentFrame()`.
- Always pass `extrapolateRight: "clamp"` to `interpolate` unless you want values to keep growing.
- Seconds to frames: `seconds * fps`.
- Use `<Sequence from={..} durationInFrames={..}>` to order scenes; `<Series>` to chain them.
- Load fonts with `@remotion/google-fonts` so they are ready before rendering.
- Keep props in `defaultProps` so the user can edit text in the Studio.
- Rendering needs Chromium and ffmpeg (Remotion installs/handles these); first render can be slow.
## Fonts
Google Fonts: `npm i @remotion/google-fonts`, then
```tsx
import { loadFont } from "@remotion/google-fonts/Inter";
const { fontFamily } = loadFont(); // use as style={{ fontFamily }}
```
It downloads the font while rendering, so the machine needs internet access to fonts.googleapis.com. If the render fails with "Failed to load font", the network is blocking it: use a local font file in `public/` with `@remotion/fonts` (`loadFont({ family, url: staticFile("x.woff2") })`) or a system font. (Not verified in the sandbox where this skill was tested, which had no access to Google.)
## Common problems
- **Can't download the browser (no internet / locked-down machine)**: point Remotion at an installed Chromium:
`npx remotion render <Id> out/video.mp4 --browser-executable=/path/to/chromium --chrome-mode=chrome-for-testing`
- **Blank/white frames**: an asset path is wrong; use `staticFile()`.
- **Flicker**: an image or font not loaded; use `<Img>` and `@remotion/google-fonts`.
- **Slow render**: lower resolution/fps while testing, or use `--concurrency`.
## Templates
Copy-paste starting points. Read the one that fits:
- `templates/captions.md` - words highlighted in time with speech
- `templates/charts.md` - animated bar chart
- `templates/intro-outro.md` - title card + chaining scenes with `Series`
- `templates/audio-voiceover.md` - background music, voiceover, auto video length
- `templates/vertical.md` - 1080x1920 clips for Reels/TikTok/Shorts
## Docs
https://www.remotion.dev/docs
@@ -1,62 +0,0 @@
# Template: Audio, music and voiceover
Put sound files in `public/` (mp3 or wav). Load them with `staticFile()`.
`src/Narrated.tsx`
```tsx
import { AbsoluteFill, Audio, Sequence, interpolate, staticFile, useVideoConfig } from "remotion";
import { getAudioDurationInSeconds } from "@remotion/media-utils";
import type { CalculateMetadataFunction } from "remotion";
type Props = { title: string; voice: string; music: string };
// Make the video exactly as long as the voiceover (+1 second of padding).
export const calcNarratedMetadata: CalculateMetadataFunction<Props> = async ({ props }) => {
const seconds = await getAudioDurationInSeconds(staticFile(props.voice));
return { durationInFrames: Math.ceil((seconds + 1) * 30) };
};
export const Narrated = ({ title, voice, music }: Props) => {
const { fps, durationInFrames } = useVideoConfig();
return (
<AbsoluteFill style={{ background: "#0b1020", justifyContent: "center", alignItems: "center" }}>
<h1 style={{ color: "white", fontSize: 110 }}>{title}</h1>
{/* Background music: quiet, fades out over the last second. */}
<Audio
src={staticFile(music)}
volume={(f) => interpolate(f, [durationInFrames - fps, durationInFrames], [0.15, 0], { extrapolateLeft: "clamp", extrapolateRight: "clamp" })}
/>
{/* Voiceover starts half a second in, full volume. */}
<Sequence from={Math.round(fps * 0.5)}>
<Audio src={staticFile(voice)} volume={1} />
</Sequence>
</AbsoluteFill>
);
};
```
Register it (note `calculateMetadata`):
```tsx
<Composition
id="Narrated"
component={Narrated}
calculateMetadata={calcNarratedMetadata}
durationInFrames={300} // placeholder, replaced by calculateMetadata
fps={30} width={1920} height={1080}
defaultProps={{ title: "My story", voice: "voice.mp3", music: "music.mp3" }}
/>
```
Install: `npm i @remotion/media-utils`
Getting a voiceover
- Record yourself, or generate speech with a text-to-speech service, and save as `public/voice.mp3`. Never commit API keys; keep them in environment variables.
- Pair with `templates/captions.md`: feed it word timings from a transcription of the same file.
Rules
- Music volume 0.1-0.2 so the voice stays clear.
- `<Sequence from={...}>` delays when a sound starts.
- Audio is only in the final render (mp4). Stills (`remotion still`) have no sound.
- Check the sound made it in: `ffprobe out/video.mp4` should list an `Audio:` stream.
@@ -1,38 +0,0 @@
# Template: Captions
Words appear in time with speech. Give each word a start time in seconds.
`src/Captions.tsx`
```tsx
import { AbsoluteFill, useCurrentFrame, useVideoConfig } from "remotion";
type Word = { text: string; start: number; end: number }; // seconds
export const Captions = ({ words, background = "#111" }: { words: Word[]; background?: string }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const t = frame / fps;
// Show a window of up to 5 words around the current one.
const current = words.findIndex((w) => t >= w.start && t < w.end);
const i = current === -1 ? 0 : current;
const visible = words.slice(Math.floor(i / 5) * 5, Math.floor(i / 5) * 5 + 5);
return (
<AbsoluteFill style={{ backgroundColor: background, justifyContent: "flex-end", alignItems: "center", paddingBottom: 200 }}>
<div style={{ fontSize: 72, fontWeight: 800, color: "white", textShadow: "0 4px 12px black", textAlign: "center", maxWidth: "80%" }}>
{visible.map((w, k) => (
<span key={k} style={{ color: t >= w.start && t < w.end ? "#ffd400" : "white", marginRight: 16 }}>
{w.text}
</span>
))}
</div>
</AbsoluteFill>
);
};
```
Tips
- Get word times from a transcription tool (e.g. `@remotion/captions` or Whisper) and save them as JSON in `public/`.
- `background` is the backdrop when there is no video. Pass `"transparent"` when layering over a video.
- Layer it over the video: `<AbsoluteFill><OffthreadVideo src={staticFile("clip.mp4")} /><Captions words={words} background="transparent" /></AbsoluteFill>`.
@@ -1,37 +0,0 @@
# Template: Animated bar chart
Bars grow one after another.
`src/BarChart.tsx`
```tsx
import { AbsoluteFill, spring, useCurrentFrame, useVideoConfig } from "remotion";
type Bar = { label: string; value: number };
export const BarChart = ({ data, color = "#4f8cff" }: { data: Bar[]; color?: string }) => {
const frame = useCurrentFrame();
const { fps } = useVideoConfig();
const max = Math.max(...data.map((d) => d.value));
return (
<AbsoluteFill style={{ backgroundColor: "#0b1020", padding: 120, justifyContent: "flex-end" }}>
<div style={{ display: "flex", alignItems: "flex-end", gap: 40, height: 700 }}>
{data.map((d, i) => {
const grow = spring({ frame: frame - i * 6, fps, config: { damping: 15 } });
return (
<div key={d.label} style={{ flex: 1, textAlign: "center", color: "white", fontSize: 36 }}>
<div style={{ height: (d.value / max) * 600 * grow, background: color, borderRadius: 8 }} />
<div style={{ marginTop: 16 }}>{d.label}</div>
</div>
);
})}
</div>
</AbsoluteFill>
);
};
```
Tips
- Delay each bar with `frame - i * 6` (6 frames apart).
- For lines, animate `strokeDashoffset` on an SVG path using `interpolate`.
- Keep numbers readable: show the value as text, rounded.
@@ -1,34 +0,0 @@
# Template: Title intro / outro card
A short card (2-3 seconds) with a title and subtitle. Use at the start or end.
`src/TitleCard.tsx`
```tsx
import { AbsoluteFill, interpolate, spring, useCurrentFrame, useVideoConfig } from "remotion";
export const TitleCard = ({ title, subtitle }: { title: string; subtitle?: string }) => {
const frame = useCurrentFrame();
const { fps, durationInFrames } = useVideoConfig();
const rise = spring({ frame, fps, config: { damping: 14 } });
const fadeOut = interpolate(frame, [durationInFrames - 15, durationInFrames], [1, 0], {
extrapolateLeft: "clamp",
extrapolateRight: "clamp",
});
return (
<AbsoluteFill style={{ background: "linear-gradient(135deg,#1b2a6b,#0b1020)", justifyContent: "center", alignItems: "center", opacity: fadeOut }}>
<h1 style={{ color: "white", fontSize: 130, margin: 0, transform: `translateY(${(1 - rise) * 60}px)`, opacity: rise }}>{title}</h1>
{subtitle && <p style={{ color: "#9fb3ff", fontSize: 48, opacity: rise }}>{subtitle}</p>}
</AbsoluteFill>
);
};
```
Chain with the main video using `<Series>`:
```tsx
<Series>
<Series.Sequence durationInFrames={90}><TitleCard title="My Video" /></Series.Sequence>
<Series.Sequence durationInFrames={600}><MainScene /></Series.Sequence>
<Series.Sequence durationInFrames={90}><TitleCard title="Thanks for watching" /></Series.Sequence>
</Series>
```
@@ -1,23 +0,0 @@
# Template: Vertical clips (Reels / TikTok / Shorts)
Same code, different size. Register a vertical composition:
```tsx
<Composition
id="Vertical"
component={MyScene}
width={1080}
height={1920}
fps={30}
durationInFrames={30 * 30} // 30 seconds
/>
```
Render: `npx remotion render Vertical out/vertical.mp4`
Rules
- Keep text inside the **safe zone**: about 150px from the top, 350px from the bottom (apps cover those parts with buttons and captions), and 60px from the sides.
- Use big text (60px+). Phone screens are small.
- Keep clips under 60 seconds (Shorts limit); 15-30 seconds does best.
- Use `useVideoConfig()` for width/height instead of hard-coding, so the same scene works wide and tall.
- Put captions in the lower-middle, above the bottom safe zone (see captions.md).
-1
View File
@@ -1 +0,0 @@
../../.agents/skills/svg-animation
+12
View File
@@ -0,0 +1,12 @@
# Copy to .env style settings on your host. Never commit real values.
ADMIN_EMAIL=rana.krunal7558@gmail.com
ADMIN_PASSWORD=pick-a-long-password-here
# Where new tickets are emailed (this is already the default)
TICKET_TO=rana.krunal7558@gmail.com
# Gmail sending: use an "App Password", not your normal password
SMTP_HOST=smtp.gmail.com
SMTP_PORT=465
SMTP_USER=rana.krunal7558@gmail.com
SMTP_PASS=your-16-letter-app-password
# Set to 1 when hosted behind a proxy (most hosts)
TRUST_PROXY=1
+4
View File
@@ -0,0 +1,4 @@
node_modules
dist
server/data
.env
+25
View File
@@ -0,0 +1,25 @@
# Deploy checklist (Hostinger)
## A. Before you start
- [ ] Plan is Business Web Hosting or a Cloud plan (Node.js Web App supported)
- [ ] Gmail app password created (myaccount.google.com > Security > 2-Step Verification > App passwords)
## B. In hPanel: Websites > Add website > Node.js Web App > Import Git repository
- [ ] Repo: keithrana/cycle-atlas
- [ ] Branch: claude/sleepy-goodall-rykli1 (NOT main)
- [ ] Root/app directory: it-support (if no such box, ask Claude to split into its own repo)
- [ ] Node version: 22.x or 24.x
- [ ] Build command: npm run build
- [ ] Start command: npm start (entry file, if asked: server/index.js)
## C. Environment variables (type them only into Hostinger, never into chat or Git)
ADMIN_EMAIL, ADMIN_PASSWORD (10+ chars), SMTP_HOST=smtp.gmail.com, SMTP_PORT=465,
SMTP_USER, SMTP_PASS (Gmail app password), TRUST_PROXY=1, DATA_DIR=/home/<your-username>/helpdesk-data
## D. Deploy, then test in order
1. [ ] Page loads over https:// and the video plays
2. [ ] Search "wifi" shows answers; send a test ticket
3. [ ] Email arrives at rana.krunal7558@gmail.com (check Spam)
4. [ ] /#/staff login works and the ticket is listed
5. [ ] Add a test FAQ, redeploy, confirm it is still there (proves data is kept)
6. [ ] Log out; /#/staff asks for login again
+18
View File
@@ -0,0 +1,18 @@
# IT Support Site: PRD (plan)
Restaurant analogy: the FAQ database is the **kitchen's recipe book**. The website is the **dining room**.
## Core features
1. Cinematic hero: looping video, glass buttons (exactly as specified)
2. Search bar in the hero: type a problem, get matching answers
3. Category chips: browse the 11 topics (Access, Network, Hardware...)
4. FAQ answer cards: question, answer, optional "official guide" link
5. Footer social icons
## Phased roadmap
- **Phase 1 – Food stand (TODAY):** hero + search + categories + 87 FAQs from the database, baked in as a JSON file. No server.
- **Phase 2 – Small restaurant (DONE, browser-only storage):** "Was this helpful?" votes, "Contact IT" ticket form, shareable links per question.
- **Phase 3 – Full restaurant (DONE):** small back-of-house server + real database, staff login, admin page to edit FAQs, ticket tracking.
## Test ladder
1. Page loads, no console errors 2. Buttons/search work 3. Real data/links work 4. Security (no raw HTML injection, safe links)
+11
View File
@@ -0,0 +1,11 @@
# HelpDesk IT Support
Run locally (needs Node 22+):
npm install
npm run build
ADMIN_EMAIL=you@example.com ADMIN_PASSWORD='a-long-password' npm start
Open http://localhost:3001 (staff login: http://localhost:3001/#/staff)
For development with live reload: run `npm run server` and `npm run dev` in two terminals.
Settings are listed in `.env.example`. Data lives in `server/data/helpdesk.db`: back it up, and keep it on a persistent disk when hosting.
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>HelpDesk | IT Support</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+3528
View File
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
{
"name": "it-support",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"preview": "vite preview",
"server": "node server/index.js",
"start": "NODE_ENV=production node server/index.js"
},
"dependencies": {
"express": "^4.22.3",
"lucide-react": "^0.460.0",
"nodemailer": "^10.0.13",
"react": "^18.3.1",
"react-dom": "^18.3.1"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react": "^4.3.3",
"autoprefixer": "^10.4.20",
"postcss": "^8.4.49",
"tailwindcss": "^3.4.15",
"typescript": "~5.6.2",
"vite": "^5.4.11"
}
}
+1
View File
@@ -0,0 +1 @@
export default { plugins: { tailwindcss: {}, autoprefixer: {} } }
+48
View File
@@ -0,0 +1,48 @@
import { scryptSync, randomBytes, timingSafeEqual, createHash } from 'node:crypto'
import { db } from './db.js'
export const SESSION_DAYS = 7
export const hashPassword = (pw) => {
const salt = randomBytes(16)
return `${salt.toString('hex')}:${scryptSync(pw, salt, 64).toString('hex')}`
}
export const verifyPassword = (pw, stored) => {
const [salt, hash] = stored.split(':')
const a = Buffer.from(hash, 'hex')
const b = scryptSync(pw, Buffer.from(salt, 'hex'), 64)
return a.length === b.length && timingSafeEqual(a, b)
}
const sha = (t) => createHash('sha256').update(t).digest('hex')
export function createSession(staffId) {
const token = randomBytes(32).toString('hex')
db.prepare('INSERT INTO sessions VALUES (?,?,?)').run(sha(token), staffId, Date.now() + SESSION_DAYS * 864e5)
return token
}
export const destroySession = (token) => db.prepare('DELETE FROM sessions WHERE token_hash=?').run(sha(token))
function cookieToken(req) {
const m = /(?:^|;\s*)session=([a-f0-9]{64})/.exec(req.headers.cookie || '')
return m ? m[1] : null
}
export { cookieToken }
export function requireStaff(req, res, next) {
const token = cookieToken(req)
const row = token && db.prepare('SELECT s.id, s.email, s.name, x.expires FROM sessions x JOIN staff s ON s.id=x.staff_id WHERE x.token_hash=?').get(sha(token))
if (!row || row.expires < Date.now()) return res.status(401).json({ error: 'Please log in.' })
req.staff = row
next()
}
// Tiny in-memory rate limiter: `max` hits per `windowMs` per IP+bucket.
const hits = new Map()
export const rateLimit = (bucket, max, windowMs) => (req, res, next) => {
const key = `${bucket}:${req.ip}`
const now = Date.now()
const recent = (hits.get(key) || []).filter((t) => now - t < windowMs)
if (recent.length >= max) return res.status(429).json({ error: 'Too many tries. Please wait a bit.' })
recent.push(now)
hits.set(key, recent)
next()
}
+24
View File
@@ -0,0 +1,24 @@
import { DatabaseSync } from 'node:sqlite'
import { readFileSync, mkdirSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
const here = dirname(fileURLToPath(import.meta.url))
const dataDir = process.env.DATA_DIR || join(here, 'data')
mkdirSync(dataDir, { recursive: true })
export const db = new DatabaseSync(join(dataDir, 'helpdesk.db'))
db.exec(`
CREATE TABLE IF NOT EXISTS faqs (id INTEGER PRIMARY KEY AUTOINCREMENT, category TEXT NOT NULL, question TEXT NOT NULL, answer TEXT NOT NULL, link TEXT NOT NULL DEFAULT '', link_label TEXT NOT NULL DEFAULT '');
CREATE TABLE IF NOT EXISTS tickets (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT NOT NULL, topic TEXT NOT NULL, message TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'open', emailed INTEGER NOT NULL DEFAULT 0, created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS votes (id INTEGER PRIMARY KEY AUTOINCREMENT, faq_id INTEGER NOT NULL, vote TEXT NOT NULL, created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS staff (id INTEGER PRIMARY KEY AUTOINCREMENT, email TEXT NOT NULL UNIQUE, name TEXT NOT NULL, password_hash TEXT NOT NULL, created TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS sessions (token_hash TEXT PRIMARY KEY, staff_id INTEGER NOT NULL, expires INTEGER NOT NULL);
`)
// First run: copy the 87 FAQs from the bundled file into the real database.
if (db.prepare('SELECT COUNT(*) AS n FROM faqs').get().n === 0) {
const seed = JSON.parse(readFileSync(join(here, '..', 'src', 'data', 'faqs.json'), 'utf8'))
const ins = db.prepare('INSERT INTO faqs (id, category, question, answer, link, link_label) VALUES (?,?,?,?,?,?)')
for (const f of seed) ins.run(f.id, f.category, f.question, f.answer, f.link, f.linkLabel)
}
+151
View File
@@ -0,0 +1,151 @@
import express from 'express'
import { existsSync } from 'node:fs'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { randomBytes } from 'node:crypto'
import { db } from './db.js'
import { hashPassword, verifyPassword, createSession, destroySession, cookieToken, requireStaff, rateLimit, SESSION_DAYS } from './auth.js'
import { sendTicketEmail, emailConfigured } from './mail.js'
const app = express()
const prod = process.env.NODE_ENV === 'production'
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const clean = (s, max) => String(s ?? '').replace(/[\r\n]+/g, ' ').trim().slice(0, max)
const cleanBlock = (s, max) => String(s ?? '').trim().slice(0, max)
const isHttpUrl = (u) => { try { return ['http:', 'https:'].includes(new URL(u).protocol) } catch { return false } }
app.set('trust proxy', process.env.TRUST_PROXY ? 1 : false)
app.disable('x-powered-by')
app.use((req, res, next) => {
res.set({
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'DENY',
'Referrer-Policy': 'same-origin',
'Content-Security-Policy': "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src https://fonts.gstatic.com; media-src https://d8j0ntlcm91z4.cloudfront.net; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'",
})
next()
})
app.use(express.json({ limit: '20kb' }))
// Block cross-site writes: browsers always send Origin on POST/PUT/PATCH/DELETE from other sites.
app.use((req, res, next) => {
if (['GET', 'HEAD'].includes(req.method)) return next()
const origin = req.headers.origin
if (origin && new URL(origin).host !== req.headers.host) return res.status(403).json({ error: 'Bad origin.' })
next()
})
// ---------- Public ----------
const faqOut = (r) => ({ id: r.id, category: r.category, question: r.question, answer: r.answer, link: r.link, linkLabel: r.link_label })
app.get('/api/faqs', (_req, res) => res.json(db.prepare('SELECT * FROM faqs ORDER BY id').all().map(faqOut)))
app.post('/api/tickets', rateLimit('ticket', 5, 3600e3), async (req, res) => {
const t = {
id: `IT-${Date.now().toString(36).toUpperCase()}${randomBytes(2).toString('hex').toUpperCase()}`,
name: clean(req.body.name, 100), email: clean(req.body.email, 200),
topic: clean(req.body.topic, 100), message: cleanBlock(req.body.message, 2000),
}
if (!t.name) return res.status(400).json({ error: 'Please enter your name.' })
if (!EMAIL_RE.test(t.email)) return res.status(400).json({ error: 'Please enter a valid email.' })
if (t.message.length < 10) return res.status(400).json({ error: 'Please describe the problem (at least 10 characters).' })
db.prepare('INSERT INTO tickets (id,name,email,topic,message,created) VALUES (?,?,?,?,?,?)').run(t.id, t.name, t.email, t.topic, t.message, new Date().toISOString())
const emailed = await sendTicketEmail(t)
if (emailed) db.prepare('UPDATE tickets SET emailed=1 WHERE id=?').run(t.id)
res.status(201).json({ id: t.id })
})
app.post('/api/votes', rateLimit('vote', 30, 3600e3), (req, res) => {
const faqId = Number(req.body.faqId)
const vote = req.body.vote
if (!['up', 'down'].includes(vote) || !db.prepare('SELECT 1 FROM faqs WHERE id=?').get(faqId)) return res.status(400).json({ error: 'Bad vote.' })
db.prepare('INSERT INTO votes (faq_id,vote,created) VALUES (?,?,?)').run(faqId, vote, new Date().toISOString())
res.status(201).json({ ok: true })
})
// ---------- Staff login ----------
app.post('/api/login', rateLimit('login', 10, 15 * 60e3), (req, res) => {
const row = db.prepare('SELECT * FROM staff WHERE email=?').get(clean(req.body.email, 200).toLowerCase())
// Same message either way so attackers can't learn which emails exist.
if (!row || !verifyPassword(String(req.body.password ?? ''), row.password_hash)) return res.status(401).json({ error: 'Wrong email or password.' })
const token = createSession(row.id)
res.cookie('session', token, { httpOnly: true, sameSite: 'strict', secure: prod, maxAge: SESSION_DAYS * 864e5, path: '/' })
res.json({ name: row.name, email: row.email })
})
app.post('/api/logout', (req, res) => {
const t = cookieToken(req)
if (t) destroySession(t)
res.clearCookie('session', { path: '/' })
res.json({ ok: true })
})
app.get('/api/me', requireStaff, (req, res) => res.json({ name: req.staff.name, email: req.staff.email }))
// ---------- Staff only ----------
app.get('/api/staff/status', requireStaff, (_req, res) => res.json({ emailConfigured }))
app.get('/api/staff/tickets', requireStaff, (_req, res) => res.json(db.prepare('SELECT * FROM tickets ORDER BY created DESC').all()))
app.patch('/api/staff/tickets/:id', requireStaff, (req, res) => {
if (!['open', 'in_progress', 'closed'].includes(req.body.status)) return res.status(400).json({ error: 'Bad status.' })
db.prepare('UPDATE tickets SET status=? WHERE id=?').run(req.body.status, req.params.id)
res.json({ ok: true })
})
app.get('/api/staff/faqs', requireStaff, (_req, res) => {
const votes = db.prepare("SELECT faq_id, SUM(vote='up') AS up, SUM(vote='down') AS down FROM votes GROUP BY faq_id").all()
const byId = new Map(votes.map((v) => [v.faq_id, v]))
res.json(db.prepare('SELECT * FROM faqs ORDER BY id').all().map((r) => ({ ...faqOut(r), up: byId.get(r.id)?.up ?? 0, down: byId.get(r.id)?.down ?? 0 })))
})
function faqFields(body) {
const f = { category: clean(body.category, 100), question: clean(body.question, 300), answer: cleanBlock(body.answer, 3000), link: clean(body.link, 500), link_label: clean(body.linkLabel, 200) }
if (!f.category || !f.question || !f.answer) return { error: 'Category, question and answer are required.' }
if (f.link && !isHttpUrl(f.link)) return { error: 'Link must start with http:// or https://' }
return { f }
}
app.post('/api/staff/faqs', requireStaff, (req, res) => {
const { f, error } = faqFields(req.body)
if (error) return res.status(400).json({ error })
const r = db.prepare('INSERT INTO faqs (category,question,answer,link,link_label) VALUES (?,?,?,?,?)').run(f.category, f.question, f.answer, f.link, f.link_label)
res.status(201).json({ id: Number(r.lastInsertRowid) })
})
app.put('/api/staff/faqs/:id', requireStaff, (req, res) => {
const { f, error } = faqFields(req.body)
if (error) return res.status(400).json({ error })
db.prepare('UPDATE faqs SET category=?,question=?,answer=?,link=?,link_label=? WHERE id=?').run(f.category, f.question, f.answer, f.link, f.link_label, req.params.id)
res.json({ ok: true })
})
app.delete('/api/staff/faqs/:id', requireStaff, (req, res) => {
db.prepare('DELETE FROM faqs WHERE id=?').run(req.params.id)
res.json({ ok: true })
})
app.get('/api/staff/team', requireStaff, (_req, res) => res.json(db.prepare('SELECT id,email,name,created FROM staff ORDER BY id').all()))
app.post('/api/staff/team', requireStaff, (req, res) => {
const email = clean(req.body.email, 200).toLowerCase(), name = clean(req.body.name, 100), pw = String(req.body.password ?? '')
if (!EMAIL_RE.test(email) || !name) return res.status(400).json({ error: 'Name and a valid email are required.' })
if (pw.length < 10) return res.status(400).json({ error: 'Password must be at least 10 characters.' })
if (db.prepare('SELECT 1 FROM staff WHERE email=?').get(email)) return res.status(409).json({ error: 'That email is already on the team.' })
db.prepare('INSERT INTO staff (email,name,password_hash,created) VALUES (?,?,?,?)').run(email, name, hashPassword(pw), new Date().toISOString())
res.status(201).json({ ok: true })
})
app.delete('/api/staff/team/:id', requireStaff, (req, res) => {
if (Number(req.params.id) === req.staff.id) return res.status(400).json({ error: "You can't remove yourself." })
db.prepare('DELETE FROM sessions WHERE staff_id=?').run(req.params.id)
db.prepare('DELETE FROM staff WHERE id=?').run(req.params.id)
res.json({ ok: true })
})
app.use('/api', (_req, res) => res.status(404).json({ error: 'Not found.' }))
// ---------- First staff member ----------
if (db.prepare('SELECT COUNT(*) AS n FROM staff').get().n === 0) {
const { ADMIN_EMAIL, ADMIN_PASSWORD } = process.env
if (ADMIN_EMAIL && ADMIN_PASSWORD && ADMIN_PASSWORD.length >= 10) {
db.prepare('INSERT INTO staff (email,name,password_hash,created) VALUES (?,?,?,?)').run(ADMIN_EMAIL.toLowerCase(), 'Admin', hashPassword(ADMIN_PASSWORD), new Date().toISOString())
console.log(`Created first staff login: ${ADMIN_EMAIL}`)
} else console.warn('No staff yet. Set ADMIN_EMAIL and ADMIN_PASSWORD (10+ characters) and restart.')
}
if (!emailConfigured) console.warn('Email not configured (SMTP_HOST/SMTP_USER/SMTP_PASS). Tickets are saved but not emailed.')
// ---------- Serve the website (production) ----------
const dist = join(dirname(fileURLToPath(import.meta.url)), '..', 'dist')
if (existsSync(dist)) app.use(express.static(dist))
const port = Number(process.env.PORT || 3001)
app.listen(port, () => console.log(`HelpDesk server on http://localhost:${port}`))
+25
View File
@@ -0,0 +1,25 @@
import nodemailer from 'nodemailer'
const { SMTP_HOST, SMTP_PORT, SMTP_USER, SMTP_PASS, TICKET_TO = 'rana.krunal7558@gmail.com' } = process.env
const transporter = SMTP_HOST && SMTP_USER && SMTP_PASS
? nodemailer.createTransport({ host: SMTP_HOST, port: Number(SMTP_PORT || 465), secure: Number(SMTP_PORT || 465) === 465, auth: { user: SMTP_USER, pass: SMTP_PASS } })
: null
export const emailConfigured = !!transporter
export async function sendTicketEmail(t) {
if (!transporter) return false
try {
await transporter.sendMail({
from: SMTP_USER,
to: TICKET_TO,
replyTo: t.email,
subject: `[${t.id}] ${t.topic}: new IT request from ${t.name}`,
text: `Ticket: ${t.id}\nFrom: ${t.name} <${t.email}>\nTopic: ${t.topic}\n\n${t.message}\n`,
})
return true
} catch (e) {
console.error('Email failed:', e.message)
return false
}
}
+165
View File
@@ -0,0 +1,165 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { ArrowRight, Globe, Instagram, Twitter } from 'lucide-react'
import VideoBackground from './VideoBackground'
import FaqList from './Faq'
import ContactForm from './ContactForm'
import type { Faq } from './types'
import Staff from './Staff'
import faqData from './data/faqs.json'
const bundledFaqs = faqData as Faq[]
export default function App() {
const [faqs, setFaqs] = useState<Faq[]>(bundledFaqs)
const [isStaff, setIsStaff] = useState(location.hash.startsWith('#/staff'))
const categories = useMemo(() => Array.from(new Set(faqs.map((f) => f.category))), [faqs])
useEffect(() => {
fetch('/api/faqs').then((r) => (r.ok ? r.json() : Promise.reject())).then(setFaqs).catch(() => {})
const onHash = () => setIsStaff(location.hash.startsWith('#/staff'))
window.addEventListener('hashchange', onHash)
return () => window.removeEventListener('hashchange', onHash)
}, [])
const [query, setQuery] = useState('')
const [category, setCategory] = useState<string | null>(null)
const answersRef = useRef<HTMLElement>(null)
const results = useMemo(() => {
const words = query.toLowerCase().split(/\s+/).filter(Boolean)
return faqs.filter((f) => {
if (category && f.category !== category) return false
const text = `${f.question} ${f.answer} ${f.category}`.toLowerCase()
return words.every((w) => text.includes(w))
})
}, [query, category, faqs])
if (isStaff) return <Staff />
const scrollToAnswers = () => answersRef.current?.scrollIntoView({ behavior: 'smooth' })
return (
<div className="bg-black">
<div className="min-h-screen bg-black overflow-hidden relative flex flex-col">
<VideoBackground />
<nav className="relative z-20 pl-6 pr-6 py-6">
<div className="liquid-glass rounded-full px-6 py-3 flex items-center justify-between max-w-5xl mx-auto">
<div className="flex items-center gap-8">
<div className="flex items-center gap-2 text-white font-semibold text-lg">
<Globe size={24} />
<span>HelpDesk</span>
</div>
<div className="hidden md:flex items-center gap-8">
{[
['Topics', '#answers'],
['Search', '#top'],
['Contact', '#contact'],
].map(([label, href]) => (
<a key={label} href={href} className="text-white/80 hover:text-white transition-colors text-sm font-medium">
{label}
</a>
))}
</div>
</div>
<div className="flex items-center gap-4">
<a href="#contact" className="text-white text-sm font-medium">Contact IT</a>
<a href="#/staff" className="liquid-glass rounded-full px-6 py-2 text-white text-sm font-medium">Staff login</a>
</div>
</div>
</nav>
<div
id="top"
className="relative z-10 flex-1 flex flex-col items-center justify-center px-6 py-12 text-center -translate-y-[20%]"
>
<h1
className="text-5xl md:text-6xl lg:text-7xl text-white mb-8 tracking-tight whitespace-nowrap"
style={{ fontFamily: "'Instrument Serif', serif" }}
>
IT help, <em>made simple</em>
</h1>
<div className="max-w-xl w-full space-y-4">
<form
className="liquid-glass rounded-full pl-6 pr-2 py-2 flex items-center gap-3"
onSubmit={(e) => {
e.preventDefault()
scrollToAnswers()
}}
>
<input
type="text"
value={query}
maxLength={200}
onChange={(e) => setQuery(e.target.value)}
placeholder="Describe your problem"
aria-label="Search IT help"
className="bg-transparent outline-none flex-1 text-white placeholder:text-white/40 text-base"
/>
<button type="submit" aria-label="Search" className="bg-white rounded-full p-3 text-black">
<ArrowRight size={20} />
</button>
</form>
<p className="text-white text-sm leading-relaxed px-4">
Locked out? Wi-Fi down? Printer acting up? Search {faqs.length} plain-English answers to the most common IT problems.
</p>
<div className="flex justify-center">
<button
onClick={scrollToAnswers}
className="liquid-glass rounded-full px-8 py-3 text-white text-sm font-medium hover:bg-white/5 transition-colors"
>
Browse all topics
</button>
</div>
</div>
</div>
<div className="relative z-10 flex justify-center gap-4 pb-12">
{[
{ Icon: Instagram, label: 'Instagram' },
{ Icon: Twitter, label: 'Twitter' },
{ Icon: Globe, label: 'Website' },
].map(({ Icon, label }) => (
<button
key={label}
aria-label={label}
className="liquid-glass rounded-full p-4 text-white/80 hover:text-white hover:bg-white/5 transition-all"
>
<Icon size={20} />
</button>
))}
</div>
</div>
<section id="answers" ref={answersRef} className="max-w-3xl mx-auto px-6 py-20">
<h2 className="text-4xl text-white mb-2" style={{ fontFamily: "'Instrument Serif', serif" }}>
Answers
</h2>
<p className="text-white/60 text-sm mb-6" aria-live="polite">
Showing {results.length} of {faqs.length}
</p>
<div className="flex flex-wrap gap-2 mb-8">
{[null, ...categories].map((c) => (
<button
key={c ?? 'all'}
onClick={() => setCategory(c)}
aria-pressed={category === c}
className={`liquid-glass rounded-full px-4 py-2 text-sm transition-colors ${
category === c ? 'bg-white/20 text-white' : 'text-white/70 hover:text-white hover:bg-white/5'
}`}
>
{c ?? 'All'}
</button>
))}
</div>
<FaqList items={results} />
</section>
<ContactForm topics={categories} />
<footer id="about" className="max-w-3xl mx-auto px-6 pb-16 text-center text-white/50 text-sm">
General guidance only. For account-specific problems, contact your organisation's IT service desk.
</footer>
</div>
)
}
+80
View File
@@ -0,0 +1,80 @@
import { useState } from 'react'
import { Send } from 'lucide-react'
const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const inputCls = 'w-full bg-transparent outline-none text-white placeholder:text-white/40 text-base'
export default function ContactForm({ topics }: { topics: string[] }) {
const [form, setForm] = useState({ name: '', email: '', topic: topics[0] ?? '', message: '' })
const [errors, setErrors] = useState<Record<string, string>>({})
const [ticketId, setTicketId] = useState<string | null>(null)
const [sending, setSending] = useState(false)
const [serverError, setServerError] = useState('')
const set = (k: keyof typeof form) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) =>
setForm({ ...form, [k]: e.target.value })
const submit = async (e: React.FormEvent) => {
e.preventDefault()
const errs: Record<string, string> = {}
if (!form.name.trim()) errs.name = 'Please enter your name.'
if (!EMAIL_RE.test(form.email.trim())) errs.email = 'Please enter a valid email.'
if (form.message.trim().length < 10) errs.message = 'Please describe the problem (at least 10 characters).'
setErrors(errs)
setServerError('')
if (Object.keys(errs).length) return
setSending(true)
try {
const res = await fetch('/api/tickets', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(form) })
const data = await res.json().catch(() => ({}))
if (!res.ok) throw new Error(data.error || 'Something went wrong. Please try again.')
setTicketId(data.id)
setForm({ name: '', email: '', topic: topics[0] ?? '', message: '' })
} catch (err) {
setServerError(err instanceof Error ? err.message : 'Could not reach the server.')
} finally {
setSending(false)
}
}
const field = 'liquid-glass rounded-3xl px-6 py-4'
const err = (k: string) => errors[k] && <p role="alert" className="text-red-300 text-sm mt-1 px-2">{errors[k]}</p>
return (
<section id="contact" className="max-w-3xl mx-auto px-6 pb-20">
<h2 className="text-4xl text-white mb-2" style={{ fontFamily: "'Instrument Serif', serif" }}>Contact IT</h2>
<p className="text-white/60 text-sm mb-6">Can't find your answer? Tell us what's wrong.</p>
{ticketId ? (
<div className="liquid-glass rounded-3xl p-8 text-white" role="status">
<p className="text-xl mb-2">Request sent. Your ticket number is <strong>{ticketId}</strong>.</p>
<p className="text-white/70 text-sm mb-4">Our IT team has been notified. Keep this number if you follow up.</p>
<button onClick={() => setTicketId(null)} className="liquid-glass rounded-full px-6 py-2 text-sm hover:bg-white/5">Send another</button>
</div>
) : (
<form onSubmit={submit} noValidate className="space-y-3">
<div>
<div className={field}><input className={inputCls} placeholder="Your name" aria-label="Your name" maxLength={100} value={form.name} onChange={set('name')} /></div>
{err('name')}
</div>
<div>
<div className={field}><input className={inputCls} type="email" placeholder="Your email" aria-label="Your email" maxLength={200} value={form.email} onChange={set('email')} /></div>
{err('email')}
</div>
<div className={field}>
<select className={`${inputCls} [&>option]:text-black`} aria-label="Topic" value={form.topic} onChange={set('topic')}>
{topics.map((t) => <option key={t}>{t}</option>)}
</select>
</div>
<div>
<div className={field}><textarea className={`${inputCls} resize-none`} rows={5} placeholder="What's the problem?" aria-label="Problem description" maxLength={2000} value={form.message} onChange={set('message')} /></div>
{err('message')}
</div>
{serverError && <p role="alert" className="text-red-300 text-sm px-2">{serverError}</p>}
<button type="submit" disabled={sending} className="bg-white text-black rounded-full px-8 py-3 text-sm font-medium inline-flex items-center gap-2 disabled:opacity-60">
<Send size={16} /> {sending ? 'Sending...' : 'Send request'}
</button>
</form>
)}
</section>
)
}
+120
View File
@@ -0,0 +1,120 @@
import { useEffect, useState } from 'react'
import { Check, ExternalLink, Link2, SearchX, ThumbsDown, ThumbsUp } from 'lucide-react'
import type { Faq } from './types'
import { load, save } from './storage'
type Votes = Record<number, 'up' | 'down'>
function safeUrl(url: string): string | null {
try {
const u = new URL(url)
return u.protocol === 'https:' || u.protocol === 'http:' ? u.href : null
} catch {
return null
}
}
function FaqCard({ f, forceOpen, vote, onVote }: { f: Faq; forceOpen: boolean; vote?: 'up' | 'down'; onVote: (v: 'up' | 'down') => void }) {
const [copied, setCopied] = useState(false)
const href = f.link ? safeUrl(f.link) : null
const copyLink = async () => {
const url = `${location.origin}${location.pathname}#faq-${f.id}`
try {
await navigator.clipboard.writeText(url)
setCopied(true)
window.setTimeout(() => setCopied(false), 2000)
} catch {
location.hash = `faq-${f.id}`
}
}
const voteBtn = (v: 'up' | 'down', label: string, Icon: typeof ThumbsUp) => (
<button
onClick={() => onVote(v)}
aria-pressed={vote === v}
className={`liquid-glass rounded-full px-4 py-2 inline-flex items-center gap-2 text-sm transition-colors ${
vote === v ? 'bg-white/20 text-white' : 'text-white/70 hover:text-white hover:bg-white/5'
}`}
>
<Icon size={14} /> {label}
</button>
)
return (
<li id={`faq-${f.id}`} className="scroll-mt-6">
<details className="liquid-glass rounded-3xl group" open={forceOpen || undefined}>
<summary className="cursor-pointer list-none px-6 py-5 flex items-start justify-between gap-4 text-white">
<span>
<span className="block text-xs uppercase tracking-wider text-white/50 mb-1">{f.category}</span>
<span className="text-lg">{f.question}</span>
</span>
<span className="text-white/60 transition-transform group-open:rotate-45 text-2xl leading-none">+</span>
</summary>
<div className="px-6 pb-6 text-white/80 text-sm leading-relaxed">
<p>{f.answer}</p>
{href && (
<a href={href} target="_blank" rel="noopener noreferrer" className="inline-flex items-center gap-2 mt-4 text-white hover:underline">
{f.linkLabel || 'Official guide'} <ExternalLink size={14} />
</a>
)}
<div className="mt-5 flex flex-wrap items-center gap-2">
<span className="text-white/50 mr-1">Was this helpful?</span>
{voteBtn('up', 'Yes', ThumbsUp)}
{voteBtn('down', 'No', ThumbsDown)}
<button
onClick={copyLink}
className="liquid-glass rounded-full px-4 py-2 inline-flex items-center gap-2 text-sm text-white/70 hover:text-white hover:bg-white/5 transition-colors ml-auto"
>
{copied ? <Check size={14} /> : <Link2 size={14} />} {copied ? 'Link copied' : 'Copy link'}
</button>
</div>
{vote === 'down' && (
<p className="mt-3 text-white/60">
Sorry about that. <a href="#contact" className="text-white underline">Contact IT</a> and we'll help directly.
</p>
)}
</div>
</details>
</li>
)
}
export default function FaqList({ items }: { items: Faq[] }) {
const [votes, setVotes] = useState<Votes>(() => load<Votes>('faq-votes', {}))
const [hashId, setHashId] = useState<number | null>(null)
useEffect(() => {
const read = () => {
const m = /^#faq-(\d+)$/.exec(location.hash)
setHashId(m ? Number(m[1]) : null)
if (m) window.setTimeout(() => document.getElementById(`faq-${m[1]}`)?.scrollIntoView({ behavior: 'smooth' }), 50)
}
read()
window.addEventListener('hashchange', read)
return () => window.removeEventListener('hashchange', read)
}, [])
const onVote = (id: number, v: 'up' | 'down') => {
const next = { ...votes, [id]: v }
setVotes(next)
save('faq-votes', next)
fetch('/api/votes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ faqId: id, vote: v }) }).catch(() => {})
}
if (items.length === 0) {
return (
<div className="liquid-glass rounded-3xl p-10 text-center text-white/70">
<SearchX className="mx-auto mb-3" size={28} />
<p>No answers found. Try different words, or <a href="#contact" className="text-white underline">contact IT</a>.</p>
</div>
)
}
return (
<ul className="space-y-3">
{items.map((f) => (
<FaqCard key={f.id} f={f} forceOpen={hashId === f.id} vote={votes[f.id]} onVote={(v) => onVote(f.id, v)} />
))}
</ul>
)
}
+175
View File
@@ -0,0 +1,175 @@
import { useCallback, useEffect, useState } from 'react'
import { LogOut } from 'lucide-react'
interface Ticket { id: string; name: string; email: string; topic: string; message: string; status: string; emailed: number; created: string }
interface StaffFaq { id: number; category: string; question: string; answer: string; link: string; linkLabel: string; up: number; down: number }
interface Member { id: number; email: string; name: string }
type Tab = 'tickets' | 'faqs' | 'team'
async function api<T = unknown>(path: string, method = 'GET', body?: unknown): Promise<T> {
const res = await fetch(`/api${path}`, { method, headers: body ? { 'Content-Type': 'application/json' } : undefined, body: body ? JSON.stringify(body) : undefined })
const data = await res.json().catch(() => ({}))
if (!res.ok) throw Object.assign(new Error(data.error || 'Request failed'), { status: res.status })
return data as T
}
const box = 'liquid-glass rounded-3xl p-6 text-white'
const input = 'w-full bg-white/5 rounded-2xl px-4 py-3 text-white placeholder:text-white/40 outline-none'
const btn = 'liquid-glass rounded-full px-5 py-2 text-sm text-white hover:bg-white/5 transition-colors'
function Login({ onDone }: { onDone: () => void }) {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const submit = async (e: React.FormEvent) => {
e.preventDefault()
try { await api('/login', 'POST', { email, password }); onDone() } catch (err) { setError((err as Error).message) }
}
return (
<form onSubmit={submit} className={`${box} max-w-sm mx-auto space-y-3`}>
<h1 className="text-3xl mb-2" style={{ fontFamily: "'Instrument Serif', serif" }}>Staff login</h1>
<input className={input} type="email" placeholder="Email" aria-label="Email" value={email} onChange={(e) => setEmail(e.target.value)} autoComplete="username" />
<input className={input} type="password" placeholder="Password" aria-label="Password" value={password} onChange={(e) => setPassword(e.target.value)} autoComplete="current-password" />
{error && <p role="alert" className="text-red-300 text-sm">{error}</p>}
<button type="submit" className="bg-white text-black rounded-full px-6 py-2 text-sm font-medium">Log in</button>
</form>
)
}
function Tickets() {
const [rows, setRows] = useState<Ticket[]>([])
const load = useCallback(() => api<Ticket[]>('/staff/tickets').then(setRows), [])
useEffect(() => { load() }, [load])
const setStatus = async (id: string, status: string) => { await api(`/staff/tickets/${id}`, 'PATCH', { status }); load() }
if (!rows.length) return <p className="text-white/60">No tickets yet.</p>
return (
<ul className="space-y-3">
{rows.map((t) => (
<li key={t.id} className={box}>
<div className="flex flex-wrap justify-between gap-2 text-sm text-white/60">
<span>{t.id} · {t.topic} · {new Date(t.created).toLocaleString()}</span>
<span>{t.emailed ? 'emailed' : 'not emailed'}</span>
</div>
<p className="mt-2 whitespace-pre-wrap">{t.message}</p>
<p className="mt-2 text-sm text-white/70">{t.name} · <a className="underline" href={`mailto:${encodeURIComponent(t.email)}`}>{t.email}</a></p>
<select aria-label="Status" value={t.status} onChange={(e) => setStatus(t.id, e.target.value)} className="mt-3 bg-white/10 rounded-full px-4 py-2 text-sm [&>option]:text-black">
<option value="open">Open</option><option value="in_progress">In progress</option><option value="closed">Closed</option>
</select>
</li>
))}
</ul>
)
}
const emptyFaq = { category: '', question: '', answer: '', link: '', linkLabel: '' }
function Faqs() {
const [rows, setRows] = useState<StaffFaq[]>([])
const [editing, setEditing] = useState<(typeof emptyFaq & { id?: number }) | null>(null)
const [error, setError] = useState('')
const load = useCallback(() => api<StaffFaq[]>('/staff/faqs').then(setRows), [])
useEffect(() => { load() }, [load])
const save = async (e: React.FormEvent) => {
e.preventDefault()
if (!editing) return
try {
if (editing.id) await api(`/staff/faqs/${editing.id}`, 'PUT', editing)
else await api('/staff/faqs', 'POST', editing)
setEditing(null); setError(''); load()
} catch (err) { setError((err as Error).message) }
}
const remove = async (f: StaffFaq) => { if (confirm(`Delete "${f.question}"?`)) { await api(`/staff/faqs/${f.id}`, 'DELETE'); load() } }
const set = (k: keyof typeof emptyFaq) => (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => editing && setEditing({ ...editing, [k]: e.target.value })
return (
<div className="space-y-4">
{editing ? (
<form onSubmit={save} className={`${box} space-y-3`}>
<input className={input} placeholder="Category" aria-label="Category" value={editing.category} onChange={set('category')} />
<input className={input} placeholder="Question" aria-label="Question" value={editing.question} onChange={set('question')} />
<textarea className={input} rows={5} placeholder="Answer" aria-label="Answer" value={editing.answer} onChange={set('answer')} />
<input className={input} placeholder="Link (optional, https://...)" aria-label="Link" value={editing.link} onChange={set('link')} />
<input className={input} placeholder="Link label (optional)" aria-label="Link label" value={editing.linkLabel} onChange={set('linkLabel')} />
{error && <p role="alert" className="text-red-300 text-sm">{error}</p>}
<div className="flex gap-2"><button type="submit" className="bg-white text-black rounded-full px-6 py-2 text-sm font-medium">Save</button><button type="button" className={btn} onClick={() => { setEditing(null); setError('') }}>Cancel</button></div>
</form>
) : <button className={btn} onClick={() => setEditing({ ...emptyFaq })}>+ Add FAQ</button>}
<ul className="space-y-2">
{rows.map((f) => (
<li key={f.id} className={`${box} flex flex-wrap items-center justify-between gap-3 !py-4`}>
<span><span className="block text-xs text-white/50">{f.category}</span>{f.question}</span>
<span className="flex items-center gap-3 text-sm text-white/70">
👍 {f.up} 👎 {f.down}
<button className={btn} onClick={() => setEditing(f)}>Edit</button>
<button className={btn} onClick={() => remove(f)}>Delete</button>
</span>
</li>
))}
</ul>
</div>
)
}
function Team({ me }: { me: string }) {
const [rows, setRows] = useState<Member[]>([])
const [f, setF] = useState({ name: '', email: '', password: '' })
const [error, setError] = useState('')
const load = useCallback(() => api<Member[]>('/staff/team').then(setRows), [])
useEffect(() => { load() }, [load])
const add = async (e: React.FormEvent) => {
e.preventDefault()
try { await api('/staff/team', 'POST', f); setF({ name: '', email: '', password: '' }); setError(''); load() } catch (err) { setError((err as Error).message) }
}
const remove = async (m: Member) => { if (confirm(`Remove ${m.name}?`)) { try { await api(`/staff/team/${m.id}`, 'DELETE'); load() } catch (err) { setError((err as Error).message) } } }
return (
<div className="space-y-4">
<ul className="space-y-2">
{rows.map((m) => (
<li key={m.id} className={`${box} flex items-center justify-between !py-4`}>
<span>{m.name} <span className="text-white/60 text-sm">· {m.email}</span></span>
{m.email !== me && <button className={btn} onClick={() => remove(m)}>Remove</button>}
</li>
))}
</ul>
<form onSubmit={add} className={`${box} space-y-3`}>
<h2 className="text-xl">Add a team member</h2>
<input className={input} placeholder="Name" aria-label="Name" value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} />
<input className={input} type="email" placeholder="Email" aria-label="Email" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} />
<input className={input} type="password" placeholder="Temporary password (10+ characters)" aria-label="Password" value={f.password} onChange={(e) => setF({ ...f, password: e.target.value })} autoComplete="new-password" />
{error && <p role="alert" className="text-red-300 text-sm">{error}</p>}
<button type="submit" className="bg-white text-black rounded-full px-6 py-2 text-sm font-medium">Add</button>
</form>
</div>
)
}
export default function Staff() {
const [me, setMe] = useState<{ name: string; email: string } | null | undefined>(undefined)
const [emailOk, setEmailOk] = useState(true)
const [tab, setTab] = useState<Tab>('tickets')
const check = useCallback(() => {
api<{ name: string; email: string }>('/me').then((m) => { setMe(m); api<{ emailConfigured: boolean }>('/staff/status').then((s) => setEmailOk(s.emailConfigured)) }).catch(() => setMe(null))
}, [])
useEffect(() => { check() }, [check])
const logout = async () => { await api('/logout', 'POST'); setMe(null) }
return (
<div className="min-h-screen bg-black text-white px-6 py-10">
<div className="max-w-3xl mx-auto">
<div className="flex items-center justify-between mb-8">
<a href="#" className="text-white/70 hover:text-white text-sm">← Back to site</a>
{me && <button onClick={logout} className={`${btn} inline-flex items-center gap-2`}><LogOut size={14} /> Log out ({me.name})</button>}
</div>
{me === undefined ? <p className="text-white/60">Loading...</p> : me === null ? <Login onDone={check} /> : (
<>
{!emailOk && <p className="mb-4 text-amber-300 text-sm">Email is not set up on the server yet, so new tickets are saved here but not emailed.</p>}
<div className="flex gap-2 mb-6">
{(['tickets', 'faqs', 'team'] as Tab[]).map((t) => (
<button key={t} onClick={() => setTab(t)} aria-pressed={tab === t} className={`${btn} capitalize ${tab === t ? 'bg-white/20' : ''}`}>{t === 'faqs' ? 'FAQs' : t}</button>
))}
</div>
{tab === 'tickets' && <Tickets />}{tab === 'faqs' && <Faqs />}{tab === 'team' && <Team me={me.email} />}
</>
)}
</div>
</div>
)
}
+66
View File
@@ -0,0 +1,66 @@
import { useCallback, useEffect, useRef } from 'react'
const VIDEO_URL =
'https://d8j0ntlcm91z4.cloudfront.net/user_38xzZboKViGWJOttwIXH07lWA1P/hf_20260328_115001_bcdaa3b4-03de-47e7-ad63-ae3e392c32d4.mp4'
const FADE_MS = 500
const FADE_OUT_REMAINING = 0.55
export default function VideoBackground() {
const videoRef = useRef<HTMLVideoElement>(null)
const rafRef = useRef<number | null>(null)
const fadingOutRef = useRef(false)
const fadeTo = useCallback((target: number) => {
const video = videoRef.current
if (!video) return
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
const startOpacity = parseFloat(video.style.opacity || '0')
const startTime = performance.now()
const step = (now: number) => {
const t = Math.min((now - startTime) / FADE_MS, 1)
video.style.opacity = String(startOpacity + (target - startOpacity) * t)
rafRef.current = t < 1 ? requestAnimationFrame(step) : null
}
rafRef.current = requestAnimationFrame(step)
}, [])
useEffect(() => () => {
if (rafRef.current !== null) cancelAnimationFrame(rafRef.current)
}, [])
const handleTimeUpdate = () => {
const video = videoRef.current
if (!video || !video.duration || fadingOutRef.current) return
if (video.duration - video.currentTime <= FADE_OUT_REMAINING) {
fadingOutRef.current = true
fadeTo(0)
}
}
const handleEnded = () => {
const video = videoRef.current
if (!video) return
video.style.opacity = '0'
window.setTimeout(() => {
video.currentTime = 0
void video.play().catch(() => {})
fadingOutRef.current = false
fadeTo(1)
}, 100)
}
return (
<video
ref={videoRef}
src={VIDEO_URL}
autoPlay
muted
playsInline
style={{ opacity: 0 }}
className="absolute inset-0 w-full h-full object-cover translate-y-[17%]"
onLoadedData={() => fadeTo(1)}
onTimeUpdate={handleTimeUpdate}
onEnded={handleEnded}
/>
)
}
+698
View File
@@ -0,0 +1,698 @@
[
{
"id": 1,
"category": "Access & logins",
"question": "I forgot my password",
"answer": "Most organisations have a self-service reset link on the sign-in page, usually 'Forgot password' or 'Can't access your account'. You'll be asked to verify your identity, normally with a code sent to a backup email or phone number you registered earlier. If there's no self-service option, or verification fails, your IT service desk can reset it after confirming your identity another way. Keep any backup codes you were given when MFA was set up somewhere safe, they're often the fastest way back in.",
"link": "https://support.microsoft.com/en-us/account-billing/how-to-reset-your-microsoft-account-password-eff4f067-5042-c1a3-fe72-b04d60556c37",
"linkLabel": "Microsoft: reset your password"
},
{
"id": 2,
"category": "Access & logins",
"question": "I'm locked out after too many failed attempts",
"answer": "This is a security feature, not a fault, it stops someone guessing your password repeatedly. Most systems clear the lockout automatically after a set time, often 15 to 30 minutes, so waiting is sometimes the fastest fix. If it's urgent, or the lockout doesn't clear itself, your IT service desk can unlock the account manually once they've verified it's really you.",
"link": "",
"linkLabel": ""
},
{
"id": 3,
"category": "Access & logins",
"question": "My multi-factor login (authenticator app) isn't working",
"answer": "If you've lost your phone or the authenticator app stopped generating valid codes, try a saved backup code first, most systems issue a set of one-time codes when MFA is first set up. If you don't have one, contact IT to re-register your MFA device, this normally requires an identity check (staff or student ID, or a manager confirming it's you) since it's effectively resetting your account security.",
"link": "",
"linkLabel": ""
},
{
"id": 4,
"category": "Access & logins",
"question": "My account is disabled or expired after returning from leave",
"answer": "Accounts are sometimes automatically disabled after a period of inactivity, or a leave period that wasn't flagged as 'returning' in the system. This is an account status issue in the directory (Active Directory or similar), not a password problem, ask IT to check whether the account itself is disabled or expired rather than resetting the password again.",
"link": "",
"linkLabel": ""
},
{
"id": 5,
"category": "Access & logins",
"question": "Single sign-on (SSO) keeps redirecting in a loop",
"answer": "An SSO loop, bouncing between your organisation's login page and the app without ever landing you in, is usually a cookie or session problem rather than your password. Try a private or incognito browser window first, if that works cleanly, clear cookies for your organisation's login domain. If it still loops, the connection between your identity provider and that specific app may need IT to check its configuration.",
"link": "",
"linkLabel": ""
},
{
"id": 6,
"category": "Access & logins",
"question": "A guest or contractor account isn't working",
"answer": "Guest and contractor accounts usually go through a separate approval process, often needing an internal sponsor, and typically expire automatically after a set period for security. If a guest account stops working, check with the person who sponsored the access first, then IT if they confirm it should still be active.",
"link": "",
"linkLabel": ""
},
{
"id": 7,
"category": "Access & logins",
"question": "My security questions aren't being accepted during recovery",
"answer": "Recovery answers need to match exactly what was originally entered, including capitalisation in some systems, so a common cause is simply misremembering the exact wording. If you've genuinely forgotten the answers, look for a 'try another way' option instead of repeatedly guessing, most recovery tools offer an alternative path such as an email or SMS code.",
"link": "",
"linkLabel": ""
},
{
"id": 8,
"category": "Access & logins",
"question": "A new password keeps being rejected as too weak or previously used",
"answer": "Organisations enforce password rules (minimum length, a mix of character types, and often a block on reusing recent passwords) to reduce the risk of a compromised account. A longer passphrase, three or four random unrelated words plus a number and symbol, is both stronger and easier to remember than a short complex one, and tends to pass these checks more easily. Avoid names, birthdays or the organisation's own name.",
"link": "",
"linkLabel": ""
},
{
"id": 9,
"category": "Network & wifi",
"question": "My wifi keeps dropping",
"answer": "Try moving closer to the access point, restarting your device's wifi, and checking if other devices nearby have the same problem, that tells you whether it's your device or the network. On a corporate or school network with certificate-based login (802.1x), an expired certificate is a common cause, IT can reissue it. A network adapter driver that's out of date after a Windows update is another very common cause worth ruling out.",
"link": "https://support.microsoft.com/en-us/windows/fix-wi-fi-connection-issues-in-windows-9424a1f7-6a3b-65a6-4d78-7f07eee84d2c",
"linkLabel": "Microsoft: fix Wi-Fi connection issues"
},
{
"id": 10,
"category": "Network & wifi",
"question": "The VPN won't connect",
"answer": "Check your normal internet connection works first. Then fully close and reopen the VPN app rather than just reconnecting, a half-open session is a common cause. Public wifi (cafes, hotels) sometimes blocks VPN traffic entirely until you've accepted its own login page in a browser first.",
"link": "",
"linkLabel": ""
},
{
"id": 11,
"category": "Network & wifi",
"question": "I can't reach a shared drive or folder",
"answer": "Confirm you're connected to the VPN or office network, shared drives usually don't work from the open internet. If it still fails, the folder permissions may have changed, ask IT to check your access rather than repeatedly trying to reconnect.",
"link": "",
"linkLabel": ""
},
{
"id": 12,
"category": "Network & wifi",
"question": "I'm getting an IP conflict or 'limited connectivity' message",
"answer": "This usually means your device didn't get a valid address from the network's DHCP server, often after being moved between networks or waking from sleep. Disconnecting and reconnecting to wifi, or running `ipconfig /release` then `ipconfig /renew` on Windows, fixes most cases. If it keeps happening on the same device, report it, it can indicate a DHCP address pool running low.",
"link": "",
"linkLabel": ""
},
{
"id": 13,
"category": "Network & wifi",
"question": "A captive portal (hotel or cafe wifi login page) won't load",
"answer": "If the login page doesn't appear automatically, try opening a plain, non-secure website, some networks only trigger the portal on unencrypted traffic. A corporate VPN client often blocks the portal from appearing at all, disconnect the VPN first, log in to the wifi, then reconnect the VPN.",
"link": "",
"linkLabel": ""
},
{
"id": 14,
"category": "Network & wifi",
"question": "Wifi shows connected but the internet is very slow",
"answer": "Being 'connected' only confirms a local network link, not that everything beyond it is fast. Run a speed test, then check whether it's isolated to one device (a device or driver issue) or affects everyone nearby, which usually points to the access point, the internet link itself, or a bandwidth-heavy device worth reporting to IT.",
"link": "",
"linkLabel": ""
},
{
"id": 15,
"category": "Network & wifi",
"question": "A mapped network drive keeps failing after a password change",
"answer": "A mapped drive often stores the old credentials separately, so it can keep failing silently even though you can log in to everything else fine. Disconnect the mapped drive and reconnect it fresh, entering the new password when prompted, rather than relying on the saved ones.",
"link": "",
"linkLabel": ""
},
{
"id": 16,
"category": "Network & wifi",
"question": "A Bluetooth device won't pair",
"answer": "Turn Bluetooth off and on again on both devices, and make sure the device is actually in pairing mode. If it was previously paired with a different computer, 'forget' or remove the old pairing on both ends first, most Bluetooth accessories only hold a limited number of paired connections at once.",
"link": "",
"linkLabel": ""
},
{
"id": 17,
"category": "Hardware",
"question": "The printer won't print",
"answer": "Check it's powered on, has paper and toner, and that you picked the right printer name in the print dialog. Network printers can show as 'offline' if they've lost wifi, turning them off and on again often fixes this.",
"link": "",
"linkLabel": ""
},
{
"id": 18,
"category": "Hardware",
"question": "An external monitor isn't detected",
"answer": "Check the cable is firmly in at both ends and try a different port or cable if you have one. Then open your display settings and click 'Detect'. A driver or graphics update can also help on older laptops.",
"link": "",
"linkLabel": ""
},
{
"id": 19,
"category": "Hardware",
"question": "A USB device isn't recognised",
"answer": "Try a different USB port, and a different cable if it's detachable. If it still doesn't show up, check Device Manager (Windows) or System Report (Mac) for a warning icon next to the device.",
"link": "",
"linkLabel": ""
},
{
"id": 20,
"category": "Hardware",
"question": "A laptop won't turn on at all",
"answer": "First rule out a flat battery, plug in the charger, check for a charging light, then leave it 15 to 30 minutes before trying again, some laptops won't start with a completely dead battery even while charging. If there's a charging light but still nothing on screen, try an external monitor, that tells you whether it's a screen problem or the laptop genuinely isn't starting.",
"link": "",
"linkLabel": ""
},
{
"id": 21,
"category": "Hardware",
"question": "The battery is draining fast or won't charge",
"answer": "Test the charger and cable on a different device or outlet first, to rule out a faulty charger rather than the laptop itself. Battery health does genuinely fade over 2 to 4 years of daily use, if the laptop is older and the drop was gradual, a battery replacement through IT asset management is often the real fix rather than a software setting.",
"link": "",
"linkLabel": ""
},
{
"id": 22,
"category": "Hardware",
"question": "The keyboard or trackpad isn't responding",
"answer": "Restart the device first, a stuck driver is a common and simple cause. If only specific keys are affected, check for anything physically stuck underneath, common after spills or crumbs, and try an external USB keyboard or mouse to confirm whether it's the built-in hardware or a wider fault.",
"link": "",
"linkLabel": ""
},
{
"id": 23,
"category": "Hardware",
"question": "A docking station isn't detecting monitors or peripherals",
"answer": "Confirm the dock itself has power, many need their own power cable, not just the laptop cable, and try unplugging the laptop from the dock and reconnecting it firmly. Docks that connect via USB-C or Thunderbolt can be picky about cable quality, swap the cable before assuming the dock has failed.",
"link": "",
"linkLabel": ""
},
{
"id": 24,
"category": "Hardware",
"question": "The webcam isn't detected by any app",
"answer": "Some laptops have a physical privacy shutter or a function-key toggle that disables the camera entirely, check for both before assuming it's broken. Checking Device Manager (Windows) or System Information (Mac) shows whether the operating system sees the camera at all, if it's not listed there, it's a driver or hardware fault rather than an app setting.",
"link": "",
"linkLabel": ""
},
{
"id": 25,
"category": "Software & apps",
"question": "My computer is running very slow",
"answer": "Restart it first, this clears a surprising number of slowdowns. After that, check how much storage is free and close programs you're not using that start automatically. If it's still slow, let IT know, it could be a background update or a bigger issue.",
"link": "",
"linkLabel": ""
},
{
"id": 26,
"category": "Software & apps",
"question": "An app keeps crashing or won't open",
"answer": "Close and reopen it, then restart your computer if that doesn't help. Check whether an update is available. If it's an approved work app that IT installed for you, they may need to reinstall it rather than you doing it yourself.",
"link": "",
"linkLabel": ""
},
{
"id": 27,
"category": "Software & apps",
"question": "My email isn't syncing or I'm missing messages",
"answer": "Check your internet connection and your junk or spam folder. Also check your mailbox isn't full, a full mailbox silently stops receiving mail in some systems. Outlook and Gmail both have a 'repair account' option worth trying.",
"link": "",
"linkLabel": ""
},
{
"id": 28,
"category": "Software & apps",
"question": "My camera isn't working in Microsoft Teams",
"answer": "Close other apps that might already be using the camera (like Zoom or FaceTime), unplug and reconnect it if it's external, and restart the device. Make a test call from Teams' device settings to check camera, mic and speaker together in one go.",
"link": "https://support.microsoft.com/en-US/teams/meetings/my-camera-isn-t-working-in-microsoft-teams",
"linkLabel": "Microsoft: Teams camera troubleshooting"
},
{
"id": 29,
"category": "Software & apps",
"question": "Zoom audio or video isn't working",
"answer": "Check the correct microphone, speaker and camera are selected inside Zoom's own settings, not just that your device isn't muted at the operating system level. If it's a browser-based meeting, the browser also needs camera and microphone permission granted specifically for that site.",
"link": "https://support.zoom.us/",
"linkLabel": "Zoom support"
},
{
"id": 30,
"category": "Software & apps",
"question": "Windows Update is stuck or won't install",
"answer": "Restart the device once and let it sit for at least 30 minutes, some updates genuinely take a long time on the 'working on updates' screen, and interrupting them can cause more problems than waiting. If it's still stuck well beyond that, or fails repeatedly, note the exact error code for IT, the built-in update troubleshooter resolves a lot of common stuck updates on its own.",
"link": "",
"linkLabel": ""
},
{
"id": 31,
"category": "Software & apps",
"question": "Office or Microsoft 365 shows 'unlicensed product' or won't activate",
"answer": "This usually means the app can't confirm your licence with Microsoft's servers, often because you're signed in with the wrong account, or you've been offline too long since the last successful check-in. Sign out and back in with your work or school account specifically, not a personal Microsoft account, and make sure you're online or on VPN when it tries to reactivate.",
"link": "",
"linkLabel": ""
},
{
"id": 32,
"category": "Software & apps",
"question": "'Access denied' or 'permission denied' opening a file",
"answer": "This is almost always a permissions setting on the file or folder itself, not a fault with your computer. Confirm you're opening it from the right location, a synced local copy can behave differently to the shared original, and if you believe you should have access, ask the file's owner or IT to check the permission list rather than trying to force it open.",
"link": "",
"linkLabel": ""
},
{
"id": 33,
"category": "Security",
"question": "I received a suspicious email, is it phishing?",
"answer": "Don't click links or open attachments. Check the sender's actual email address, not just the display name, and look for urgency or requests for passwords or gift cards, common phishing signs. Report it to your IT security team rather than deleting it, they may need to warn others across the organisation.",
"link": "https://www.cyber.gov.au/report-and-recover",
"linkLabel": "ACSC: report a cybercrime (ReportCyber)"
},
{
"id": 34,
"category": "Security",
"question": "My computer crashed or showed a blue screen",
"answer": "Note down any error code or message shown before it restarts, a photo on your phone is fine. Restart the computer. If it happens more than once, that error code is exactly what IT will need to diagnose it.",
"link": "",
"linkLabel": ""
},
{
"id": 35,
"category": "Security",
"question": "I think I've been hit by ransomware",
"answer": "If files suddenly become inaccessible with strange new extensions, or a ransom note appears, disconnect the device from the network immediately (unplug the cable or turn off wifi) without shutting it down, this can stop it spreading before you power off. Don't pay anything and don't try to remove it yourself, contact IT security immediately, this is treated as a priority incident.",
"link": "",
"linkLabel": ""
},
{
"id": 36,
"category": "Security",
"question": "I suspect my account has been compromised",
"answer": "Change your password immediately from a device you trust, and check for any MFA devices, mail forwarding rules, or app connections you don't recognise, attackers often quietly add a forwarding rule or a second MFA device to keep access even after the password changes. Report it to IT security even after you've changed the password, they may need to check for wider impact.",
"link": "",
"linkLabel": ""
},
{
"id": 37,
"category": "Security",
"question": "What actually makes a strong password or passphrase",
"answer": "Length matters more than complexity, three or four random unrelated words make a passphrase that's both stronger and easier to remember than a short complex one. Never reuse a password across personal and work accounts, and use a password manager rather than trying to remember unique passwords for everything, most organisations provide or approve one.",
"link": "",
"linkLabel": ""
},
{
"id": 38,
"category": "Security",
"question": "How to report a data breach or accidental data exposure",
"answer": "If personal or sensitive information was sent to the wrong person, uploaded somewhere public by mistake, or a device holding such data is lost or stolen, report it to IT and your privacy contact as soon as possible. Timing genuinely matters for breach response, and in government and other regulated sectors there can be mandatory notification obligations attached.",
"link": "https://www.cyber.gov.au/report-and-recover",
"linkLabel": "ACSC: report and recover"
},
{
"id": 39,
"category": "Security",
"question": "Windows is asking for a BitLocker recovery key",
"answer": "This usually appears after a hardware or firmware change, like a BIOS update, a new battery, or a changed boot order, that the encryption chip treats as suspicious, it's the protection working as intended, not a sign of a hack. The 48-digit recovery key is normally stored in your organisation's directory (Azure AD/Intune) or was saved separately when the device was set up, IT can retrieve it if you don't have it yourself. Microsoft itself cannot recover a lost key, so if neither you nor IT can locate it, the drive has to be reset.",
"link": "https://support.microsoft.com/en-us/help/4026181",
"linkLabel": "Microsoft: find your BitLocker recovery key"
},
{
"id": 40,
"category": "Security",
"question": "A Mac is asking for a FileVault recovery key",
"answer": "Similar to Windows BitLocker, this appears after certain hardware or firmware changes and is the encryption protecting your data working as designed. The recovery key is usually escrowed with your organisation's MDM (Jamf or similar), IT can retrieve it if it wasn't saved when the device was set up.",
"link": "",
"linkLabel": ""
},
{
"id": 41,
"category": "Security",
"question": "Antivirus or endpoint protection just quarantined a file or blocked something",
"answer": "Don't try to restore or override it yourself, even if you're confident the file is safe, false positives do happen but confirming that is IT security's job, not yours. Report exactly what you were doing and what the alert said, that detail is what determines whether it's a false positive or something needing wider action.",
"link": "",
"linkLabel": ""
},
{
"id": 42,
"category": "Security",
"question": "A USB drive or device is blocked by policy",
"answer": "Many organisations block USB storage devices entirely as a data-loss-prevention measure, this is deliberate policy rather than a fault, and it usually can't be worked around with a different port or drive. If you have a genuine business need to transfer files this way, request an exception through IT rather than trying another device.",
"link": "",
"linkLabel": ""
},
{
"id": 43,
"category": "Sector notes",
"question": "Why are some settings locked on my device?",
"answer": "Government, school and many corporate devices are deliberately locked down for security, this is policy, not a fault. Australian government agencies generally follow the ACSC's Essential Eight security controls, which is why things like installing your own software or changing certain settings are restricted to IT staff.",
"link": "https://www.cyber.gov.au/resources-business-and-government/essential-cybersecurity/essential-eight",
"linkLabel": "ACSC: Essential Eight explained"
},
{
"id": 44,
"category": "Sector notes",
"question": "School: why is a legitimate website or resource blocked?",
"answer": "Australian schools typically apply internet content filtering as required by state and territory education department policy, and manage student devices through a mobile device management (MDM) system. If a legitimate educational site is blocked, that's a filtering rule, not a fault, report it to the school's IT support so they can review or whitelist it rather than trying to work around the filter.",
"link": "",
"linkLabel": ""
},
{
"id": 45,
"category": "Sector notes",
"question": "Government: why can't I install software myself?",
"answer": "Restricting who can install software (application control) is one of the Essential Eight strategies Australian government agencies are expected to implement, it stops unapproved or malicious software running on government devices. If you need software for a work purpose, the usual path is a request to IT for review and installation through an approved, managed process.",
"link": "https://www.cyber.gov.au/resources-business-and-government/essential-cybersecurity/essential-eight",
"linkLabel": "ACSC: Essential Eight explained"
},
{
"id": 46,
"category": "Sector notes",
"question": "Corporate: why can't I do everything on my personal (BYOD) device?",
"answer": "A personal device enrolled for work access (BYOD) is usually only given a limited, contained work profile rather than full management of the whole device, protecting both your personal data and the organisation's. If a work app or file won't open, or copy-paste out of a work app is blocked, that's often a deliberate BYOD policy restriction rather than a technical fault.",
"link": "",
"linkLabel": ""
},
{
"id": 47,
"category": "How IT support works",
"question": "What do Level 1, 2, 3 (and 4) support actually mean?",
"answer": "Level 1 is the frontline help desk, handling common self-service issues like this page's Access, Wifi and Hardware topics, usually resolved in one call or ticket. Level 2 is more technical staff who handle things needing deeper diagnosis, like the Network Hardware topics here. Level 3 is specialist or senior engineers, often involved in design and complex incidents, and Level 4 is the vendor's own support (Cisco TAC, Fortinet support), brought in when the issue is inside the product itself, not the configuration.",
"link": "",
"linkLabel": ""
},
{
"id": 48,
"category": "How IT support works",
"question": "When should something be escalated to the next level?",
"answer": "As a general rule, escalate when the fix needs a permission, tool, or specialist knowledge the current level doesn't have, not simply because an issue is taking a long time. A good escalation includes what's already been tried, exact error messages, and which users or systems are affected, that context is what actually speeds up the next level's diagnosis.",
"link": "",
"linkLabel": ""
},
{
"id": 49,
"category": "How IT support works",
"question": "What's the difference between an incident, a request, and a problem?",
"answer": "An incident is something broken right now (the printer isn't printing, the VPN is down), the goal is to restore service quickly. A request is asking for something new (new software, more storage, account access), it follows an approval process rather than a fix. A problem is the underlying root cause behind repeated incidents, if the same printer fails every Monday, that pattern gets investigated as a problem so it stops recurring, rather than just fixed each time it happens.",
"link": "",
"linkLabel": ""
},
{
"id": 50,
"category": "How IT support works",
"question": "Where does a change request fit in?",
"answer": "A change request is a planned, deliberate modification to a system, like a firmware upgrade or a new firewall rule, done through an approval process because unplanned changes are one of the most common causes of new incidents. This is why network hardware changes especially are usually scheduled for a maintenance window rather than made on the spot.",
"link": "",
"linkLabel": ""
},
{
"id": 51,
"category": "Mobile & remote work",
"question": "A phone or tablet won't enrol in the company's mobile device management (MDM)",
"answer": "Confirm you're using the exact enrolment method IT specified (a QR code, an enrolment URL, or a specific app store link), a generic 'add work account' option in phone settings sometimes skips steps the proper enrolment method includes. Also check the device's operating system version meets what IT requires, MDM enrolment is commonly blocked on outdated OS versions for security reasons.",
"link": "",
"linkLabel": ""
},
{
"id": 52,
"category": "Mobile & remote work",
"question": "Work email or apps stopped working on a personal phone after an update",
"answer": "A phone OS update can reset app permissions or trigger a compliance re-check by the organisation's MDM, temporarily blocking access until the device is confirmed to still meet security requirements like having a passcode set. Check for a compliance or 'action needed' notification from the company portal app before assuming it's broken.",
"link": "",
"linkLabel": ""
},
{
"id": 53,
"category": "Mobile & remote work",
"question": "A mobile VPN drops every time the screen locks",
"answer": "Many phones aggressively kill background network connections to save battery, including VPN apps, unless the app is specifically excluded from battery optimisation. Check the phone's battery settings for an 'unrestricted' or 'no optimisation' option for that VPN app specifically.",
"link": "",
"linkLabel": ""
},
{
"id": 54,
"category": "Mobile & remote work",
"question": "A remote desktop (RDP) session freezes or won't connect",
"answer": "Confirm you're connected to the VPN first if the remote machine is inside a private network, RDP almost never works over the open internet directly, for good security reasons. If the VPN is connected but it still fails, check whether the remote machine is actually powered on and not asleep, a surprisingly common cause.",
"link": "",
"linkLabel": ""
},
{
"id": 55,
"category": "Mobile & remote work",
"question": "A VDI session (Citrix, Horizon) is slow or won't launch",
"answer": "Test your own internet connection's latency and stability first, VDI performance is very sensitive to a poor home connection in a way a locally installed app isn't. If your connection is fine, try a different VDI client version or a browser-based login as a workaround while reporting the failure to IT with the exact error shown.",
"link": "",
"linkLabel": ""
},
{
"id": 56,
"category": "Mobile & remote work",
"question": "Working from home, the VPN connects but internal apps still time out",
"answer": "Some VPN setups use 'split tunnelling', where only traffic for specific internal systems goes through the VPN and everything else uses your home internet directly, if a newer internal app isn't yet included in that list, it will time out even with the VPN connected. That's a configuration detail for IT to add, not something you can usually fix from your end.",
"link": "",
"linkLabel": ""
},
{
"id": 57,
"category": "Cloud storage & sync",
"question": "OneDrive is stuck on 'processing changes' or won't sync",
"answer": "Pause and resume syncing from the OneDrive icon in the system tray, this resets a stuck sync engine more often than you'd expect. A very long file path, a file open in another program, or special characters in a file name are the next most common causes of a stuck sync. Moving the affected file out of the synced folder and back in again can also clear a single stuck item without resetting the whole sync.",
"link": "https://support.microsoft.com/en-us/onedrive/fix-onedrive-sync-problems",
"linkLabel": "Microsoft: fix OneDrive sync problems"
},
{
"id": 58,
"category": "Cloud storage & sync",
"question": "Google Drive shows a red exclamation mark on a file",
"answer": "This means that specific file failed to sync, usually because it's open in another application, too large for your remaining storage quota, or has a file type or name Drive can't handle. Hover over the icon for the exact reason, then close the file elsewhere or check your storage quota before retrying.",
"link": "",
"linkLabel": ""
},
{
"id": 59,
"category": "Cloud storage & sync",
"question": "Cloud storage quota is full",
"answer": "Check what's actually taking up space first, large video files and old email attachments are common causes, rather than immediately requesting more storage. If you genuinely need more for legitimate work purposes, that's a request rather than an incident (see 'How IT support works'), so it goes through IT's normal approval process.",
"link": "",
"linkLabel": ""
},
{
"id": 60,
"category": "Cloud storage & sync",
"question": "A shared file link says 'access denied' for someone outside the organisation",
"answer": "Many organisations restrict external sharing by default for security, so a link that works fine internally can fail for an outside recipient. Check the specific sharing settings on that file or folder, external sharing is often something that needs to be deliberately enabled per-file or per-site, rather than being on by default.",
"link": "",
"linkLabel": ""
},
{
"id": 61,
"category": "Cloud storage & sync",
"question": "Files show as 'online-only' and won't open without internet",
"answer": "Cloud sync clients often keep infrequently used files as a placeholder to save local disk space, downloading the real content only when opened, which fails without an internet connection. Right-click the specific file or folder you need offline and choose 'always keep on this device' before you lose connectivity, before a flight or a site visit, for example.",
"link": "",
"linkLabel": ""
},
{
"id": 62,
"category": "macOS specific",
"question": "A Mac update is stuck or won't install",
"answer": "Confirm there's enough free disk space, macOS updates need significant free space to stage the install and fail silently without it. Restart once and try again from System Settings rather than clicking install repeatedly, which can leave the updater in a confused state.",
"link": "",
"linkLabel": ""
},
{
"id": 63,
"category": "macOS specific",
"question": "Time Machine backup keeps failing",
"answer": "Check the backup drive isn't full and is actually connected and mounted, an intermittent external drive connection is the most common cause. If backing up to a network location, confirm you can still reach that server or NAS at all, a backup failure is often really a network or permissions issue in disguise.",
"link": "",
"linkLabel": ""
},
{
"id": 64,
"category": "macOS specific",
"question": "A Mac keeps asking for the keychain password unexpectedly",
"answer": "This usually happens after a password change that the login keychain doesn't yet know about, since it's a separate password store from your account login. Go to Keychain Access and update or reset the login keychain's password to match your new account password, rather than repeatedly dismissing the prompt. Resetting the keychain does clear its saved passwords, so only do this if you can't recover the old one.",
"link": "https://support.apple.com/guide/keychain-access/kyca2429/mac",
"linkLabel": "Apple: update your keychain password"
},
{
"id": 65,
"category": "macOS specific",
"question": "A Mac won't join a corporate wifi network with certificate login",
"answer": "Confirm the required certificate is actually installed in the Mac's keychain, it's normally pushed automatically by MDM (Jamf or similar) but can fail to install if the Mac hasn't checked in with MDM recently. Manually forcing an MDM check-in (System Settings > general profile management) before retrying the wifi connection resolves this in many cases.",
"link": "",
"linkLabel": ""
},
{
"id": 66,
"category": "Network hardware (IT staff)",
"question": "A Cisco switch port shows no link light",
"answer": "Start at the physical layer: reseat the cable, try a different port, and check for a bad SFP. Then confirm the port isn't administratively shut down with `show interfaces status`, if it is, `no shutdown` brings it back up.",
"link": "",
"linkLabel": ""
},
{
"id": 67,
"category": "Network hardware (IT staff)",
"question": "A Cisco port went err-disabled",
"answer": "This means the switch shut the port down itself, usually after a security violation, a BPDU guard trip, or a duplex mismatch. Check the reason with `show interfaces status err-disabled`, fix the underlying cause, then cycle the port with `shutdown` then `no shutdown`.",
"link": "",
"linkLabel": ""
},
{
"id": 68,
"category": "Network hardware (IT staff)",
"question": "Devices can't reach each other across a Cisco VLAN or trunk",
"answer": "Confirm the VLAN exists on both switches with `show vlan brief`, then check the trunk with `show interfaces trunk`. A mismatched native VLAN or a VLAN missing from the allowed list is the most common cause.",
"link": "",
"linkLabel": ""
},
{
"id": 69,
"category": "Network hardware (IT staff)",
"question": "A Cisco router or Layer 3 switch can't reach a remote subnet",
"answer": "Check `show ip interface brief` to confirm the interface is up, then `show ip route` to confirm a route exists. `ping` and `traceroute` will show exactly where the path breaks.",
"link": "",
"linkLabel": ""
},
{
"id": 70,
"category": "Network hardware (IT staff)",
"question": "A Cisco device is running hot (high CPU)",
"answer": "Check `show processes cpu sorted` to see what's using it. A spanning-tree loop or broadcast storm is a common cause on switches, `show spanning-tree` will show repeated topology changes if that's happening.",
"link": "",
"linkLabel": ""
},
{
"id": 71,
"category": "Network hardware (IT staff)",
"question": "A FortiGate isn't passing traffic that looks like it should be allowed",
"answer": "Confirm a firewall policy actually matches the source, destination and service, then use `diagnose sniffer packet any 'host x.x.x.x' 4` to see if traffic is arriving, and `diagnose debug flow` to see how the FortiGate is treating it.",
"link": "",
"linkLabel": ""
},
{
"id": 72,
"category": "Network hardware (IT staff)",
"question": "A FortiGate site-to-site IPsec VPN won't come up",
"answer": "Phase 1 and Phase 2 settings (encryption, PSK or certificate, proposals) must match exactly on both ends. `diagnose vpn ike log-filter` with `diagnose debug application ike -1` shows exactly where negotiation is failing.",
"link": "",
"linkLabel": ""
},
{
"id": 73,
"category": "Network hardware (IT staff)",
"question": "A FortiGate is slow or unresponsive",
"answer": "Check `get system performance status` for CPU, memory and session count, and `diagnose sys top` to see which process is responsible. A nearly-full session table is a common cause on busy units.",
"link": "",
"linkLabel": ""
},
{
"id": 74,
"category": "Network hardware (IT staff)",
"question": "Can't reach the FortiGate admin GUI from a particular network",
"answer": "FortiGate can restrict admin access to trusted hosts and specific interfaces. Check the admin account's trusted host settings and confirm the interface you're connecting through has HTTPS/SSH admin access enabled.",
"link": "",
"linkLabel": ""
},
{
"id": 75,
"category": "Network hardware (IT staff)",
"question": "How to safely back up a Cisco device's configuration",
"answer": "Before any change, save the running config to the startup config with `copy running-config startup-config`, then copy it off the device via TFTP or SCP so there's an external copy too. Always confirm the backup completed before making changes.",
"link": "",
"linkLabel": ""
},
{
"id": 76,
"category": "Network hardware (IT staff)",
"question": "How to safely upgrade Cisco IOS firmware",
"answer": "Confirm the new image is supported on the exact hardware model and that there's enough flash and RAM. Copy the image to flash, verify its checksum, set the new boot variable, save the config, then reload in a maintenance window in case it needs rolling back.",
"link": "",
"linkLabel": ""
},
{
"id": 77,
"category": "Network hardware (IT staff)",
"question": "Lost the password to a Cisco device",
"answer": "Password recovery needs physical console access and a reboot into ROMMON mode to bypass the startup config temporarily. This is a standard, well-documented process, but the exact key combination differs by model, check the vendor documentation for your specific device first.",
"link": "https://www.cisco.com/c/en/us/support/index.html",
"linkLabel": "Cisco Support"
},
{
"id": 78,
"category": "Network hardware (IT staff)",
"question": "A wireless access point won't join the Cisco WLC",
"answer": "Check the AP can discover the controller (DHCP option 43, DNS, or same-subnet broadcast), and that the AP's firmware is compatible with the controller's software version, a mismatch is a common cause of a failed join.",
"link": "",
"linkLabel": ""
},
{
"id": 79,
"category": "Network hardware (IT staff)",
"question": "Traffic is blocked on a Cisco ASA despite a matching ACL",
"answer": "Check NAT rules aren't exempting or redirecting the traffic unexpectedly, and confirm the ACL is applied in the right direction on the right interface. `packet-tracer` simulates a specific flow and shows exactly which rule drops it.",
"link": "",
"linkLabel": ""
},
{
"id": 80,
"category": "Network hardware (IT staff)",
"question": "One FortiGate in an HA cluster won't sync",
"answer": "Check both units are running the identical firmware version first, a mismatch is the most common HA sync blocker. `diagnose sys ha status` shows the current sync state and any errors.",
"link": "",
"linkLabel": ""
},
{
"id": 81,
"category": "Network hardware (IT staff)",
"question": "A FortiSwitch isn't showing up under FortiGate management",
"answer": "FortiGate manages FortiSwitches over FortiLink, confirm the FortiLink interface is correctly configured and that the switch port used for FortiLink hasn't been repurposed for something else.",
"link": "",
"linkLabel": ""
},
{
"id": 82,
"category": "Network hardware (IT staff)",
"question": "A FortiAP won't join its FortiGate",
"answer": "Confirm the AP can discover the FortiGate (same subnet, or DHCP option 138/CAPWAP discovery across routed networks) and that the AP and FortiGate firmware are a supported combination.",
"link": "",
"linkLabel": ""
},
{
"id": 83,
"category": "Network hardware (IT staff)",
"question": "SD-WAN traffic is taking the wrong path on a FortiGate",
"answer": "Check the SD-WAN rule order, first match wins, and whether the SLA health checks for that link are actually passing, a failed health check silently removes a path from consideration. `diagnose sys sdwan` shows live link status.",
"link": "",
"linkLabel": ""
},
{
"id": 84,
"category": "Network hardware (IT staff)",
"question": "A FortiGate says its licence or support contract has expired",
"answer": "An expired contract stops signature and firmware updates but doesn't usually stop the firewall passing traffic. Check the exact status with `get system status`, then renew through your reseller or Fortinet, running without updates for long is a real security risk.",
"link": "",
"linkLabel": ""
},
{
"id": 85,
"category": "Network hardware (IT staff)",
"question": "Where to find full Cisco documentation and command syntax",
"answer": "Always confirm exact command syntax against Cisco's own docs, it changes between switch/router models and IOS versions.",
"link": "https://www.cisco.com/c/en/us/support/index.html",
"linkLabel": "Cisco Support"
},
{
"id": 86,
"category": "Network hardware (IT staff)",
"question": "Where to find full Fortinet documentation and command syntax",
"answer": "FortiOS CLI commands and defaults vary by firmware version, the official Fortinet Document Library is the source of truth.",
"link": "https://docs.fortinet.com/",
"linkLabel": "Fortinet Document Library"
},
{
"id": 87,
"category": "Network hardware (IT staff)",
"question": "An IPsec tunnel looks correctly configured but still won't come up",
"answer": "When the config looks right on paper, checking the live IKE negotiation logs tells you more than re-checking the configuration a third time. Fortinet's own support community has a detailed walkthrough of the exact `diagnose` commands and log filters their engineers use for exactly this scenario.",
"link": "https://community.fortinet.com/t5/FortiGate/Troubleshooting-Tip-IPsec-VPN-tunnels/ta-p/195955",
"linkLabel": "Fortinet Community: IPsec VPN troubleshooting"
}
]
+37
View File
@@ -0,0 +1,37 @@
@import url('https://fonts.googleapis.com/css2?family=Instrument+Serif:ital@0;1&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
.liquid-glass {
background: rgba(255, 255, 255, 0.01);
background-blend-mode: luminosity;
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
border: none;
box-shadow: inset 0 1px 1px rgba(255, 255, 255, 0.1);
position: relative;
overflow: hidden;
}
.liquid-glass::before {
content: '';
position: absolute;
inset: 0;
border-radius: inherit;
padding: 1.4px;
background: linear-gradient(
180deg,
rgba(255, 255, 255, 0.45) 0%,
rgba(255, 255, 255, 0.15) 20%,
rgba(255, 255, 255, 0) 40%,
rgba(255, 255, 255, 0) 60%,
rgba(255, 255, 255, 0.15) 80%,
rgba(255, 255, 255, 0.45) 100%
);
-webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
-webkit-mask-composite: xor;
mask-composite: exclude;
pointer-events: none;
}
+10
View File
@@ -0,0 +1,10 @@
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App'
import './index.css'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<App />
</React.StrictMode>
)
+17
View File
@@ -0,0 +1,17 @@
// Safe wrappers: localStorage can be blocked (private mode), so never let it crash the page.
export function load<T>(key: string, fallback: T): T {
try {
const raw = localStorage.getItem(key)
return raw ? (JSON.parse(raw) as T) : fallback
} catch {
return fallback
}
}
export function save(key: string, value: unknown): void {
try {
localStorage.setItem(key, JSON.stringify(value))
} catch {
/* ignore */
}
}
+8
View File
@@ -0,0 +1,8 @@
export interface Faq {
id: number
category: string
question: string
answer: string
link: string
linkLabel: string
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+6
View File
@@ -0,0 +1,6 @@
/** @type {import('tailwindcss').Config} */
export default {
content: ['./index.html', './src/**/*.{ts,tsx}'],
theme: { extend: {} },
plugins: [],
}
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"moduleResolution": "bundler",
"jsx": "react-jsx",
"strict": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"noEmit": true,
"isolatedModules": true
},
"include": ["src", "vite.config.ts"]
}
+1
View File
@@ -0,0 +1 @@
{"root":["./src/App.tsx","./src/ContactForm.tsx","./src/Faq.tsx","./src/Staff.tsx","./src/VideoBackground.tsx","./src/main.tsx","./src/storage.ts","./src/types.ts","./src/vite-env.d.ts","./vite.config.ts"],"version":"5.6.3"}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
export default defineConfig({
plugins: [react()],
base: './',
server: { proxy: { '/api': 'http://localhost:3001' } },
})
+11
View File
@@ -0,0 +1,11 @@
{
"name": "cycle-atlas-root",
"private": true,
"version": "1.0.0",
"description": "Root wrapper so hosts can build and start the IT Support site in it-support/",
"engines": { "node": ">=22.13" },
"scripts": {
"build": "npm --prefix it-support install --include=dev && npm --prefix it-support run build",
"start": "NODE_ENV=production node it-support/server/index.js"
}
}
-59
View File
@@ -1,59 +0,0 @@
{
"version": 1,
"skills": {
"60fps-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/60fps-animation/SKILL.md",
"computedHash": "d832ea4a0dc07c18483d4fd39352c65e4daa2f298998290730cf159df30f400e"
},
"accessible-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/accessible-animation/SKILL.md",
"computedHash": "46695e422851b64f2b680924584ba9f7690309c109b6d98925ef3021b139167c"
},
"ascii-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/ascii-animation/SKILL.md",
"computedHash": "cc219b1851f713f76934a2738ccdcec37d4a266f1d20ecc346487290cc40d2fb"
},
"glassmorphism": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/glassmorphism/SKILL.md",
"computedHash": "c98e77044561fea5e51116156d0ba600a56f9961ed18b498d72504d49aff7882"
},
"gsap-web": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/gsap-web/SKILL.md",
"computedHash": "11585ce3142acae8db34c9d0eb57e03834972f1095643266eb2c41b432564b1d"
},
"lottie-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/lottie-animation/SKILL.md",
"computedHash": "3b9838145f5af19d03014a5eca9041ae0ba267b77e312332a129f3fe40078f68"
},
"micro-interaction": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/micro-interaction/SKILL.md",
"computedHash": "f236bc97a9f4c0e9c9a045d0b591e3ca6b6b2aeb26e42b661c15211f652ac131"
},
"page-transition-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/page-transition-animation/SKILL.md",
"computedHash": "62e103e2313433e77db26c67fdcae1c425030e1a51d0f5ffc0fb6fdac6d36132"
},
"svg-animation": {
"source": "iart-ai/web-animation-skills",
"sourceType": "github",
"skillPath": "skills/svg-animation/SKILL.md",
"computedHash": "b6902577f093a1cd724052b94e633154cb42020b5001138185982fb4ce230404"
}
}
}