@xtia/timeline 1.0.0 → 1.0.2

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.
@@ -0,0 +1,414 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Timeline = void 0;
4
+ exports.animate = animate;
5
+ const emitters_1 = require("./emitters");
6
+ const utils_1 = require("./utils");
7
+ const default_fps = 60;
8
+ const EndAction = {
9
+ pause: 0,
10
+ continue: 1,
11
+ wrap: 2,
12
+ restart: 3,
13
+ };
14
+ /**
15
+ * Creates an autoplaying Timeline and returns a range from it
16
+ * @param duration
17
+ * @returns Object representing a range on a single-use, autoplaying Timeline
18
+ */
19
+ function animate(duration) {
20
+ return new Timeline(true).range(0, duration);
21
+ }
22
+ class Timeline {
23
+ get currentTime() { return this._currentTime; }
24
+ set currentTime(v) {
25
+ this.seek(v);
26
+ }
27
+ get isPlaying() {
28
+ return this.interval !== null;
29
+ }
30
+ get end() {
31
+ return this.point(this._endPosition);
32
+ }
33
+ constructor(autoplay = false, endAction = "pause") {
34
+ /**
35
+ * Multiplies the speed at which `play()` progresses through the Timeline
36
+ *
37
+ * A value of 2 would double progression speed while .25 would slow it to a quarter
38
+ */
39
+ this.timeScale = 1;
40
+ this._currentTime = 0;
41
+ this._endPosition = 0;
42
+ this.interval = null;
43
+ this.points = [];
44
+ this.ranges = [];
45
+ this.currentSortDirection = 0;
46
+ this.smoothSeeker = null;
47
+ this.seeking = false;
48
+ this.start = this.point(0);
49
+ this.positionHandlers = [];
50
+ if (endAction == "loop")
51
+ endAction = "restart";
52
+ if (autoplay !== false) {
53
+ this.play(typeof autoplay == "number" ? autoplay : default_fps);
54
+ }
55
+ if (typeof endAction == "object"
56
+ && "restartAt" in endAction) {
57
+ this.endAction = {
58
+ type: EndAction.restart,
59
+ at: this.point(endAction.restartAt),
60
+ };
61
+ }
62
+ else if (typeof endAction == "object"
63
+ && "wrapAt" in endAction) {
64
+ this.endAction = {
65
+ type: EndAction.wrap,
66
+ at: this.point(endAction.wrapAt),
67
+ };
68
+ }
69
+ else
70
+ this.endAction = {
71
+ type: EndAction[endAction],
72
+ at: this.point(0),
73
+ };
74
+ }
75
+ /**
76
+ * Defines a single point on the Timeline
77
+ *
78
+ * @param position
79
+ * @returns A point on the Timeline as specified
80
+ *
81
+ * Listenable: this point will emit a PointEvent whenever a `seek()` reaches or passes it
82
+ */
83
+ point(position) {
84
+ if (position > this._endPosition)
85
+ this._endPosition = position;
86
+ const handlers = [];
87
+ const data = {
88
+ handlers,
89
+ position,
90
+ };
91
+ return (0, emitters_1.createEmitter)(handler => {
92
+ if (this.seeking)
93
+ throw new Error("Can't add a listener while seeking");
94
+ // we're adding and removing points and ranges to the internal registry according to whether any subscriptions are active, to allow obsolete points and ranges to be garbage-collected
95
+ if (handlers.length == 0) {
96
+ this.points.push(data);
97
+ this.currentSortDirection = 0;
98
+ }
99
+ handlers.push(handler);
100
+ return () => {
101
+ const idx = handlers.indexOf(handler);
102
+ if (idx === -1)
103
+ throw new Error("Internal error: attempting to remove a non-present handler");
104
+ handlers.splice(idx, 1);
105
+ if (handlers.length == 0) {
106
+ const idx = this.points.indexOf(data);
107
+ this.points.splice(idx, 1);
108
+ }
109
+ };
110
+ }, {
111
+ delta: t => this.point(position + t),
112
+ range: duration => this.range(position, duration),
113
+ to: target => {
114
+ const targetPosition = typeof target == "number"
115
+ ? target
116
+ : target.position;
117
+ return this.range(position, targetPosition - position);
118
+ },
119
+ position,
120
+ });
121
+ }
122
+ range(start = 0, optionalDuration) {
123
+ const startPoint = typeof start == "number"
124
+ ? this.point(start)
125
+ : start;
126
+ const startPosition = startPoint.position;
127
+ const duration = optionalDuration ?? this._endPosition - startPosition;
128
+ const endPosition = startPosition + duration;
129
+ if (endPosition > this._endPosition)
130
+ this._endPosition = endPosition;
131
+ const handlers = [];
132
+ const range = {
133
+ position: startPosition,
134
+ duration,
135
+ handlers,
136
+ };
137
+ const addHandler = (handler) => {
138
+ if (this.seeking)
139
+ throw new Error("Can't add a listener while seeking");
140
+ if (handlers.length == 0) {
141
+ this.ranges.push(range);
142
+ this.currentSortDirection = 0;
143
+ }
144
+ handlers.push(handler);
145
+ return () => {
146
+ const idx = handlers.indexOf(handler);
147
+ if (idx === -1)
148
+ throw new Error("Internal error: attempting to remove a non-present handler");
149
+ handlers.splice(idx, 1);
150
+ if (handlers.length == 0) {
151
+ const idx = this.ranges.indexOf(range);
152
+ this.ranges.splice(idx, 1);
153
+ }
154
+ };
155
+ };
156
+ return (0, emitters_1.createProgressEmitter)(addHandler, {
157
+ duration,
158
+ start: this.point(startPosition),
159
+ end: this.point(startPosition + duration),
160
+ bisect: (position = duration / 2) => {
161
+ return [
162
+ this.range(startPosition, position),
163
+ this.range(startPosition + position, duration - position),
164
+ ];
165
+ },
166
+ spread: (count) => {
167
+ const delta = duration / (count + 1);
168
+ return [
169
+ ...Array(count).fill(0).map((_, idx) => this.point(idx * delta + startPosition + delta))
170
+ ];
171
+ },
172
+ play: (easer) => {
173
+ this.pause();
174
+ this.currentTime = startPosition;
175
+ return this.seek(startPosition + duration, duration, easer);
176
+ },
177
+ grow: (delta, anchor = 0) => {
178
+ const clampedAnchor = (0, utils_1.clamp)(anchor, 0, 1);
179
+ const leftDelta = -delta * (1 - clampedAnchor);
180
+ const rightDelta = delta * clampedAnchor;
181
+ const newStart = startPosition + leftDelta;
182
+ const newEnd = endPosition + rightDelta;
183
+ if (newEnd < newStart) {
184
+ const mid = (newStart + newEnd) / 2;
185
+ return this.range(mid, 0);
186
+ }
187
+ return this.range(newStart, newEnd - newStart);
188
+ },
189
+ scale: (factor, anchor = 0.5) => {
190
+ if (factor <= 0) {
191
+ throw new RangeError('scale factor must be > 0');
192
+ }
193
+ const clampedAnchor = (0, utils_1.clamp)(anchor, 0, 1);
194
+ const oldLen = endPosition - startPosition;
195
+ const pivot = startPosition + oldLen * clampedAnchor;
196
+ const newStart = pivot - (pivot - startPosition) * factor;
197
+ const newEnd = pivot + (endPosition - pivot) * factor;
198
+ if (newEnd < newStart) {
199
+ const mid = (newStart + newEnd) / 2;
200
+ return this.range(mid, 0);
201
+ }
202
+ return this.range(newStart, newEnd - newStart);
203
+ },
204
+ });
205
+ }
206
+ getWrappedPosition(n) {
207
+ if (this.endAction.type !== EndAction.wrap)
208
+ return n;
209
+ const wrapAt = this.endAction.at?.position ?? 0;
210
+ if (wrapAt == 0)
211
+ return n % this._endPosition;
212
+ if (n <= this._endPosition)
213
+ return n;
214
+ const loopStart = wrapAt;
215
+ const segment = this._endPosition - loopStart;
216
+ if (segment <= 0)
217
+ return Math.min(n, this._endPosition);
218
+ const overflow = n - this._endPosition;
219
+ const remainder = overflow % segment;
220
+ return loopStart + remainder;
221
+ }
222
+ seek(to, duration = 0, easer) {
223
+ const toPosition = typeof to == "number"
224
+ ? to
225
+ : to.position;
226
+ if (this.seeking) {
227
+ throw new Error("Can't seek while seeking");
228
+ }
229
+ if (this.smoothSeeker !== null) {
230
+ this.smoothSeeker.pause();
231
+ // ensure any awaits are resolved for the previous seek?
232
+ this.smoothSeeker.seek(this.smoothSeeker.end);
233
+ this.smoothSeeker = null;
234
+ }
235
+ if (duration === 0) {
236
+ this.seekDirect(toPosition);
237
+ return;
238
+ }
239
+ const seeker = new Timeline(true);
240
+ this.smoothSeeker = seeker;
241
+ seeker.range(0, duration).ease(easer).tween(this.currentTime, toPosition).listen(v => this.seekDirect(v));
242
+ return new Promise(r => seeker.end.listen(() => r()));
243
+ }
244
+ seekDirect(toPosition) {
245
+ const fromPosition = this._currentTime;
246
+ if (toPosition === fromPosition)
247
+ return;
248
+ const loopingTo = this.getWrappedPosition(toPosition);
249
+ const loopingFrom = this.getWrappedPosition(fromPosition);
250
+ let virtualFrom = loopingFrom;
251
+ let virtualTo = loopingTo;
252
+ const direction = toPosition > fromPosition ? 1 : -1;
253
+ if (direction !== this.currentSortDirection)
254
+ this.sortEntries(direction);
255
+ if (direction === 1 && loopingTo < loopingFrom) {
256
+ virtualFrom = loopingFrom - this._endPosition;
257
+ }
258
+ else if (direction === -1 && loopingTo > loopingFrom) {
259
+ virtualFrom = loopingFrom + this._endPosition;
260
+ }
261
+ this.seeking = true;
262
+ this._currentTime = virtualFrom;
263
+ try {
264
+ this.seekPoints(virtualTo);
265
+ this.seekRanges(virtualTo);
266
+ }
267
+ catch (e) {
268
+ this.pause();
269
+ throw e;
270
+ }
271
+ this._currentTime = toPosition;
272
+ this.positionHandlers.slice().forEach(h => h(toPosition));
273
+ this.seeking = false;
274
+ }
275
+ seekPoints(to) {
276
+ const from = this._currentTime;
277
+ const direction = to > from ? 1 : -1;
278
+ const pointsBetween = this.points.filter(direction > 0
279
+ ? p => p.position > from && p.position <= to
280
+ : p => p.position <= from && p.position > to);
281
+ pointsBetween.slice().forEach(p => {
282
+ this.seekRanges(p.position);
283
+ this._currentTime = p.position;
284
+ const eventData = {
285
+ direction
286
+ };
287
+ p.handlers.slice().forEach(h => h(eventData));
288
+ });
289
+ }
290
+ seekRanges(to) {
291
+ const fromTime = this._currentTime;
292
+ this.ranges.slice().forEach((range) => {
293
+ const { duration, position } = range;
294
+ const end = position + duration;
295
+ // filter ranges that overlap seeked range
296
+ if (Math.min(position, end) <= Math.max(to, fromTime)
297
+ && Math.min(to, fromTime) <= Math.max(position, end)) {
298
+ let progress = (0, utils_1.clamp)((to - range.position) / range.duration, 0, 1);
299
+ range.handlers.slice().forEach(h => h(progress));
300
+ }
301
+ });
302
+ }
303
+ sortEntries(direction) {
304
+ this.currentSortDirection = direction;
305
+ this.points.sort(direction == 1
306
+ ? sortEvents
307
+ : sortReverse);
308
+ this.ranges.sort(direction == 1
309
+ ? sortTweens
310
+ : sortReverse);
311
+ }
312
+ play(fps = default_fps) {
313
+ if (this.interval !== null)
314
+ this.pause();
315
+ let previousTime = Date.now();
316
+ this.interval = setInterval(() => {
317
+ const newTime = Date.now();
318
+ const elapsed = newTime - previousTime;
319
+ previousTime = newTime;
320
+ let delta = elapsed * this.timeScale;
321
+ if (this._currentTime + delta <= this._endPosition) {
322
+ this.currentTime += delta;
323
+ return;
324
+ }
325
+ // overshot; perform endAction
326
+ if (this.endAction.type == EndAction.restart) {
327
+ const loopRange = this.endAction.at.to(this._endPosition);
328
+ const loopLen = loopRange.duration;
329
+ if (loopLen <= 0) {
330
+ const target = Math.min(this._currentTime + delta, this._endPosition);
331
+ this.seek(target);
332
+ return;
333
+ }
334
+ while (delta > 0) {
335
+ const distanceToEnd = this._endPosition - this._currentTime;
336
+ if (delta < distanceToEnd) {
337
+ this.seek(this._currentTime + delta);
338
+ return;
339
+ }
340
+ this.seek(this._endPosition);
341
+ delta -= distanceToEnd;
342
+ this.seek(this.endAction.at);
343
+ }
344
+ return;
345
+ }
346
+ if (this.endAction.type == EndAction.pause) {
347
+ this.seek(this._endPosition);
348
+ this.pause();
349
+ return;
350
+ }
351
+ this.currentTime += delta;
352
+ }, 1000 / fps);
353
+ }
354
+ pause() {
355
+ if (this.interval === null)
356
+ return;
357
+ clearInterval(this.interval);
358
+ this.interval = null;
359
+ }
360
+ step(delta = 1) {
361
+ this.currentTime += delta * this.timeScale;
362
+ }
363
+ tween(start, durationOrToPoint, apply, from, to, easer) {
364
+ const startPosition = typeof start == "number"
365
+ ? start
366
+ : start.position;
367
+ const duration = typeof durationOrToPoint == "number"
368
+ ? durationOrToPoint
369
+ : (durationOrToPoint.position - startPosition);
370
+ this.range(startPosition, duration).ease(easer).tween(from, to).listen(apply);
371
+ return this.createChainingInterface(startPosition + duration);
372
+ }
373
+ at(position, action, reverse) {
374
+ const point = typeof position == "number" ? this.point(position) : position;
375
+ if (reverse === true)
376
+ reverse = action;
377
+ if (action)
378
+ point.listen(reverse
379
+ ? (event => event.direction < 0 ? reverse() : action)
380
+ : action);
381
+ return this.createChainingInterface(point.position);
382
+ }
383
+ createChainingInterface(position) {
384
+ return {
385
+ thenTween: (duration, apply, from = 0, to = 1, easer) => {
386
+ return this.tween(position, duration, apply, from, to, easer);
387
+ },
388
+ then: (action) => this.at(position, action),
389
+ thenWait: (delay) => {
390
+ this.point(position + delay);
391
+ return this.createChainingInterface(position + delay);
392
+ },
393
+ end: this.point(position),
394
+ };
395
+ }
396
+ /**
397
+ * @deprecated use `timeline.currentTime`
398
+ */
399
+ get position() {
400
+ return this._currentTime;
401
+ }
402
+ }
403
+ exports.Timeline = Timeline;
404
+ const sortEvents = (a, b) => {
405
+ return a.position - b.position;
406
+ };
407
+ const sortTweens = (a, b) => {
408
+ return (a.position + a.duration) - (b.position + b.duration);
409
+ };
410
+ const sortReverse = (a, b) => {
411
+ if (a.position == b.position)
412
+ return 1;
413
+ return b.position - a.position;
414
+ };
@@ -0,0 +1,8 @@
1
+ /** @internal */
2
+ export type Tweenable = number | number[] | string | Blendable;
3
+ /** @internal */
4
+ export interface Blendable {
5
+ blend(target: this, progress: number): this;
6
+ }
7
+ /** @internal */
8
+ export declare function tweenValue<T extends Tweenable>(from: T, to: T, progress: number): T;
@@ -0,0 +1,154 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tweenValue = tweenValue;
4
+ const utils_1 = require("./utils");
5
+ /** @internal */
6
+ function tweenValue(from, to, progress) {
7
+ if (Array.isArray(from)) {
8
+ const toArr = to;
9
+ if (from.length != toArr.length)
10
+ throw new Error("Array size mismatch");
11
+ return from.map((v, i) => tweenValue(v, toArr[i], progress));
12
+ }
13
+ if (typeof from == "string") {
14
+ return blendStrings(from, to, progress);
15
+ }
16
+ if (typeof from == "number") {
17
+ return blendNumbers(from, to, progress);
18
+ }
19
+ if (from && typeof from == "object") {
20
+ if ("blend" in from) {
21
+ const blendableSource = from;
22
+ return blendableSource.blend(to, progress);
23
+ }
24
+ }
25
+ throw new Error("Value not recognised as Tweenable");
26
+ }
27
+ function blendNumbers(from, to, progress) {
28
+ return from + progress * (to - from);
29
+ }
30
+ function mergeStrings(from, to, progress) {
31
+ const p = Math.min(Math.max(progress, 0), 1);
32
+ // Fast‑path: identical strings or one is empty
33
+ if (from === to)
34
+ return from;
35
+ if (!from)
36
+ return to;
37
+ if (!to)
38
+ return from;
39
+ const split = (s) => {
40
+ // Prefer Intl.Segmenter if available (Node ≥ 14, modern browsers)
41
+ if (typeof Intl !== "undefined" && Intl.Segmenter) {
42
+ const seg = new Intl.Segmenter(undefined, { granularity: "grapheme" });
43
+ return Array.from(seg.segment(s), (seg) => seg.segment);
44
+ }
45
+ // Fallback regex (covers surrogate pairs & combining marks)
46
+ const graphemeRegex = /(\P{Mark}\p{Mark}*|[\uD800-\uDBFF][\uDC00-\uDFFF])/gu;
47
+ return s.match(graphemeRegex) ?? Array.from(s);
48
+ };
49
+ const a = split(from);
50
+ const b = split(to);
51
+ const maxLen = Math.max(a.length, b.length);
52
+ const pad = (arr) => {
53
+ const diff = maxLen - arr.length;
54
+ if (diff <= 0)
55
+ return arr;
56
+ return arr.concat(Array(diff).fill(" "));
57
+ };
58
+ const fromP = pad(a);
59
+ const toP = pad(b);
60
+ const replaceCount = Math.floor(p * maxLen);
61
+ const result = new Array(maxLen);
62
+ for (let i = 0; i < maxLen; ++i) {
63
+ result[i] = i < replaceCount ? toP[i] : fromP[i];
64
+ }
65
+ while (result.length && result[result.length - 1] === " ") {
66
+ result.pop();
67
+ }
68
+ return result.join("");
69
+ }
70
+ function parseColour(code) {
71
+ if (code.length < 2 || !code.startsWith("#"))
72
+ throw new Error("Invalid colour");
73
+ let rawHex = code.substring(1);
74
+ if (rawHex.length == 1)
75
+ rawHex = rawHex + rawHex + rawHex;
76
+ if (rawHex.length == 2) {
77
+ const white = rawHex[0];
78
+ const alpha = rawHex[1];
79
+ rawHex = white + white + white + alpha;
80
+ }
81
+ if (rawHex.length == 3)
82
+ rawHex += "f";
83
+ if (rawHex.length == 4)
84
+ rawHex = rawHex.replace(/./g, c => c + c);
85
+ if (rawHex.length == 6)
86
+ rawHex += "ff";
87
+ return [...rawHex.matchAll(/../g)].map(hex => parseInt(hex[0], 16));
88
+ }
89
+ function blendColours(from, to, bias) {
90
+ const fromColour = parseColour(from);
91
+ const toColour = parseColour(to);
92
+ const blended = fromColour.map((val, i) => (0, utils_1.clamp)(blendNumbers(val, toColour[i], bias), 0, 255));
93
+ return ("#" + blended.map(n => Math.round(n).toString(16).padStart(2, "0")).join("")).replace(/ff$/, "");
94
+ }
95
+ const tweenableTokenRegex = /(#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})\b|[-+]?\d*\.?\d+(?:[eE][-+]?\d+)?)/g;
96
+ function blendStrings(from, to, progress) {
97
+ if (from === to || progress === 0)
98
+ return from;
99
+ const tokenise = (s) => {
100
+ const chunks = [];
101
+ let lastIdx = 0;
102
+ let m;
103
+ while ((m = tweenableTokenRegex.exec(s))) {
104
+ const token = m[0];
105
+ const prefix = s.slice(lastIdx, m.index); // literal before token
106
+ chunks.push({ prefix, token });
107
+ lastIdx = m.index + token.length;
108
+ }
109
+ // trailing literal after the last token – stored as a final chunk
110
+ // with an empty token (so the consumer can easily append it)
111
+ const tail = s.slice(lastIdx);
112
+ if (tail.length) {
113
+ chunks.push({ prefix: tail, token: "" });
114
+ }
115
+ return chunks;
116
+ };
117
+ const fromChunks = tokenise(from);
118
+ const toChunks = tokenise(to);
119
+ const tokenCount = fromChunks.filter(c => c.token).length;
120
+ if (tokenCount !== toChunks.filter(c => c.token).length) {
121
+ return mergeStrings(from, to, progress);
122
+ }
123
+ let result = "";
124
+ for (let i = 0, j = 0; i < fromChunks.length && j < toChunks.length;) {
125
+ const f = fromChunks[i];
126
+ const t = toChunks[j];
127
+ // The *prefix* (the text before the token) must be the same.
128
+ if (f.prefix !== t.prefix) {
129
+ return mergeStrings(from, to, progress);
130
+ }
131
+ // Append the unchanged prefix.
132
+ result += f.prefix;
133
+ // If we are at the *trailing* chunk (no token), just break.
134
+ if (!f.token && !t.token) {
135
+ break;
136
+ }
137
+ // Blend the token according to its kind.
138
+ let blended;
139
+ if (f.token.startsWith("#")) {
140
+ blended = blendColours(f.token, t.token, progress);
141
+ }
142
+ else {
143
+ const fNum = parseFloat(f.token);
144
+ const tNum = parseFloat(t.token);
145
+ const blendedNum = blendNumbers(fNum, tNum, progress);
146
+ blended = blendedNum.toString();
147
+ }
148
+ result += blended;
149
+ // Advance both pointers.
150
+ i++;
151
+ j++;
152
+ }
153
+ return result;
154
+ }
@@ -0,0 +1,4 @@
1
+ /** @internal */
2
+ export declare const clamp: (value: number, min: number, max: number) => number;
3
+ /** @internal */
4
+ export type Widen<T> = T extends number ? number : T extends string ? string : T;
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.clamp = void 0;
4
+ /** @internal */
5
+ const clamp = (value, min, max) => Math.min(Math.max(value, min), max);
6
+ exports.clamp = clamp;
package/package.json CHANGED
@@ -1,12 +1,21 @@
1
1
  {
2
2
  "name": "@xtia/timeline",
3
- "version": "1.0.0",
3
+ "version": "1.0.2",
4
4
  "repository": {
5
5
  "url": "https://github.com/tiadrop/timeline",
6
6
  "type": "github"
7
7
  },
8
- "description": "A generalpurpose, environment-agnostic choreography engine",
9
- "main": "index.js",
8
+ "description": "A general-purpose, environment-agnostic choreography engine",
9
+ "sideEffects": false,
10
+ "types": "./index.d.ts",
11
+ "main": "./index.js",
12
+ "exports": {
13
+ ".": {
14
+ "types": "./index.d.ts",
15
+ "default": "./index.js"
16
+ },
17
+ "./internal/*": null
18
+ },
10
19
  "scripts": {
11
20
  "prepublishOnly": "cp ../README.md .",
12
21
  "postpublish": "rm README.md"