@mkbabb/keyframes.js 1.1.0 → 1.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +208 -214
- package/dist/assets/CSSCodeEditor.vue_vue_type_script_setup_true_lang-DoeFo9B0.js +15 -0
- package/dist/assets/KeyframeTimeline-DCuTtSyj.js +3 -0
- package/dist/assets/KeyframeTimeline-Jb8HiEJ9.css +1 -0
- package/dist/assets/KeyframesStringControls-gfJd8pQq.js +6 -0
- package/dist/assets/codicon-DCmgc-ay.ttf +0 -0
- package/dist/assets/css.worker-DaIVPe4I.js +78 -0
- package/dist/assets/cube-CrhWuGpy.png +0 -0
- package/dist/assets/editor.worker-D_e4rV1K.js +11 -0
- package/dist/assets/html2canvas.esm-DXEQVQnt.js +5 -0
- package/dist/assets/index-BV83975F.css +1 -0
- package/dist/assets/index-DJ_IAlfb.js +651 -0
- package/dist/assets/ppmycota-logo-2-CAWHh5aE.svg +5 -0
- package/dist/assets/ppmycota-logo-3-BIN0nMRd.svg +5 -0
- package/dist/assets/vendor-highlight-CTbb6sRM.js +1 -0
- package/dist/assets/vendor-monaco-BS62pb6i.js +1035 -0
- package/dist/assets/vendor-monaco-bo9aZu7E.css +1 -0
- package/dist/assets/vendor-prettier-CT2Eqd5k.js +89 -0
- package/dist/index.html +20 -0
- package/package.json +5 -3
- package/dist/keyframes.cjs +0 -15
- package/dist/keyframes.d.ts +0 -213
- package/dist/keyframes.js +0 -5116
package/README.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# keyframes.js 
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
CSS keyframe animations for anything in JavaScript. Specify your keyframes in standards-compliant CSS; animate any object, DOM element, or data structure.
|
|
4
4
|
|
|
5
|
-
[demo
|
|
5
|
+
[Try the demo here!](https://keyframes.babb.dev/)
|
|
6
6
|
|
|
7
|
-
## Quick Start
|
|
7
|
+
## Quick Start
|
|
8
8
|
|
|
9
|
-
|
|
9
|
+
Create a `CSSKeyframesAnimation`, feed it CSS `@keyframes`, add targets, play:
|
|
10
10
|
|
|
11
11
|
```ts
|
|
12
12
|
const anim = new CSSKeyframesAnimation({
|
|
@@ -15,307 +15,301 @@ const anim = new CSSKeyframesAnimation({
|
|
|
15
15
|
direction: "alternate",
|
|
16
16
|
fillMode: "forwards",
|
|
17
17
|
});
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
#### Specify your keyframes in CSS:
|
|
21
18
|
|
|
22
|
-
|
|
23
|
-
@keyframes mijn-keyframes {
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
19
|
+
anim.fromString(`
|
|
20
|
+
@keyframes mijn-keyframes {
|
|
21
|
+
from {
|
|
22
|
+
transform: translateX(-100%) translateY(-100%) rotate(0turn);
|
|
23
|
+
background-color: #C462D8;
|
|
24
|
+
}
|
|
25
|
+
100% {
|
|
26
|
+
transform: translateX(50%) translateY(75%) rotate(1turn);
|
|
27
|
+
background-color: #E85252;
|
|
28
|
+
}
|
|
31
29
|
}
|
|
32
|
-
|
|
33
|
-
```
|
|
34
|
-
|
|
35
|
-
#### Add the keyframes to your animation, and add target elements to animate:
|
|
30
|
+
`);
|
|
36
31
|
|
|
37
|
-
|
|
38
|
-
const CSSKeyframes = /* the above string */ ...
|
|
39
|
-
anim.fromCSSKeyframes(CSSKeyframes);
|
|
40
|
-
anim.addTargets(document.getElementById("myElement"));
|
|
41
|
-
```
|
|
42
|
-
|
|
43
|
-
#### Play ▶️
|
|
44
|
-
|
|
45
|
-
```ts
|
|
32
|
+
anim.setTargets(document.getElementById("myElement"));
|
|
46
33
|
anim.play();
|
|
47
34
|
```
|
|
48
35
|
|
|
49
|
-
This
|
|
36
|
+
This animates the element's style properties as specified in the keyframes. The default behavior, but you can get far more inventive with it.
|
|
50
37
|
|
|
51
|
-
|
|
38
|
+
Plucked directly from the [`demo/simple`](demo/simple/App.vue) Vue file.
|
|
52
39
|
|
|
53
40
|
## Table of Contents
|
|
54
41
|
|
|
55
|
-
- [
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
- [
|
|
62
|
-
|
|
63
|
-
- [
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
- [Bézier Curves](#bézier-curves)
|
|
69
|
-
- [Graphing Bézier Curves](#graphing-bézier-curves)
|
|
70
|
-
- [Just gimme the `t` value](#just-gimme-the-t-value)
|
|
71
|
-
- [`TemplateAnimationFrame`](#templateanimationframe)
|
|
72
|
-
- [Reification of a `TemplateAnimationFrame`](#reification-of-a-templateanimationframe)
|
|
73
|
-
- [Variable Resolution](#variable-resolution)
|
|
74
|
-
- [`CSSKeyframesAnimation`](#csskeyframesanimation)
|
|
75
|
-
- [Parsing CSS Keyframes; `keyframes.ts`](#parsing-css-keyframes-keyframests)
|
|
76
|
-
- [Units: `units.ts` \& `CSS Units`](#units-unitsts--css-units)
|
|
77
|
-
- [Unit class hierarchy](#unit-class-hierarchy)
|
|
78
|
-
- [Unit interpolation and resolution](#unit-interpolation-and-resolution)
|
|
42
|
+
- [Installation](#installation)
|
|
43
|
+
- [Project Structure](#project-structure)
|
|
44
|
+
- [Animation](#animation)
|
|
45
|
+
- [AnimationOptions](#animationoptions)
|
|
46
|
+
- [Transform Function](#the-transform-function)
|
|
47
|
+
- [Timing Function](#the-timing-function)
|
|
48
|
+
- [TemplateAnimationFrame](#templateanimationframe)
|
|
49
|
+
- [CSSKeyframesAnimation](#csskeyframesanimation)
|
|
50
|
+
- [Parsing CSS Keyframes](#parsing-css-keyframes)
|
|
51
|
+
- [Units](#units)
|
|
52
|
+
- [AnimationGroup](#animationgroup)
|
|
53
|
+
- [Presets](#presets)
|
|
54
|
+
- [Build & Development](#build--development)
|
|
79
55
|
|
|
80
56
|
## Installation
|
|
81
57
|
|
|
82
58
|
```bash
|
|
83
|
-
npm install keyframes.
|
|
59
|
+
npm install @mkbabb/keyframes.js
|
|
84
60
|
```
|
|
85
61
|
|
|
86
|
-
|
|
62
|
+
Works both in and out of the browser. Anything that touches the DOM (`getComputedStyle`, `document`, etc.) won't work in Node.
|
|
87
63
|
|
|
88
|
-
##
|
|
64
|
+
## Project Structure
|
|
89
65
|
|
|
90
|
-
|
|
66
|
+
```
|
|
67
|
+
src/
|
|
68
|
+
├── animation/ # Animation engine: classes, group, presets, interpolation, WAAPI
|
|
69
|
+
│ ├── index.ts # Animation, CSSKeyframesAnimation
|
|
70
|
+
│ ├── group.ts # AnimationGroup — multi-animation compositor
|
|
71
|
+
│ ├── animations.ts # 30+ preset animations
|
|
72
|
+
│ ├── constants.ts # Types & defaults
|
|
73
|
+
│ ├── utils.ts # Frame calc, value interpolation
|
|
74
|
+
│ └── waapi.ts # Web Animations API delegation
|
|
75
|
+
├── parsing/ # CSS @keyframes parsing & serialization
|
|
76
|
+
│ ├── keyframes.ts # @keyframes grammar (parse-that combinators)
|
|
77
|
+
│ ├── format.ts # Animation → CSS string (Prettier)
|
|
78
|
+
│ ├── units.ts # Re-export: CSS value/color parsers
|
|
79
|
+
│ └── utils.ts # Re-export: parser combinators
|
|
80
|
+
├── units/ # Value types & normalization
|
|
81
|
+
│ ├── normalize.ts # DOM-aware unit normalization
|
|
82
|
+
│ ├── color/ # Color space classes, converters, normalization
|
|
83
|
+
│ └── *.ts # Re-export barrels from @mkbabb/value.js
|
|
84
|
+
├── easing.ts # Re-export: easing functions
|
|
85
|
+
├── math.ts # Re-export: clamp, lerp, bezier
|
|
86
|
+
└── utils.ts # Re-export + memoizeDecorator
|
|
87
|
+
|
|
88
|
+
demo/ # Vue 3 demo apps
|
|
89
|
+
├── @/ # Shared: animation controls, shadcn-vue UI, styles
|
|
90
|
+
├── cube/ # 3D cube + AnimationGroup + matrix editor (default demo)
|
|
91
|
+
├── simple/ # Minimal single-animation example
|
|
92
|
+
├── square/ # Custom transform function
|
|
93
|
+
├── amiga/ # 3D animated sphere (Three.js)
|
|
94
|
+
├── playground/ # Asset playground: drag-and-drop viewport with preset animation binding
|
|
95
|
+
├── balls/ # Vanilla JS: CSS vars + staggered animations
|
|
96
|
+
├── boxes/ # Vanilla JS: matrix3d transforms
|
|
97
|
+
└── bench/ # Performance benchmarks (rAF vs CSS vs WAAPI)
|
|
98
|
+
|
|
99
|
+
test/ # Vitest (jsdom) — 11 suites
|
|
100
|
+
bench/ # Vitest benchmarks — 3 suites
|
|
101
|
+
```
|
|
91
102
|
|
|
92
|
-
|
|
103
|
+
## Animation
|
|
93
104
|
|
|
94
|
-
|
|
95
|
-
- a transform function: the function to interpolate between keyframes
|
|
96
|
-
- a timing function: the function to ease the animation, which can also be set by the `AnimationOptions`
|
|
97
|
-
- keyframes: the keyframes for the animation; `TemplateAnimationFrame`
|
|
105
|
+
The `Animation` object drives `CSSKeyframesAnimation` and `AnimationGroup`. It's composed of:
|
|
98
106
|
|
|
99
|
-
|
|
107
|
+
- **options** (`AnimationOptions`)
|
|
108
|
+
- **transform function**: interpolates between keyframes
|
|
109
|
+
- **timing function**: eases the animation
|
|
110
|
+
- **keyframes** (`TemplateAnimationFrame`)
|
|
100
111
|
|
|
101
|
-
|
|
102
|
-
- delay: time in milliseconds before the animation starts
|
|
103
|
-
- iterationCount: number of times the animation should repeat
|
|
104
|
-
- direction: direction of the animation (normal, reverse, alternate, alternate-reverse)
|
|
105
|
-
- fillMode: how the animation should apply styles before and after it plays (none, forwards, backwards, both)
|
|
106
|
-
- timing function: the timing function to use for easing, tweening, etc., the animation
|
|
107
|
-
-
|
|
112
|
+
### `AnimationOptions`
|
|
108
113
|
|
|
109
|
-
|
|
114
|
+
- `duration`: time in milliseconds (default: 1000)
|
|
115
|
+
- `delay`: time in milliseconds before the animation begins (default: 0)
|
|
116
|
+
- `iterationCount`: number of repetitions (default: 1)
|
|
117
|
+
- `direction`: `normal`, `reverse`, `alternate`, `alternate-reverse`
|
|
118
|
+
- `fillMode`: `none`, `forwards`, `backwards`, `both`
|
|
119
|
+
- `timingFunction`: easing function (default: `easeInOutCubic`)
|
|
120
|
+
- `colorSpace`: color interpolation space (default: `oklab`)
|
|
121
|
+
- `hueMethod`: hue interpolation method for cylindrical color spaces (optional)
|
|
122
|
+
- `useWAAPI`: delegate to Web Animations API when eligible (default: `true`)
|
|
110
123
|
|
|
111
|
-
The
|
|
124
|
+
### The transform function
|
|
112
125
|
|
|
113
126
|
```ts
|
|
114
|
-
type TransformFunction<V extends Vars> = (
|
|
127
|
+
type TransformFunction<V extends Vars> = (v: V, t: number) => void;
|
|
115
128
|
```
|
|
116
129
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
The variables `v` are the interpolated values at time `t`, given to you in almost exactly the same form as you originally specified them in the keyframes. Deeply nested objects are supported, as are just about anything else you can think of.
|
|
130
|
+
Called at each timestep `t` (0 to `duration`) with the interpolated variables `v`. The variables arrive in the same shape you specified in your keyframes—deeply nested objects included.
|
|
120
131
|
|
|
121
|
-
Every value
|
|
132
|
+
Every value is parsed as a CSS value unit (`1px`, `1em`, `1deg`, etc.). To interpolate between two units they must share a supertype: `px` and `em` are both **length**, so they interpolate; `px` and `deg` are not.
|
|
122
133
|
|
|
123
134
|
### The timing function
|
|
124
135
|
|
|
125
|
-
The timing, or easing, tweening, etc., function is responsible for determining how the animation progresses over time. The type signature of the timing function is as follows:
|
|
126
|
-
|
|
127
136
|
```ts
|
|
128
137
|
type TimingFunction = (t: number) => number;
|
|
129
138
|
```
|
|
130
139
|
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
All CSS timing functions are supported, and are implemented in [`easing.ts`](src/easing.ts).
|
|
134
|
-
|
|
135
|
-
#### Step Functions
|
|
140
|
+
Takes `t` in `[0, 1]`, returns `[0, 1]`. All CSS timing functions are implemented in [`easing.ts`](src/easing.ts).
|
|
136
141
|
|
|
137
|
-
|
|
142
|
+
#### Step functions
|
|
138
143
|
|
|
139
|
-
|
|
140
|
-
- the direction, or jump term, of the step
|
|
144
|
+
Implemented as `steppedEase(t, steps, jumpTerm)`:
|
|
141
145
|
|
|
142
|
-
|
|
146
|
+
- `jump-none`: the value is held until the end of the step
|
|
147
|
+
- `jump-start` / `start`: step occurs at the start
|
|
148
|
+
- `jump-end` / `end`: step occurs at the end
|
|
149
|
+
- `jump-both` / `both`: steps at both boundaries
|
|
143
150
|
|
|
144
|
-
|
|
145
|
-
- `jump-start` | `start`: the step occurs at the start of the step
|
|
146
|
-
- `jump-end` | `end`: the step occurs at the end of the step
|
|
147
|
-
- `jump-both` | `both`: the step occurs at the start and end of the step
|
|
151
|
+
#### Bezier curves
|
|
148
152
|
|
|
149
|
-
|
|
153
|
+
`cubicBezier(t, x1, y1, x2, y2)` implements the cubic case. The general case uses de Casteljau's algorithm iteratively.
|
|
150
154
|
|
|
151
|
-
|
|
155
|
+
Both are in [`math.ts`](src/math.ts). For Bezier visualizations, see [this Desmos graph](https://www.desmos.com/calculator/tvivnkflzv) or the `timing-functions` demo.
|
|
152
156
|
|
|
153
|
-
|
|
157
|
+
`CSSCubicBezier` is the higher-order convenience: takes control points, returns a `t → value` function. CSS's named easings are built from it:
|
|
154
158
|
|
|
155
159
|
```ts
|
|
156
|
-
const
|
|
160
|
+
const easeInBounce = (t: number) => CSSCubicBezier(0.09, 0.91, 0.5, 1.5)(t);
|
|
157
161
|
```
|
|
158
162
|
|
|
159
|
-
|
|
163
|
+
### `TemplateAnimationFrame`
|
|
160
164
|
|
|
161
|
-
|
|
165
|
+
A template keyframe prior to resolution. Composed of:
|
|
162
166
|
|
|
163
|
-
|
|
167
|
+
- `id`: auto-incremented identifier
|
|
168
|
+
- `start`: start time (CSS time string, number, or percentage)
|
|
169
|
+
- `vars`: the variables to interpolate
|
|
170
|
+
- `transform`: per-keyframe transform function (optional)
|
|
171
|
+
- `timingFunction`: per-keyframe timing function (optional)
|
|
164
172
|
|
|
165
|
-
|
|
173
|
+
Once a transform or timing function is specified, it propagates to all subsequent keyframes.
|
|
166
174
|
|
|
167
|
-
|
|
175
|
+
#### Reification
|
|
168
176
|
|
|
169
|
-
|
|
177
|
+
Template keyframes are reified into concrete keyframes by:
|
|
170
178
|
|
|
171
|
-
|
|
179
|
+
1. **Parsing start times**: CSS time formats (`1s`, `100ms`), raw numbers, or percentages (`50%`). All normalized to a percentage of total duration.
|
|
180
|
+
2. **Resolving functions**: null transforms and timing functions fall back to the `AnimationOptions` defaults.
|
|
181
|
+
3. **Sorting** by start percentage.
|
|
182
|
+
4. **Resolving variables** across keyframes—every keyframe ends up with the same variable set.
|
|
183
|
+
5. **Computing durations** from sorted start/stop times.
|
|
172
184
|
|
|
173
|
-
|
|
185
|
+
#### Variable resolution
|
|
174
186
|
|
|
175
|
-
|
|
187
|
+
Keyframes needn't declare the same variables. The resolver walks backward from each keyframe, seeking the most recent definition of each variable. If none exists, the default value (typically `0`) is used.
|
|
176
188
|
|
|
177
189
|
```ts
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
}
|
|
190
|
+
const kf1 = { start: "0s", vars: { x: 0, y: 0 } };
|
|
191
|
+
const kf2 = { start: "500ms", vars: { x: 1 } };
|
|
192
|
+
const kf3 = { start: "100%", vars: { x: 0, y: 1 } };
|
|
182
193
|
```
|
|
183
194
|
|
|
184
|
-
|
|
195
|
+
`kf2` gets `y: 0` from `kf1`. This lets you specify keyframes loosely.
|
|
185
196
|
|
|
186
|
-
|
|
197
|
+
## `CSSKeyframesAnimation`
|
|
187
198
|
|
|
188
|
-
|
|
189
|
-
- start: the start time of the keyframe
|
|
190
|
-
- vars: the variables of the keyframe to be interpolated
|
|
191
|
-
- transform: the transform function of the keyframe
|
|
192
|
-
- timingFunction: the timing function of the keyframe
|
|
199
|
+
An abstraction over `Animation` that parses CSS `@keyframes` into `TemplateAnimationFrame` objects, then adds them to a base `Animation`.
|
|
193
200
|
|
|
194
|
-
|
|
201
|
+
Three ways to create keyframes:
|
|
195
202
|
|
|
196
|
-
|
|
203
|
+
```ts
|
|
204
|
+
// From CSS string (underlying parser is memoized; results cloned per call)
|
|
205
|
+
anim.fromString(`from { opacity: 0; } to { opacity: 1; }`);
|
|
197
206
|
|
|
198
|
-
|
|
207
|
+
// From keyframe map
|
|
208
|
+
anim.fromKeyframes({ "0%": { opacity: 0 }, "100%": { opacity: 1 } });
|
|
199
209
|
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
210
|
+
// From variable array
|
|
211
|
+
anim.fromVars([{ opacity: 0 }, { opacity: 1 }]);
|
|
212
|
+
```
|
|
203
213
|
|
|
204
|
-
|
|
214
|
+
The default transform applies interpolated values to `element.style` for each target.
|
|
205
215
|
|
|
206
|
-
|
|
207
|
-
- resolve the variables for each keyframe
|
|
208
|
-
- resolve the keyframes' start and stop times
|
|
209
|
-
- calculate the keyframes' duration
|
|
216
|
+
### Parsing CSS keyframes
|
|
210
217
|
|
|
211
|
-
|
|
218
|
+
[`keyframes.ts`](src/parsing/keyframes.ts) covers most of the CSS spec:
|
|
212
219
|
|
|
213
|
-
|
|
220
|
+
- `from`, `to`, and percentages
|
|
221
|
+
- Time units (`s`, `ms`)
|
|
222
|
+
- Lengths (`px`, `em`, etc.)
|
|
223
|
+
- Angles (`deg`, `rad`, etc.)
|
|
224
|
+
- Colors (`#fff`, `rgb(255, 255, 255)`, `lab(100, 0, 0)`, `lightblue`, etc.)
|
|
225
|
+
- Transforms (`translateX(100%)`, `rotate(1turn)`, etc.)
|
|
226
|
+
- Variables (`var(--my-var)`)
|
|
227
|
+
- Math expressions (`calc(100% - 10px)`)
|
|
228
|
+
- Any `key: value` pair parseable as a CSS value, function, or list thereof
|
|
214
229
|
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
z: 1,
|
|
227
|
-
};
|
|
228
|
-
```
|
|
230
|
+
The parser uses [`@mkbabb/parse-that`](https://github.com/mkbabb/parse-that) and [`@mkbabb/value.js`](https://github.com/mkbabb/value.js) for CSS value parsing. All exported parse functions are memoized.
|
|
231
|
+
|
|
232
|
+
### Units
|
|
233
|
+
|
|
234
|
+
Thorough unit parsing and resolution, covering:
|
|
235
|
+
|
|
236
|
+
- **length**, **angle**, **time**, **resolution**, **percentage**, **color**
|
|
237
|
+
|
|
238
|
+
See [`units/`](src/units/) and [`parsing/units.ts`](src/parsing/units.ts).
|
|
239
|
+
|
|
240
|
+
A `unit` value takes one of three forms:
|
|
229
241
|
|
|
230
|
-
|
|
242
|
+
- `ValueUnit`: a value with a string unit and an array of supertypes
|
|
243
|
+
- `FunctionValue`: a function name with an array of `ValueUnit`s
|
|
244
|
+
- `ValueArray`: an array of `ValueUnit`s
|
|
231
245
|
|
|
232
|
-
|
|
246
|
+
Each defines `toString()`, `valueOf()`, and `lerp(t, other, target?)`. Any `ValueUnit` variant can interpolate with any other—values are aligned to the shorter array, then interpolated element-wise.
|
|
233
247
|
|
|
234
|
-
|
|
248
|
+
Units of the same supertype interpolate freely. Supertypes also encode whether a unit is relative or absolute (`px` is absolute; `em` is relative), used to resolve to a common base before interpolation.
|
|
249
|
+
|
|
250
|
+
Interpolation dispatch: numeric values use `lerp`; colors use perceptual interpolation (`oklab` by default, configurable); computed units (`vh`, `vw`, `calc`, `var`) resolve against the live DOM at interpolation time.
|
|
251
|
+
|
|
252
|
+
## `AnimationGroup`
|
|
253
|
+
|
|
254
|
+
Composites multiple animations with layer blending. Each animation gets a layer config controlling how it merges with others.
|
|
235
255
|
|
|
236
256
|
```ts
|
|
237
|
-
const
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
vars: {
|
|
241
|
-
x: 0,
|
|
242
|
-
y: 0,
|
|
243
|
-
},
|
|
244
|
-
};
|
|
245
|
-
|
|
246
|
-
const keyframe2 = {
|
|
247
|
-
start: "100%",
|
|
248
|
-
vars: {
|
|
249
|
-
x: 0,
|
|
250
|
-
y: 1,
|
|
251
|
-
},
|
|
252
|
-
};
|
|
253
|
-
|
|
254
|
-
const keyframe3 = {
|
|
255
|
-
start: "500ms",
|
|
256
|
-
vars: {
|
|
257
|
-
x: 1,
|
|
258
|
-
},
|
|
259
|
-
};
|
|
257
|
+
const group = anim1.group(anim2, anim3);
|
|
258
|
+
group.setTargets(element);
|
|
259
|
+
group.play();
|
|
260
260
|
```
|
|
261
261
|
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
An abstraction over the `Animation` object, the `CSSKeyframesAnimation` object is responsible for creating animations from CSS keyframes. This is done by parsing the CSS keyframes into a series of `TemplateAnimationFrame` objects, thereupon adding them to a base `Animation` object.
|
|
262
|
+
Three blend modes:
|
|
265
263
|
|
|
266
|
-
|
|
264
|
+
- **`replace`**: highest `zIndex` wins (default)
|
|
265
|
+
- **`add`**: numeric values accumulate
|
|
266
|
+
- **`weighted`**: linear interpolation by `weight` (0–1)
|
|
267
267
|
|
|
268
|
-
|
|
268
|
+
Layer configuration per animation: `zIndex`, `weight`, `blendMode`, `enabled`, `properties` (whitelist). Property whitelisting enables effect layering—one layer animates position, another animates opacity.
|
|
269
269
|
|
|
270
|
-
|
|
271
|
-
- time units (`s`, `ms`, etc.)
|
|
272
|
-
- lengths (`px`, `em`, etc.)
|
|
273
|
-
- angles (`deg`, `rad`, etc.)
|
|
274
|
-
- colors (`#fff`, `rgb(255, 255, 255)`, `lab(100, 0, 0)`, `lightblue`, etc.)
|
|
275
|
-
- transforms (`translateX(100%)`, `rotate(1turn)`, etc.)
|
|
276
|
-
- variables (`var(--my-var)`)
|
|
277
|
-
- resolved math expressions (`calc(100% - 10px)`)
|
|
278
|
-
- Any `key: value` pair that can be parsed by the `CSS` parser, where value can be
|
|
279
|
-
- any CSS value
|
|
280
|
-
- any CSS function
|
|
281
|
-
- any list of CSS values or functions
|
|
282
|
-
- a limited subset of `JSON`-like objects, though the implemention of `JSON-CSS` is on the roadmap
|
|
270
|
+
The group manages its own `requestAnimationFrame` loop and marks child animations as `managed`.
|
|
283
271
|
|
|
284
|
-
|
|
272
|
+
## Presets
|
|
285
273
|
|
|
286
|
-
|
|
274
|
+
30+ ready-to-use animations in [`animations.ts`](src/animation/animations.ts). All return `CSSKeyframesAnimation` instances and accept optional `InputAnimationOptions`:
|
|
287
275
|
|
|
288
|
-
|
|
276
|
+
```ts
|
|
277
|
+
import { fadeIn, bounce, spinner } from "@mkbabb/keyframes.js";
|
|
289
278
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
- `percentage`
|
|
295
|
-
- `color`
|
|
279
|
+
const anim = fadeIn({ duration: 500 });
|
|
280
|
+
anim.setTargets(element);
|
|
281
|
+
anim.play();
|
|
282
|
+
```
|
|
296
283
|
|
|
297
|
-
|
|
284
|
+
**Fade**: `fadeIn`, `fadeOut` · **Attention**: `pulse`, `heartbeat`, `glow`, `shake`, `bounce` · **Entrance/Exit**: `flip`, `rotateIn`, `slideIn`, `slideInLeft/Right`, `slideOutLeft/Right`, `blurIn/Out/InOut`, `jumpUp/Down`, `warpLeft/Right` · **Effects**: `hover`, `typewriter`, `typingCursor`, `rainbowText`, `progressBar`, `skeletonLoading`, `spinner`, `parallaxScroll`, `gradientBackground`, `rotateScale`, `accordionExpand`, `notificationBounce`, `textFocusBlur`
|
|
298
285
|
|
|
299
|
-
|
|
286
|
+
## Web Animations API
|
|
300
287
|
|
|
301
|
-
|
|
288
|
+
When `useWAAPI` is `true` (default), eligible animations run on the compositor thread via `Element.animate()`. Eligibility requires: DOM targets, uniform timing function across frames, no computed units, no custom transform function, no color interpolation. Falls back to `requestAnimationFrame` silently.
|
|
302
289
|
|
|
303
|
-
|
|
304
|
-
- `FunctionValue`: a function with a string name and an array of `ValueUnit`s
|
|
305
|
-
- `ValueArray`: an array of `ValueUnit`s
|
|
290
|
+
## Build & Development
|
|
306
291
|
|
|
307
|
-
|
|
292
|
+
```sh
|
|
293
|
+
npm run build # library → dist/keyframes.js + keyframes.cjs + keyframes.d.ts
|
|
294
|
+
npm run gh-pages # demo → dist/
|
|
295
|
+
npm run dev # vite dev server on :8080 (cube demo)
|
|
296
|
+
npm test # vitest (jsdom)
|
|
297
|
+
npm run bench # vitest bench
|
|
298
|
+
```
|
|
308
299
|
|
|
309
|
-
|
|
310
|
-
- `valueOf()`: if the value is unit-less, returns the value; otherwise, returns the string variant
|
|
311
|
-
- `lerp(t: number,
|
|
312
|
-
other: FunctionValue<T> | ValueArray<T> | ValueUnit<T>,
|
|
313
|
-
target?: HTMLElement,)`: interpolates between two units
|
|
300
|
+
**Dependencies**: [`@mkbabb/value.js`](https://github.com/mkbabb/value.js) (ValueUnit, Color, math, parsing, normalization) and [`@mkbabb/parse-that`](https://github.com/mkbabb/parse-that) (parser combinators).
|
|
314
301
|
|
|
315
|
-
|
|
302
|
+
**TypeScript**: `strict: true`, `verbatimModuleSyntax: true`, `target: ES2022`, `moduleResolution: bundler`.
|
|
316
303
|
|
|
317
|
-
|
|
304
|
+
**Node**: >=22. **License**: GPL-3.0.
|
|
318
305
|
|
|
319
|
-
|
|
306
|
+
## Sources, acknowledgements, &c.
|
|
320
307
|
|
|
321
|
-
|
|
308
|
+
- [CSS Animations Level 1](https://www.w3.org/TR/css-animations-1/). W3C. — `@keyframes`, `animation-*` properties, timing model.
|
|
309
|
+
- [CSS Easing Functions Level 2](https://www.w3.org/TR/css-easing-2/). W3C. — `linear()` piecewise easing, `steps()` jump terms, `cubic-bezier()`.
|
|
310
|
+
- [CSS Transforms Module Level 2](https://www.w3.org/TR/css-transforms-2/). W3C. — `matrix3d()`, decomposition algorithm, quaternion interpolation.
|
|
311
|
+
- [CSSOM View Module](https://www.w3.org/TR/cssom-view-1/). W3C. — `getComputedStyle`, unit resolution for relative values.
|
|
312
|
+
- [Web Animations API](https://www.w3.org/TR/web-animations-1/). W3C. — `Element.animate()`; the WAAPI delegation path.
|
|
313
|
+
- [`@mkbabb/value.js`](https://github.com/mkbabb/value.js) — CSS value parsing, color spaces, unit conversion, easing functions.
|
|
314
|
+
- [`@mkbabb/parse-that`](https://github.com/mkbabb/parse-that) — Parser combinators for the `@keyframes` grammar.
|
|
315
|
+
- de Casteljau, P. (1959). *Outillages méthodes calcul*. — The recursive subdivision algorithm used for general Bezier curves.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import{W as b,a as w,e as m,D as V,L as T,l as W}from"./vendor-monaco-BS62pb6i.js";import{b as x,G as y,r as p,x as M,u as E,F,d as _,e as z}from"./index-DJ_IAlfb.js";import{H as D,_ as L}from"./vendor-prettier-CT2Eqd5k.js";import{C as O,a7 as B,ac as j,w as S,o as H,A as N,J as P,V as R,M as G,a5 as A,a9 as I}from"./vendor-highlight-CTbb6sRM.js";const K=80;async function C(a,i=void 0){return await D.format(a,{parser:"scss",plugins:[L],printWidth:i??K})}function U(a,i="animation"){let t="";t+=` animation-name: ${i};
|
|
2
|
+
`;const r=p(a.duration);t+=` animation-duration: ${r};
|
|
3
|
+
`;let s=Object.entries(M).filter(([l,n])=>n===a.timingFunction).map(([l])=>l)?.[0]??"linear";return s=y(s),t+=` animation-timing-function: ${s};
|
|
4
|
+
`,t+=` animation-iteration-count: ${isFinite(a.iterationCount)?a.iterationCount:"infinite"};
|
|
5
|
+
`,t+=` animation-direction: ${a.direction};
|
|
6
|
+
`,t+=` animation-fill-mode: ${a.fillMode};
|
|
7
|
+
`,a.delay>0&&(t+=` animation-delay: ${p(a.delay)};
|
|
8
|
+
`),t=`.${i} {
|
|
9
|
+
${t}}
|
|
10
|
+
`,t}function q(a){return`{
|
|
11
|
+
${Object.entries(x(a.flatVars)).map(([t,r])=>(t=y(t),` ${t}: ${r};`)).join(`
|
|
12
|
+
`).trim()}
|
|
13
|
+
}`}async function ee(a,i="animation",t=void 0){const r=a.options,s=new Map;a.frames.forEach(async d=>{const f=q(d);s.has(f)?s.get(f).push(d.start):s.set(f,[d.start])});let l="";for(let[d,f]of s)l+=`${f.join(", ")} ${d}`;const c=`${U(r,i)}
|
|
14
|
+
@keyframes ${i} {
|
|
15
|
+
${l}}`;return(await C(c,t)).replace(/\(\s*\{/g,"{").replace(/\}\s*\)/g,"}")}const te=O({__name:"CSSCodeEditor",props:I({height:{default:"300px"},fontSize:{default:14},lineNumbers:{type:Boolean,default:!0},padding:{default:16},border:{type:Boolean,default:!0}},{modelValue:{required:!0},modelModifiers:{}}),emits:["update:modelValue"],setup(a,{expose:i}){self.MonacoEnvironment={getWorker(e,o){return o==="css"||o==="scss"||o==="less"?new b:new w}},m.defineTheme("dark-theme",V),m.defineTheme("light-theme",T),W.register({id:"css"});const t=a,r=B(a,"modelValue"),s=j("containerEl"),{isDark:l}=E();let n,c=null,u=!1;const d=()=>{const e=s.value;if(!e||!e.offsetWidth||e.offsetWidth===0)return;const o=_(e.offsetWidth,"px","ch",e);return o!=null?Math.floor(o):void 0},f=z(e=>{r.value=e},200,!1),h=()=>{const e=s.value;n=m.create(e,{value:r.value,language:"css",fontLigatures:!0,theme:l.value?"dark-theme":"light-theme",fontSize:t.fontSize,fontFamily:"Fira Code",minimap:{enabled:!1},wordWrap:"on",scrollBeyondLastLine:!1,automaticLayout:!0,lineNumbers:t.lineNumbers?"on":"off",padding:{top:t.padding,bottom:t.padding}}),n.onDidChangeModelContent(()=>{u||f(n.getValue())})};S(l,()=>{m.setTheme(l.value?"dark-theme":"light-theme")}),S(r,e=>{if(n&&n.getValue()!==e){const o=n.getPosition();u=!0,n.setValue(e),o&&n.setPosition(o),u=!1}});const v=async()=>{if(!n)return;const e=await C(n.getValue(),d()),o=n.getPosition();u=!0,n.setValue(e),o&&n.setPosition(o),u=!1,F.success("CSS formatted")},$=e=>{n&&(u=!0,n.setValue(e),u=!1)},k=()=>n?.getValue()??"";return H(()=>{const e=s.value;e.offsetWidth>0&&e.offsetHeight>0?h():(c=new ResizeObserver(o=>{const g=o[0];g&&g.contentRect.width>0&&g.contentRect.height>0&&(c?.disconnect(),c=null,h())}),c.observe(e))}),N(()=>{c?.disconnect(),n?.dispose()}),i({formatCSS:v,setValue:$,getValue:k,editor:()=>n}),(e,o)=>(P(),R("div",{ref_key:"containerEl",ref:s,class:A(["w-full rounded-lg overflow-hidden",a.border?"border-2 border-gray-700 shadow-[4px_4px_0px_0px_rgba(0,0,0,0.6)] dark:shadow-gray-700":""]),style:G({height:a.height})},null,6))}});export{ee as C,te as _};
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{a6 as ze,C as se,J as y,V as b,a5 as I,u as l,I as Re,a as T,U as Ue,m as V,f as Be,ac as ke,M as z,Z as q,a1 as K,a3 as pe,n as Le,N as c,L as f,$ as x,K as ne,_ as Xe,O as X,F as H,W as J,a0 as O,af as We,v as ve}from"./vendor-highlight-CTbb6sRM.js";import{f as qe,h as Ye,U as Ge,C as Ze,G as ye,i as He,F as E,_ as Je,j as xe,k as W,T as Qe,M as et,l as tt,m as at,n as ot,o as nt,q as st,X as rt,t as lt,v as ge,w as he,y as be,D as it,z as _e,A as ct,B as ut}from"./index-DJ_IAlfb.js";import{C as dt,_ as mt}from"./CSSCodeEditor.vue_vue_type_script_setup_true_lang-DoeFo9B0.js";import{_ as ft}from"./vendor-monaco-BS62pb6i.js";import"./vendor-prettier-CT2Eqd5k.js";const pt=ze("maximize-2",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"m21 3-7 7",key:"1l2asr"}],["path",{d:"m3 21 7-7",key:"tjx5ai"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]),Se=se({__name:"DialogFooter",props:{class:{type:[Boolean,null,String,Object,Array]}},setup(u){const v=u;return(o,n)=>(y(),b("div",{class:I(l(qe)("flex flex-col-reverse sm:flex-row sm:justify-end sm:gap-x-2",v.class))},[Re(o.$slots,"default")],2))}}),vt=["transform","opacity","background-color","color","border-color","box-shadow","filter","width","height","top","left","right","bottom","margin","padding","border-radius","font-size"];let yt=0;const Q=()=>`kf-${Date.now()}-${yt++}`;function xt(u,v,o){const n=getComputedStyle(u),s={};for(const d of o){const p=n.getPropertyValue(d).trim();p&&p!=="none"&&p!=="auto"&&p!==""&&(s[d]=p)}return{id:Q(),percent:v,vars:s}}function we(u,v,o){const n={},s=[...u.keyframes].sort((p,$)=>p.percent-$.percent);for(const p of s){const $=p.percent===0?"from":p.percent===100?"to":`${p.percent}%`,g=n[$]??{};for(const[P,R]of Object.entries(p.vars)){const D=Ge(P);g[D]=R}n[$]=g}const d=new Ze(v,...o).fromKeyframes(n);return d.name=u.animationName,d}async function gt(u,v,o){const n=we(u,v,o);return await dt(n,u.animationName)}function ht(u){const v=Ye(u),o=[];for(const[n,s]of v.entries()){let d;if(n==="from"?d=0:n==="to"?d=100:d=parseFloat(n),isNaN(d))continue;const p={};Ce(s,"",p),o.push({id:Q(),percent:d,vars:p})}return o}function Ce(u,v,o){for(const[n,s]of Object.entries(u)){const d=v?`${v}-${ye(n)}`:ye(n);typeof s=="object"&&s!==null&&!s.valueOf?Ce(s,d,o):o[d]=String(s)}}function bt(u,v){const o=T({keyframes:[],captureProperties:[...vt],animationName:"timeline-animation"}),n=v??T({...He}),s=Be(null),d=T(0),p=T(!1),$=V(()=>[...o.value.keyframes].sort((r,i)=>r.percent-i.percent)),g=()=>{if(o.value.keyframes.length<2){s.value=null;return}try{const r=we(o.value,n.value,u.value);s.value=Ue(r)}catch(r){console.error("Failed to rebuild timeline animation:",r),s.value=null}},P=r=>{const i=u.value[0];if(!i){E.error("No target element to snapshot");return}const m=r??d.value*100,_=xt(i,m,o.value.captureProperties);o.value.keyframes.push(_),g(),E.success(`Keyframe captured at ${Math.round(m)}%`)},R=(r,i)=>{const m={id:Q(),percent:r,vars:i??{}};o.value.keyframes.push(m),g()},D=r=>{const i=o.value.keyframes.findIndex(m=>m.id===r);i!==-1&&(o.value.keyframes.splice(i,1),g())},Y=(r,i)=>{const m=o.value.keyframes.find(_=>_.id===r);m&&(m.percent=Math.max(0,Math.min(100,i)),g())},ee=(r,i,m)=>{const _=o.value.keyframes.find(w=>w.id===r);_&&(m.trim()===""?delete _.vars[i]:_.vars[i]=m,g())},U=r=>{d.value=Math.max(0,Math.min(1,r)),s.value&&(s.value.paused=!0,s.value.t=d.value*s.value.options.duration,s.value.interpFrames(s.value.t,!0))};return{state:o,animation:s,scrubT:d,isPlaying:p,sortedKeyframes:$,snapshot:P,addKeyframe:R,removeKeyframe:D,moveKeyframe:Y,updateKeyframeProperty:ee,rebuild:g,scrub:U,scrubAndCapture:async r=>{const i=u.value[0];if(!i)return null;const m=!!s.value,_=d.value;m&&(U(r/100),await new Promise(w=>requestAnimationFrame(()=>w())));try{const{default:w}=await ft(async()=>{const{default:F}=await import("./html2canvas.esm-DXEQVQnt.js");return{default:F}},[],import.meta.url);return await w(i,{scale:.5,logging:!1,backgroundColor:null})}catch{return null}finally{m&&U(_)}},exportCSS:async()=>{if(o.value.keyframes.length<2)return E.error("Need at least 2 keyframes to export"),"";try{const r=await gt(o.value,n.value,u.value);return await navigator.clipboard.writeText(r),E.success("CSS copied to clipboard!"),r}catch(r){return E.error("Failed to export CSS",{description:r.message}),""}},importCSS:r=>{try{const i=ht(r);if(i.length===0){E.error("No keyframes found in CSS");return}o.value.keyframes=i,g(),E.success(`Imported ${i.length} keyframes`)}catch(i){E.error("Failed to parse CSS",{description:i.message})}},loadPreset:r=>{const i=[];for(const m of r.templateFrames){const _=typeof m.start.valueOf()=="number"?m.start.valueOf()*100:0,w={};Te(m.vars,"",w),i.push({id:Q(),percent:_,vars:w})}o.value.keyframes=i,o.value.animationName=r.name??"preset-animation",g()},clear:()=>{o.value.keyframes=[],s.value=null}}}function Te(u,v,o){for(const[n,s]of Object.entries(u)){const d=v?`${v}-${n}`:n;typeof s=="object"&&s!==null&&typeof s.valueOf!="function"?Te(s,d,o):o[d]=String(s)}}const _t=["value"],St=se({__name:"TimelineCaret",props:{keyframeId:{},percent:{},position:{},isSelected:{type:Boolean}},emits:["update:percent","select"],setup(u,{emit:v}){const o=v,n=T(!1),s=ke("inputEl"),d=()=>{o("select"),n.value=!0,Le(()=>{s.value?.select()})},p=()=>{if(!n.value)return;const g=parseFloat(s.value?.value??"");isNaN(g)||o("update:percent",Math.max(0,Math.min(100,Math.round(g)))),n.value=!1},$=()=>{n.value=!1};return(g,P)=>(y(),b("div",{class:"absolute flex flex-col items-center",style:z({left:`${u.position}%`,top:"calc(50% + 14px)",transform:"translateX(-50%)"})},[n.value?(y(),b("input",{key:1,ref_key:"inputEl",ref:s,type:"number",value:Math.round(u.percent),class:"fira-code text-[10px] w-10 h-5 text-center bg-background border border-border rounded px-0.5 outline-none focus:ring-1 focus:ring-primary",min:"0",max:"100",onBlur:p,onKeydown:[pe(p,["enter"]),pe($,["escape"])],onClick:P[0]||(P[0]=q(()=>{},["stop"])),onPointerdown:P[1]||(P[1]=q(()=>{},["stop"]))},null,40,_t)):(y(),b("div",{key:0,class:I(["fira-code text-[10px] cursor-pointer select-none transition-colors whitespace-nowrap",u.isSelected?"text-primary font-semibold":"text-muted-foreground hover:text-foreground"]),onClick:q(d,["stop"])},K(Math.round(u.percent))+"%",3))],4))}}),kt={class:"flex flex-col gap-3"},wt={class:"flex items-center justify-end gap-1"},Ct={key:0,class:"flex items-center gap-2"},Tt={class:"relative flex-1 h-1.5 rounded-full bg-muted/50 border border-border/30"},Pt={class:"instrument-serif text-sm text-muted-foreground shrink-0"},$t=["onPointerdown","onMouseenter"],Mt={class:"flex flex-col items-center gap-1.5"},Kt={class:"fira-code text-xs font-semibold"},Et=["src"],Ot={key:2,class:"text-muted-foreground text-[10px] fira-code"},It={class:"fira-code text-[10px] text-muted-foreground max-h-24 overflow-y-auto w-full"},Dt={class:"text-foreground/70"},Ft={key:0,class:"italic"},At={key:0,class:"flex flex-col gap-3"},Nt={class:"flex items-center justify-between"},jt={class:"flex items-center gap-2"},Vt={class:"fira-code text-sm font-semibold"},zt=se({__name:"KeyframeTimeline",props:{targets:{},animationOptions:{},expanded:{type:Boolean}},emits:["toggleExpand"],setup(u,{expose:v,emit:o}){const n=u,s=o,d=V(()=>n.targets),p=n.animationOptions?V(()=>n.animationOptions):void 0,{state:$,sortedKeyframes:g,scrubT:P,snapshot:R,removeKeyframe:D,moveKeyframe:Y,rebuild:ee,scrubAndCapture:U,exportCSS:re,importCSS:te,clear:le}=bt(d,p),B=ke("trackEl"),C=T(null),r=T(null),i=T(!1),m=T(""),_=T(!1),w=T(""),F=ve({}),G=ve({}),ie=e=>{const t={};return e["background-color"]&&(t.backgroundColor=e["background-color"]),e.opacity&&(t.opacity=e.opacity),e.transform&&(t.transform=`scale(0.3) ${e.transform}`),e["border-radius"]&&(t.borderRadius=e["border-radius"]),t},Pe=async e=>{if(!(F[e.id]||G[e.id])){G[e.id]=!0;try{const t=await U(e.percent);t&&(F[e.id]=t.toDataURL("image/png"))}catch{}finally{G[e.id]=!1}}},S=T(1),M=T(0),A=e=>(e-M.value)*S.value,ce=e=>e/S.value+M.value,ae=()=>{const e=100-100/S.value;M.value=Math.max(0,Math.min(e,M.value))},$e=V(()=>{let e;S.value>=8?e=1:S.value>=5?e=5:S.value>=3?e=10:e=25;const t=[],a=M.value,h=M.value+100/S.value;for(let k=0;k<=100;k+=e)k>=a-e&&k<=h+e&&t.push(k);return t}),Me=e=>{if(e.ctrlKey||e.metaKey){const t=B.value.getBoundingClientRect(),a=(e.clientX-t.left)/t.width,h=ce(a*100),k=e.deltaY<0?1.05:1/1.05,j=Math.max(1,Math.min(10,S.value*k));M.value=h-a*100/j,S.value=j,ae()}else e.shiftKey&&S.value>1&&(M.value+=e.deltaY*.1/S.value,ae())};let Z=0,ue=1;const de=e=>{if(e.length<2)return 0;const t=e[1].clientX-e[0].clientX,a=e[1].clientY-e[0].clientY;return Math.sqrt(t*t+a*a)},Ke=e=>{e.touches.length===2&&(Z=de(e.touches),ue=S.value)},Ee=e=>{if(e.touches.length===2&&Z>0){const a=de(e.touches)/Z;S.value=Math.max(1,Math.min(10,ue*a)),ae()}},Oe=()=>{Z=0},N=V(()=>$.value.keyframes.find(e=>e.id===C.value)),Ie=V(()=>N.value?Object.entries(N.value.vars).map(([e,t])=>`${e}: ${t};`).join(`
|
|
2
|
+
`):""),De=e=>{if(!C.value)return;const t=$.value.keyframes.find(h=>h.id===C.value);if(!t)return;const a={};for(const h of e.split(`
|
|
3
|
+
`)){const k=h.trim();if(!k||k.startsWith("/*"))continue;const j=k.indexOf(":");if(j===-1)continue;const fe=k.slice(0,j).trim();let L=k.slice(j+1).trim();L.endsWith(";")&&(L=L.slice(0,-1).trim()),fe&&L&&(a[fe]=L)}t.vars=a,ee()},oe=e=>{if(!B.value)return 0;const t=B.value.getBoundingClientRect(),h=(e.clientX-t.left)/t.width*100;return Math.max(0,Math.min(100,ce(h)))},Fe=e=>{const t=oe(e);P.value=t/100,e.target.setPointerCapture(e.pointerId)},Ae=e=>{if(r.value){const t=oe(e);Y(r.value,t);return}if(e.buttons>0&&!r.value){const t=oe(e);P.value=t/100}},me=()=>{r.value=null},Ne=(e,t)=>{C.value=t,r.value=t,e.target.setPointerCapture(e.pointerId)},je=()=>{m.value.trim()&&(te(m.value),i.value=!1,m.value="")},Ve=()=>{w.value.trim()&&(te(w.value),_.value=!1,w.value="")};return v({snapshot:R,openImportDialog:()=>{i.value=!0},openAddCSSDialog:()=>{_.value=!0},exportCSS:re,removeSelectedKeyframe:()=>{C.value&&(D(C.value),C.value=null)},selectedKeyframeId:C}),(e,t)=>(y(),b("div",kt,[c(l(lt),{class:I(["w-full overflow-visible transition-all duration-150",n.expanded?"border-0 shadow-none bg-transparent":""])},{default:f(()=>[c(l(Je),{class:I(["relative flex flex-col gap-3",n.expanded?"p-2 px-0":"p-4"])},{default:f(()=>[x("div",wt,[c(xe,{text:"Clear all keyframes"},{default:f(()=>[c(l(W),{size:"sm",variant:"ghost",class:"cursor-pointer h-7 w-7 p-0 opacity-50 hover:opacity-100",onClick:t[0]||(t[0]=a=>l(le)())},{default:f(()=>[c(l(Qe),{class:"w-3.5 h-3.5"})]),_:1})]),_:1}),c(xe,{text:n.expanded?"Collapse timeline":"Expand timeline"},{default:f(()=>[c(l(W),{size:"sm",variant:"ghost",class:"cursor-pointer h-7 w-7 p-0 opacity-50 hover:opacity-100",onClick:t[1]||(t[1]=a=>s("toggleExpand"))},{default:f(()=>[(y(),ne(Xe(n.expanded?l(et):l(pt)),{class:"w-3.5 h-3.5"}))]),_:1})]),_:1},8,["text"])]),S.value>1?(y(),b("div",Ct,[x("div",Tt,[x("div",{class:"absolute top-0 h-full rounded-full bg-primary/40",style:z({left:`${M.value/100*100}%`,width:`${100/S.value/100*100}%`})},null,4)]),x("span",Pt,K(S.value.toFixed(1))+"x",1)])):X("",!0),x("div",{ref_key:"trackEl",ref:B,class:I(["timeline-track relative rounded-lg border border-border bg-muted/50 hover:bg-muted/70 transition-all duration-150 cursor-pointer select-none overflow-x-clip overflow-y-visible",n.expanded?"h-32":"h-12"]),style:{"touch-action":"none"},onPointerdown:Fe,onPointermove:Ae,onPointerup:me,onPointercancel:me,onWheel:q(Me,["prevent"]),onTouchstartPassive:Ke,onTouchmovePassive:Ee,onTouchendPassive:Oe},[(y(!0),b(H,null,J($e.value,a=>(y(),b("div",{key:a,class:"absolute top-0 h-full border-l border-border/30",style:z({left:`${A(a)}%`})},[x("span",{class:I(["instrument-serif absolute -top-5 left-0 text-sm text-muted-foreground whitespace-nowrap",A(a)<=2?"translate-x-0":A(a)>=98?"-translate-x-full":"-translate-x-1/2"])},K(a)+"%",3)],4))),128)),x("div",{class:"absolute top-0 h-full w-0.5 bg-primary z-10 pointer-events-none",style:z({left:`${A(l(P)*100)}%`})},null,4),(y(!0),b(H,null,J(l(g),a=>(y(),ne(l(tt),{key:a.id},{default:f(()=>[c(l(at),{"as-child":""},{default:f(()=>[x("div",{class:I(["keyframe-marker absolute top-1/2 -translate-x-1/2 -translate-y-1/2 z-20",n.expanded?"w-6 h-6":"w-4 h-4","rotate-45 rounded-sm cursor-grab","border-2 transition-all",C.value===a.id?"bg-primary border-primary scale-125":"bg-background border-foreground/50 hover:border-primary hover:scale-110"]),style:z({left:`${A(a.percent)}%`}),onPointerdown:q(h=>Ne(h,a.id),["stop"]),onMouseenter:h=>Pe(a)},null,46,$t)]),_:2},1024),c(l(ot),{side:"top","side-offset":8,class:"p-2 max-w-56"},{default:f(()=>[x("div",Mt,[x("span",Kt,K(Math.round(a.percent))+"%",1),F[a.id]?(y(),b("img",{key:0,src:F[a.id],class:"w-36 h-auto rounded border border-border/30"},null,8,Et)):Object.keys(ie(a.vars)).length>0?(y(),b("div",{key:1,class:"w-16 h-16 rounded border border-border/30 bg-muted/30",style:z(ie(a.vars))},null,4)):X("",!0),G[a.id]?(y(),b("div",Ot," Capturing... ")):X("",!0),x("div",It,[(y(!0),b(H,null,J(Object.entries(a.vars),([h,k])=>(y(),b("div",{key:h,class:"truncate"},[x("span",Dt,K(h),1),O(": "+K(k),1)]))),128)),Object.keys(a.vars).length===0?(y(),b("div",Ft,"No properties")):X("",!0)])])]),_:2},1024)]),_:2},1024))),128)),(y(!0),b(H,null,J(l(g),a=>(y(),ne(St,{key:"caret-"+a.id,"keyframe-id":a.id,percent:a.percent,position:A(a.percent),"is-selected":C.value===a.id,"onUpdate:percent":h=>l(Y)(a.id,h),onSelect:h=>C.value=a.id},null,8,["keyframe-id","percent","position","is-selected","onUpdate:percent","onSelect"]))),128))],34),c(We,{name:"kf-editor"},{default:f(()=>[N.value?(y(),b("div",At,[c(l(nt)),x("div",Nt,[x("div",jt,[x("span",Vt,K(Math.round(N.value.percent))+"%",1),c(l(st),{modelValue:N.value.label,"onUpdate:modelValue":t[2]||(t[2]=a=>N.value.label=a),placeholder:"Label...",class:"fira-code text-xs h-6 w-32"},null,8,["modelValue"])]),c(l(W),{size:"sm",variant:"ghost",class:"h-6 w-6 p-0 cursor-pointer",onClick:t[3]||(t[3]=a=>l(D)(C.value))},{default:f(()=>[c(l(rt),{class:"w-3 h-3"})]),_:1})]),c(mt,{"model-value":Ie.value,height:"250px","onUpdate:modelValue":De},null,8,["model-value"])])):X("",!0)]),_:1})]),_:1},8,["class"])]),_:1},8,["class"]),c(l(_e),{open:i.value,"onUpdate:open":t[5]||(t[5]=a=>i.value=a)},{default:f(()=>[c(l(ge),null,{default:f(()=>[c(l(he),{class:"instrument-serif text-lg font-medium"},{default:f(()=>[...t[8]||(t[8]=[O("Import CSS @keyframes",-1)])]),_:1}),c(l(be),{class:"instrument-serif text-lg text-muted-foreground"},{default:f(()=>[...t[9]||(t[9]=[O("Paste CSS @keyframes to load into the timeline",-1)])]),_:1}),x("pre",{ref:"importTextEl",onInput:t[4]||(t[4]=a=>{m.value=a.target.innerText}),class:"fira-code min-h-[20vh] p-3 cursor-text rounded-lg text-sm bg-muted/50 outline-none border border-border",contenteditable:"true"},[x("code",null,K(m.value),1)],544),c(l(Se),null,{default:f(()=>[c(l(W),{class:"cursor-pointer gap-2",onClick:je},{default:f(()=>[t[10]||(t[10]=O("Import",-1)),c(l(it),{class:"w-4 h-4"})]),_:1})]),_:1})]),_:1})]),_:1},8,["open"]),c(l(_e),{open:_.value,"onUpdate:open":t[7]||(t[7]=a=>_.value=a)},{default:f(()=>[c(l(ge),null,{default:f(()=>[c(l(he),{class:"instrument-serif text-lg font-medium"},{default:f(()=>[...t[11]||(t[11]=[O("Add CSS @keyframes",-1)])]),_:1}),c(l(be),{class:"instrument-serif text-lg text-muted-foreground"},{default:f(()=>[...t[12]||(t[12]=[O("Paste CSS @keyframes to merge into the timeline",-1)])]),_:1}),x("pre",{ref:"addCSSTextEl",onInput:t[6]||(t[6]=a=>{w.value=a.target.innerText}),class:"fira-code min-h-[20vh] p-3 cursor-text rounded-lg text-sm bg-muted/50 outline-none border border-border",contenteditable:"true"},[x("code",null,K(w.value),1)],544),c(l(Se),null,{default:f(()=>[c(l(W),{class:"cursor-pointer gap-2",onClick:Ve},{default:f(()=>[t[13]||(t[13]=O("Add",-1)),c(l(ct),{class:"w-4 h-4"})]),_:1})]),_:1})]),_:1})]),_:1},8,["open"])]))}}),Gt=ut(zt,[["__scopeId","data-v-2463a7b5"]]);export{Gt as default};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
.timeline-track[data-v-2463a7b5]{margin-top:1.25rem;margin-bottom:1rem}.keyframe-marker[data-v-2463a7b5]{transition:transform .15s ease,border-color .15s ease}.keyframe-marker[data-v-2463a7b5]:active{cursor:grabbing}.kf-editor-enter-active[data-v-2463a7b5]{transition:opacity .15s ease,transform .15s ease}.kf-editor-leave-active[data-v-2463a7b5]{transition:opacity .1s ease,transform .1s ease}.kf-editor-enter-from[data-v-2463a7b5]{opacity:0;transform:translateY(-8px)}.kf-editor-leave-to[data-v-2463a7b5]{opacity:0;transform:translateY(-4px)}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{c as L,g as M,a as P,C as F,s as R,F as g,P as q,p as z,r as x}from"./index-DJ_IAlfb.js";import{o as E,A as U,a as r,C as G,ac as H,J,V as j,$ as Q,N as w,u as W}from"./vendor-highlight-CTbb6sRM.js";import{_ as Y,C as Z}from"./CSSCodeEditor.vue_vue_type_script_setup_true_lang-DoeFo9B0.js";import"./vendor-monaco-BS62pb6i.js";import"./vendor-prettier-CT2Eqd5k.js";function _(e){const a=r(null),l=()=>{const i=document.head.querySelector(`#${e}`);if(i)a.value=i;else{const m=document.createElement("style");m.id=e,document.head.appendChild(m),a.value=m}},u=i=>{a.value&&(a.value.textContent=i)},p=()=>{a.value&&(a.value.textContent="")};return E(()=>{l()}),U(()=>{a.value?.remove(),a.value=null}),{keyframesStyle:a,setContent:u,clear:p}}const ee={class:"min-w-0"},se=G({__name:"KeyframesStringControls",props:{animation:{}},emits:["keyframesUpdate"],setup(e,{expose:a,emit:l}){const u=l,i=`keyframes-style-${L(e.animation,e.animation.superKey)}`,m={selectedKeyframesControl:"keyframes",dialogOpen:!1,keyframes:"",addKeyframes:""},h=M(e.animation);h.keyframeControls??=m;const c=r(null),s=r(""),f=r(!1);let d;const y=r(!1),S=()=>i.replace("keyframes-style-","").toLowerCase(),b=async()=>(s.value=await Z(e.animation,S()),s.value),k=async()=>{c.value&&(f.value=!0,await c.value.formatCSS(),clearTimeout(d),d=setTimeout(()=>{f.value=!1},300))};function T(t){if(t.key==="Ï"){t.preventDefault(),k();return}}const O=P(e.animation),D=t=>{const o=e.animation.options,n=O.animationOptions;n.duration=x(o.duration),n.delay=x(o.delay),n.iterationCount=isFinite(o.iterationCount)?o.iterationCount:"infinite",n.direction=o.direction,n.fillMode=o.fillMode,t?.timingFunction&&(n.timingFunction=t.timingFunction)},I=t=>{const o=()=>{const{keyframes:n,options:C}=z(t),B=new F(e.animation.options,...e.animation.targets).fromKeyframes(n);C&&e.animation.setOptions(C),e.animation.templateFrames=B.templateFrames,e.animation.parse(),D(C),u("keyframesUpdate",{animation:e.animation}),h.keyframeControls.keyframes=t,f.value||g.success("Keyframes parsed 🎉")};try{o()}catch(n){$.play(),g.error("Failed to parse keyframes 🔧",{description:n.message,duration:1e4}),console.error(n)}},{setContent:N,clear:V}=_(i),A=r(!1),X=()=>{y.value?(e.animation.paused=A.value,V(),e.animation.targets.forEach(t=>t.classList.remove(S())),v.pause(),y.value=!1):(A.value=e.animation.paused,e.animation.paused=e.animation.started,N(s.value),e.animation.targets.forEach(t=>t.classList.add(S())),v.play(),y.value=!0)},K=H("brushEl"),v=new F({duration:1200,timingFunction:"ease-in-out",iterationCount:"infinite",direction:"alternate"}).fromString(`@keyframes paintbrushStroke {
|
|
2
|
+
0% { transform: translateX(0px) rotate(0deg); }
|
|
3
|
+
30% { transform: translateX(2px) rotate(-8deg); }
|
|
4
|
+
70% { transform: translateX(-2px) rotate(8deg); }
|
|
5
|
+
100% { transform: translateX(0px) rotate(0deg); }
|
|
6
|
+
}`),$=R();return E(async()=>{v.setTargets(K.value),await b()}),U(()=>{clearTimeout(d)}),a({formatCSS:k,copyCSS:async()=>{s.value&&(await navigator.clipboard.writeText(s.value),g.success("CSS copied to clipboard"))},getCSSString:()=>s.value,applyCSSStyles:X}),(t,o)=>(J(),j("div",ee,[Q("div",{class:"relative",onKeydown:T},[w(Y,{ref_key:"editorRef",ref:c,"model-value":s.value,height:"450px","font-size":14,"line-numbers":!0,border:!0,"onUpdate:modelValue":I},null,8,["model-value"]),w(W(q),{ref_key:"brushEl",ref:K,class:"hidden"},null,512)],32)]))}});export{se as default};
|
|
Binary file
|