@wardic/core 1.0.0-rc.9 → 1.0.0

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.
Files changed (63) hide show
  1. package/dist/Batch.d.ts +244 -0
  2. package/dist/Batch.d.ts.map +1 -0
  3. package/dist/Batch.js +1862 -0
  4. package/dist/Batch.js.map +1 -0
  5. package/dist/DragRecognizer.d.ts +16 -1
  6. package/dist/DragRecognizer.d.ts.map +1 -1
  7. package/dist/DragRecognizer.js +87 -1
  8. package/dist/DragRecognizer.js.map +1 -1
  9. package/dist/InputSource.d.ts +21 -0
  10. package/dist/InputSource.d.ts.map +1 -1
  11. package/dist/InputSource.js.map +1 -1
  12. package/dist/Machine.d.ts.map +1 -1
  13. package/dist/Machine.js +4 -67
  14. package/dist/Machine.js.map +1 -1
  15. package/dist/Playback.d.ts.map +1 -1
  16. package/dist/Playback.js +7 -6
  17. package/dist/Playback.js.map +1 -1
  18. package/dist/Recognizer.d.ts +35 -2
  19. package/dist/Recognizer.d.ts.map +1 -1
  20. package/dist/Recognizer.js +211 -16
  21. package/dist/Recognizer.js.map +1 -1
  22. package/dist/Reorder.d.ts +3 -3
  23. package/dist/Reorder.d.ts.map +1 -1
  24. package/dist/Reorder.js +28 -14
  25. package/dist/Reorder.js.map +1 -1
  26. package/dist/Sequence.d.ts +7 -2
  27. package/dist/Sequence.d.ts.map +1 -1
  28. package/dist/Sequence.js +8 -2
  29. package/dist/Sequence.js.map +1 -1
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js +1 -0
  33. package/dist/index.js.map +1 -1
  34. package/dist/internal/keyframes.d.ts +40 -0
  35. package/dist/internal/keyframes.d.ts.map +1 -0
  36. package/dist/internal/keyframes.js +70 -0
  37. package/dist/internal/keyframes.js.map +1 -0
  38. package/dist/internal/playhead.d.ts +16 -0
  39. package/dist/internal/playhead.d.ts.map +1 -0
  40. package/dist/internal/playhead.js +6 -0
  41. package/dist/internal/playhead.js.map +1 -0
  42. package/dist/internal/stepper.d.ts +6 -0
  43. package/dist/internal/stepper.d.ts.map +1 -1
  44. package/dist/internal/stepper.js +16 -0
  45. package/dist/internal/stepper.js.map +1 -1
  46. package/dist/internal/watch.d.ts +6 -0
  47. package/dist/internal/watch.d.ts.map +1 -1
  48. package/dist/internal/watch.js +7 -0
  49. package/dist/internal/watch.js.map +1 -1
  50. package/package.json +2 -2
  51. package/src/Batch.ts +2128 -0
  52. package/src/DragRecognizer.ts +97 -2
  53. package/src/InputSource.ts +25 -0
  54. package/src/Machine.ts +4 -93
  55. package/src/Playback.ts +7 -13
  56. package/src/Recognizer.ts +242 -17
  57. package/src/Reorder.ts +39 -18
  58. package/src/Sequence.ts +20 -5
  59. package/src/index.ts +1 -0
  60. package/src/internal/keyframes.ts +98 -0
  61. package/src/internal/playhead.ts +19 -0
  62. package/src/internal/stepper.ts +16 -0
  63. package/src/internal/watch.ts +15 -0
package/src/Recognizer.ts CHANGED
@@ -26,13 +26,15 @@ import * as Predicate from "effect/Predicate"
26
26
  import type * as Scope from "effect/Scope"
27
27
  import * as Stream from "effect/Stream"
28
28
  import * as UndefinedOr from "effect/UndefinedOr"
29
+ import * as Iter from "effect/Iterable"
29
30
  import * as DragActivity from "./DragActivity.ts"
30
31
  import * as InputFeed from "./InputFeed.ts"
31
32
  import * as InputSource from "./InputSource.ts"
32
33
  import * as PressClaims from "./PressClaims.ts"
33
34
  import * as Probe from "./Probe.ts"
34
35
  import { tracedScoped } from "./internal/tracing.ts"
35
- import { streamOf, watchFeed } from "./internal/watch.ts"
36
+ import { amongFeed, streamOf, watchFeed } from "./internal/watch.ts"
37
+ import type { AmongHandlers } from "./internal/watch.ts"
36
38
 
37
39
  /**
38
40
  * One state recognizer's fold: a start state, a pure step per event, and the boolean
@@ -207,6 +209,89 @@ export const watchHover: (target: unknown, handlers: HoverHandlers) => Effect.Ef
207
209
  yield* watchFeed("wardic.hover", {}, input.pointer(target), handle, handlers)
208
210
  })
209
211
 
212
+ // In internal/watch.ts, shared with DragRecognizer's watch over many members (#712).
213
+ export type { AmongHandlers } from "./internal/watch.ts"
214
+
215
+ /**
216
+ * Each target's state in a watch over many targets: held weakly by a target that's an object, so a
217
+ * target gone mid-gesture (an element removed under the pointer, which hears no leave) keeps nothing.
218
+ */
219
+ interface TargetStates<S> {
220
+ readonly get: (target: unknown) => S | undefined
221
+ readonly set: (target: unknown, state: S) => void
222
+ readonly delete: (target: unknown) => void
223
+ }
224
+
225
+ /** A {@link TargetStates}: a `WeakMap` for objects, a `Map` for the rest (a test's names). */
226
+ // Per event over a target: statements.
227
+ const targetStates = <S>(): TargetStates<S> => {
228
+ const objects = new WeakMap<object, S>()
229
+ const others = new Map<unknown, S>()
230
+ return {
231
+ get: (target) => {
232
+ if (Predicate.isObject(target)) return objects.get(target)
233
+ return others.get(target)
234
+ },
235
+ set: (target, state) => {
236
+ if (Predicate.isObject(target)) {
237
+ objects.set(target, state)
238
+ return
239
+ }
240
+ others.set(target, state)
241
+ },
242
+ delete: (target) => {
243
+ if (Predicate.isObject(target)) {
244
+ objects.delete(target)
245
+ return
246
+ }
247
+ others.delete(target)
248
+ },
249
+ }
250
+ }
251
+
252
+ /** Whether a hover's state is at rest: no pointer over its target or holding it, so it needs none kept. */
253
+ const hoverAtRest = (state: HoverState): boolean => {
254
+ if (state.inside) return false
255
+ if (state.deferred) return false
256
+ return Predicate.isNull(state.held)
257
+ }
258
+
259
+ /**
260
+ * Watches hover on many targets from one source while the Scope is open: `memberOf(node)` names the
261
+ * target a node is, `Option.none()` for none, and `handlers.on` hears each target's starts and ends, with
262
+ * it, as `watchHover` would tell it of its own events. A target a pointer has never touched keeps
263
+ * nothing, and one that's an object is held weakly.
264
+ *
265
+ * @example
266
+ * yield* Recognizer.watchHoverAmong((node) => Option.fromUndefinedOr(tiles.get(node)), {
267
+ * on: (tile, { active }) => lift(tile, active),
268
+ * })
269
+ */
270
+ // #665's PR 5 (Q56): a Batch's members, over the InputSource's `pointerAmong`. Hover's fold, a state a
271
+ // target, made at its first event and dropped at rest, held weakly. Tier 2, for bindings.
272
+ export const watchHoverAmong: (memberOf: (node: unknown) => Option.Option<unknown>, handlers: AmongHandlers<Edge>) => Effect.Effect<void, never, Scope.Scope | InputSource.InputSource> = /*#__PURE__*/ Effect.fnUntraced(
273
+ function* (memberOf: (node: unknown) => Option.Option<unknown>, handlers: AmongHandlers<Edge>) {
274
+ const input = yield* InputSource.InputSource
275
+ const activity = yield* DragActivity.DragActivity
276
+ const among = yield* amongFeed(input.pointerAmong, "pointerAmong")
277
+ const fold = hoverFold(activity)
278
+ const handle = (): ((told: InputSource.TargetEvent<InputSource.PointerLikeEvent>) => boolean) => {
279
+ const states = targetStates<HoverState>()
280
+ // Per pointer event over a target: statements.
281
+ return ({ target, event }) => {
282
+ const was = UndefinedOr.match(states.get(target), { onUndefined: () => noHover, onDefined: identity })
283
+ const next = fold.step(was, event)
284
+ states.set(target, next)
285
+ if (hoverAtRest(next)) states.delete(target)
286
+ const active = fold.active(next)
287
+ if (active !== fold.active(was)) handlers.on(target, { active, event })
288
+ return true
289
+ }
290
+ }
291
+ yield* watchFeed("wardic.hover", { among: true }, among(memberOf), handle, handlers)
292
+ },
293
+ )
294
+
210
295
  /** Whether `event` moves a pointer over the target while `state`'s hover is on (#397). */
211
296
  const movesOver = (state: HoverState, event: InputSource.PointerLikeEvent): boolean =>
212
297
  Bool.and(Bool.and(state.inside, event.type === "move"), Bool.and(event.onTarget, event.kind !== "touch"))
@@ -375,10 +460,12 @@ export type PressEvent =
375
460
  export interface PressOptions {
376
461
  /**
377
462
  * `false`: no key presses it, for a target whose Enter and Space are someone else's: a Reorder item's,
378
- * which lift it. Default `true`.
463
+ * which lift it. A function is read at each key's down, so a target whose keys are someone else's only
464
+ * some of the time (a Batch Reorder group's item, while the keyboard reorder is on) presses from its next
465
+ * key once it says so; a key's up always ends the press its down started. Default `true`.
379
466
  */
380
- // #427, ADR-0037: **Keyboard presses**.
381
- readonly keys?: boolean | undefined
467
+ // #427, ADR-0037: **Keyboard presses**; a function, #712 (Q32).
468
+ readonly keys?: boolean | LazyArg<boolean> | undefined
382
469
  /**
383
470
  * Whether its presses reach its pressable ancestors, as Motion's `propagate.tap`, read at each press's
384
471
  * start. `false` claims the down or the key it starts from, so no ancestor's press starts from it.
@@ -388,14 +475,52 @@ export interface PressOptions {
388
475
  readonly propagate?: boolean | LazyArg<boolean> | undefined
389
476
  }
390
477
 
391
- /** Whether a press with `options` propagates now: its `propagate`, read now, else `true`. */
392
- const propagatesOf = (options: PressOptions | undefined): LazyArg<boolean> => {
393
- const propagate = UndefinedOr.map(options, (o) => o.propagate)
394
- if (Predicate.isUndefined(propagate)) return constTrue
395
- if (Predicate.isBoolean(propagate)) return constant(propagate)
396
- return propagate
478
+ /** Whether keys can press a target with `options`: its `keys`, unless `false`; a function's may, from key to key. */
479
+ const keysPressOf = (options: PressOptions | undefined): boolean => UndefinedOr.match(options, { onUndefined: constTrue, onDefined: (o) => o.keys !== false })
480
+
481
+ /** An option given as a flag or as a function of now, as a function: `true` when it's left out. */
482
+ const flagNowOf = (given: boolean | LazyArg<boolean> | undefined): LazyArg<boolean> => {
483
+ if (Predicate.isUndefined(given)) return constTrue
484
+ if (Predicate.isBoolean(given)) return constant(given)
485
+ return given
486
+ }
487
+
488
+ /** Whether keys press a target with `options` now: its `keys`, a function's read now, else `true`. */
489
+ const keysOnOf = (options: PressOptions | undefined): LazyArg<boolean> => flagNowOf(UndefinedOr.map(options, (o) => o.keys))
490
+
491
+ /**
492
+ * `handle` for the keys a target's `keys` lets press it now (#712, Q32): a key's down while they're off is
493
+ * left to the page, unstepped; a key's up is always stepped, so a press its down started ends.
494
+ */
495
+ const whileKeysOn = (keysOn: LazyArg<boolean>) => (handle: (event: InputSource.KeyboardLikeEvent) => boolean) => (event: InputSource.KeyboardLikeEvent): boolean => {
496
+ if (event.type !== "down") return handle(event)
497
+ if (keysOn()) return handle(event)
498
+ return true
499
+ }
500
+
501
+ /**
502
+ * A press's state stepped from `was` to `now` by `event`: when it turned, its edge, `out`'s, marked by
503
+ * `taken` and told `on`; nothing when it didn't.
504
+ */
505
+ // Per press event: statements.
506
+ const tellPress = <Ev>(
507
+ was: PressState,
508
+ now: PressState,
509
+ event: Ev,
510
+ out: (ended: PressState, e: Ev, active: boolean) => PressEvent,
511
+ taken: (e: Ev, told: PressEvent) => void,
512
+ on: (told: PressEvent) => void,
513
+ ): void => {
514
+ const active = isPressed(now)
515
+ if (active === isPressed(was)) return
516
+ const told = out(now, event, active)
517
+ taken(event, told)
518
+ on(told)
397
519
  }
398
520
 
521
+ /** Whether a press with `options` propagates now: its `propagate`, read now, else `true`. */
522
+ const propagatesOf = (options: PressOptions | undefined): LazyArg<boolean> => flagNowOf(UndefinedOr.map(options, (o) => o.propagate))
523
+
399
524
  /**
400
525
  * `press`'s starts and ends with how each began or ended, as Motion's `onTapStart`, `onTap` and
401
526
  * `onTapCancel`, and a press a drag took over, which Motion tells as neither.
@@ -428,7 +553,7 @@ export const watchPress: (
428
553
  const input = yield* InputSource.InputSource
429
554
  const activity = yield* DragActivity.DragActivity
430
555
  const claims = yield* PressClaims.PressClaims
431
- const keys = UndefinedOr.match(options, { onUndefined: constTrue, onDefined: (o) => o.keys !== false })
556
+ const keys = keysPressOf(options)
432
557
  const propagates = propagatesOf(options)
433
558
  // A press's start marks what it started from (#439): claimed when it doesn't propagate.
434
559
  const marking = (event: PressClaims.Markable, told: PressEvent): void => {
@@ -457,11 +582,7 @@ export const watchPress: (
457
582
  const was = MutableRef.get(state)
458
583
  const now = next(was, event)
459
584
  MutableRef.set(state, now)
460
- const active = isPressed(now)
461
- if (active === isPressed(was)) return true
462
- const told = out(now, event, active)
463
- taken(event, told)
464
- handlers.on(told)
585
+ tellPress(was, now, event, out, taken, handlers.on)
465
586
  return true
466
587
  }
467
588
  yield* InputFeed.watchWith(input.pointer(target), step(pointerStep(activity, claims, target), pointerPressOf, marking), watching)
@@ -470,7 +591,8 @@ export const watchPress: (
470
591
  marking(event, told)
471
592
  takeSpace(event, told)
472
593
  }
473
- const onKey = step(keyStep(activity, claims, target), keyPressOf, keyTaken)
594
+ const keyed = whileKeysOn(keysOnOf(options))
595
+ const onKey = () => keyed(step(keyStep(activity, claims, target), keyPressOf, keyTaken)())
474
596
  const onFocus = step(focusStep, blurPressOf, constVoid)
475
597
  if (Predicate.isUndefined(focusWithin)) {
476
598
  yield* InputFeed.watchWith(input.keyboard(target), onKey, watching)
@@ -507,6 +629,109 @@ const feedsWatched = (keys: boolean, keysOnFocus: boolean): number => {
507
629
  return 3
508
630
  }
509
631
 
632
+ /**
633
+ * Watches presses on many targets from one source while the Scope is open: `memberOf(node)` names the
634
+ * target a node is, `Option.none()` for none, and `handlers.on` hears each target's starts and ends, with
635
+ * it, as `watchPress` would tell it of its own events. A focused target's Enter and Space press it, its
636
+ * keys heard only while focus is within it, through the InputSource's `focusAmong`, which tells a focus
637
+ * already within one as it starts; without one, only pointers press. A target with no press held keeps
638
+ * nothing.
639
+ *
640
+ * @example
641
+ * yield* Recognizer.watchPressAmong((node) => Option.fromUndefinedOr(tiles.get(node)), {
642
+ * on: (tile, { phase }) => {
643
+ * if (phase === "tap") open(tile)
644
+ * },
645
+ * })
646
+ */
647
+ // #665's PR 5 (Q56, Q57): a Batch's members, over `pointerAmong` and `focusAmong`. Press's steps, a state a
648
+ // target, made at its first event and dropped once no press is held; its **Press claims** marked per
649
+ // target (#439); each focused target's keys a switch of its own (#460). Tier 2, for bindings.
650
+ export const watchPressAmong: (
651
+ memberOf: (node: unknown) => Option.Option<unknown>,
652
+ handlers: AmongHandlers<PressEvent>,
653
+ options?: PressOptions,
654
+ ) => Effect.Effect<void, never, Scope.Scope | InputSource.InputSource> = /*#__PURE__*/ Effect.fnUntraced(
655
+ function* (memberOf: (node: unknown) => Option.Option<unknown>, handlers: AmongHandlers<PressEvent>, options?: PressOptions) {
656
+ yield* Effect.logDebug("wardic.press: watch")
657
+ const input = yield* InputSource.InputSource
658
+ const activity = yield* DragActivity.DragActivity
659
+ const claims = yield* PressClaims.PressClaims
660
+ const pointer = yield* amongFeed(input.pointerAmong, "pointerAmong")
661
+ const focusAmong = input.focusAmong
662
+ const keys = Bool.and(keysPressOf(options), Predicate.isNotUndefined(focusAmong))
663
+ const keyed = whileKeysOn(keysOnOf(options))
664
+ const propagates = propagatesOf(options)
665
+ // Each target with a press held, and each focused target's keys.
666
+ const states = targetStates<PressState>()
667
+ const keysOf = new Map<unknown, InputFeed.Switch>()
668
+ // Its pointer, and with keys its focus: each one's end counted for `onEnd`.
669
+ const feeds = MutableRef.make(feedsWatched(keys, true))
670
+ const onEnd = (): void => {
671
+ MutableRef.set(feeds, MutableRef.get(feeds) - 1)
672
+ if (MutableRef.get(feeds) === 0) UndefinedOr.map(handlers.onEnd, (end) => end())
673
+ }
674
+ // Told once, as the watch stops: with its pointer's.
675
+ const onStop = (): void => {
676
+ Iter.forEach(keysOf, ([, keysNow]) => keysNow.close())
677
+ keysOf.clear()
678
+ UndefinedOr.map(handlers.onStop, (stop) => stop())
679
+ }
680
+ /** `target`'s event stepped by `next`: its edge told, and its state kept while a press is held. */
681
+ // Per event over a target: statements.
682
+ const stepOn = <Ev>(target: unknown, event: Ev, next: (s: PressState, e: Ev) => PressState, out: (ended: PressState, e: Ev, active: boolean) => PressEvent, taken: (e: Ev, told: PressEvent) => void): void => {
683
+ const was = UndefinedOr.match(states.get(target), { onUndefined: () => noPress, onDefined: identity })
684
+ const now = next(was, event)
685
+ states.set(target, now)
686
+ if (Bool.not(isPressed(now))) states.delete(target)
687
+ tellPress(was, now, event, out, taken, (told) => handlers.on(target, told))
688
+ }
689
+ /** A press's start on `target` marks what it started from (#439): claimed when it doesn't propagate. */
690
+ const markingOn = (target: unknown) => (event: PressClaims.Markable, told: PressEvent): void => {
691
+ if (told.phase === "start") claims.mark(event, target, Bool.not(propagates()))
692
+ }
693
+ const onPointer = (): ((told: InputSource.TargetEvent<InputSource.PointerLikeEvent>) => boolean) => ({ target, event }) => {
694
+ stepOn(target, event, pointerStep(activity, claims, target), pointerPressOf, markingOn(target))
695
+ return true
696
+ }
697
+ yield* InputFeed.watchWith(pointer(memberOf), onPointer, { onDefect: handlers.onDefect, onEnd, onStop })
698
+ if (Bool.not(keys)) return
699
+ if (Predicate.isUndefined(focusAmong)) return
700
+ const closeKeys = (target: unknown): void => {
701
+ UndefinedOr.map(keysOf.get(target), (keysNow) => keysNow.close())
702
+ keysOf.delete(target)
703
+ }
704
+ // A target's keys only while focus is within it (#460), from its focus to its blur.
705
+ const openKeys = (target: unknown): void => {
706
+ if (keysOf.has(target)) return
707
+ const marking = markingOn(target)
708
+ const keyTaken = (event: InputSource.KeyboardLikeEvent, told: PressEvent): void => {
709
+ marking(event, told)
710
+ takeSpace(event, told)
711
+ }
712
+ const keysNow = InputFeed.switched(
713
+ input.keyboard(target),
714
+ keyed((event) => {
715
+ stepOn(target, event, keyStep(activity, claims, target), keyPressOf, keyTaken)
716
+ return true
717
+ }),
718
+ handlers.onDefect,
719
+ )
720
+ keysOf.set(target, keysNow)
721
+ keysNow.open()
722
+ }
723
+ const onFocus = (): ((told: InputSource.TargetEvent<InputSource.FocusLikeEvent>) => boolean) => ({ target, event }) => {
724
+ if (event.type === "focus") openKeys(target)
725
+ // A blur first ends a Keyboard press it cancels, then lets the keys go.
726
+ stepOn(target, event, focusStep, blurPressOf, constVoid)
727
+ if (event.type === "blur") closeKeys(target)
728
+ return true
729
+ }
730
+ yield* InputFeed.watchWith(focusAmong(memberOf), onFocus, { onDefect: handlers.onDefect, onEnd })
731
+ },
732
+ (self) => tracedScoped(self, "wardic.press"),
733
+ )
734
+
510
735
  /** A pointer's press edge, with how it began or ended. */
511
736
  const pointerPressOf = (next: PressState, event: InputSource.PointerLikeEvent, active: boolean): PressEvent => ({
512
737
  phase: Bool.match(active, { onTrue: (): PressPhase => "start", onFalse: () => endOf(next, event) }),
package/src/Reorder.ts CHANGED
@@ -24,7 +24,7 @@
24
24
  import * as Arr from "effect/Array"
25
25
  import * as Bool from "effect/Boolean"
26
26
  import * as Equivalence from "effect/Equivalence"
27
- import { constVoid, identity } from "effect/Function"
27
+ import { constFalse, constVoid, identity } from "effect/Function"
28
28
  import * as Inspectable from "effect/Inspectable"
29
29
  import * as Match from "effect/Match"
30
30
  import * as MutableRef from "effect/MutableRef"
@@ -275,27 +275,48 @@ const distanceToBox = (point: Point.Point, box: Box.Box): number => {
275
275
  return x * x + y * y
276
276
  }
277
277
 
278
- const isSeparated = (a: Box.Axis, b: Box.Axis): boolean => Bool.or(a.max <= b.min, b.max <= a.min)
278
+ /** The box that ends first on `axis`, by its index: `None` when no box's end there is a number. */
279
+ const firstToEnd = (layouts: ReadonlyArray<Box.Box>, axis: "x" | "y"): Option.Option<number> =>
280
+ Arr.reduce(layouts, Option.none<number>(), (first, box, i) =>
281
+ Option.match(first, {
282
+ onNone: () => Bool.match(Number.isNaN(box[axis].max), { onTrue: () => first, onFalse: () => Option.some(i) }),
283
+ onSome: (k) => Bool.match(box[axis].max < Arr.getUnsafe(layouts, k)[axis].max, { onTrue: () => Option.some(i), onFalse: () => first }),
284
+ }),
285
+ )
286
+
287
+ /**
288
+ * Whether some two of `layouts` are apart on `axis`: one ends at or before the other starts. Each box is
289
+ * compared with the one that ends first, which is enough: if `a` ends before `b` starts, so does that
290
+ * box, unless it's `b`, and then `a` is apart from it.
291
+ */
292
+ // #710: two passes over the boxes, nothing made per pair, where Motion compares every pair (quadratic
293
+ // for a column, where no two boxes are ever apart across).
294
+ const someApart = (layouts: ReadonlyArray<Box.Box>, axis: "x" | "y"): boolean =>
295
+ Option.match(firstToEnd(layouts, axis), {
296
+ onNone: constFalse,
297
+ onSome: (k) => {
298
+ const first = Arr.getUnsafe(layouts, k)[axis]
299
+ return Arr.some(layouts, (box, j) => Bool.and(j !== k, Bool.or(first.max <= box[axis].min, box[axis].max <= first.min)))
300
+ },
301
+ })
302
+
303
+ /** The axis two answers make: whether some two boxes are apart across, and down. Built once (#618). */
304
+ const axisOfApart = Match.type<{ readonly x: boolean; readonly y: boolean }>().pipe(
305
+ Match.when({ x: true, y: true }, (): Axis => "xy"),
306
+ Match.when({ x: true }, (): Axis => "x"),
307
+ Match.orElse((): Axis => "y"),
308
+ )
279
309
 
280
310
  /**
281
- * The axis a list's item boxes are laid out on, as Motion's `detectAxis`: `"x"` if some two don't
282
- * overlap across, `"y"` if some two don't overlap down, `"xy"` if both, a grid that wraps, and `"y"`
283
- * otherwise. It stops once it has found both.
311
+ * The axis a list's item boxes are laid out on, as Motion's `detectAxis` finds it: `"x"` if some two
312
+ * don't overlap across, `"y"` if some two don't overlap down, `"xy"` if both, a grid that wraps, and
313
+ * `"y"` otherwise.
284
314
  */
285
315
  // Motion's Reorder/utils/detect-axis.ts @ 16c61222c4166bbef5ff6ab0051192faa79fa8c8
286
- // (https://github.com/motiondivision/motion/blob/16c61222c4166bbef5ff6ab0051192faa79fa8c8/packages/framer-motion/src/components/Reorder/utils/detect-axis.ts),
287
- // ported. Tier 2 (ADR-0008).
288
- export const detectAxis = (layouts: ReadonlyArray<Box.Box>): Axis => {
289
- // Every unordered pair of boxes.
290
- const pairs = Arr.flatMap(layouts, (a, i) => Arr.map(Arr.drop(layouts, i + 1), (b) => [a, b] as const))
291
- const x = Arr.some(pairs, ([a, b]) => isSeparated(a.x, b.x))
292
- const y = Arr.some(pairs, ([a, b]) => isSeparated(a.y, b.y))
293
- return Match.value({ x, y }).pipe(
294
- Match.when({ x: true, y: true }, (): Axis => "xy"),
295
- Match.when({ x: true }, (): Axis => "x"),
296
- Match.orElse((): Axis => "y"),
297
- )
298
- }
316
+ // (https://github.com/motiondivision/motion/blob/16c61222c4166bbef5ff6ab0051192faa79fa8c8/packages/framer-motion/src/components/Reorder/utils/detect-axis.ts):
317
+ // its answers, in linear time (#710; CR12 holds them to its loop). Tier 2 (ADR-0008).
318
+ export const detectAxis = (layouts: ReadonlyArray<Box.Box>): Axis =>
319
+ axisOfApart({ x: someApart(layouts, "x"), y: someApart(layouts, "y") })
299
320
 
300
321
  // --- The group ----------------------------------------------------------------
301
322
 
package/src/Sequence.ts CHANGED
@@ -10,7 +10,8 @@
10
10
  * `repeat` below 20 is unrolled into stops. A spring through two stops or fewer becomes an easing
11
11
  * over the time it takes to rest, so a sequence is tweens all through.
12
12
  * - **A key's stops** are its Segments' in time order, a later Segment's replacing the stops it
13
- * overlaps. A Segment's single value starts from a `null`, the stop before it.
13
+ * overlaps. A Segment's single value starts from a `null`, the stop before it. A value can be a
14
+ * function of each subject's index and count, as its `delay` can, for subjects that go their own ways.
14
15
  *
15
16
  * @example
16
17
  * import * as Sequence from "@wardic/core/Sequence"
@@ -62,6 +63,13 @@ export interface Label {
62
63
  /** A Segment's delay (Motion's): seconds, or each subject's, by its index in the Segment and their count. */
63
64
  export type Delay = number | ((index: number, count: number) => number)
64
65
 
66
+ /**
67
+ * A key's value in a Segment: a value, its stops, or a function of each subject's index in the Segment
68
+ * and their count that gives one of them. Motion's are a value or stops.
69
+ */
70
+ // #665, Q38: a Batch's members, each through its own stops, in one Segment.
71
+ export type Value = Stop | ReadonlyArray<Stop> | ((index: number, count: number) => Stop | ReadonlyArray<Stop>)
72
+
65
73
  /** The `delay` a key's transition in a Segment takes, each subject's when it's a function. */
66
74
  interface Placing {
67
75
  readonly delay?: Delay | undefined
@@ -83,8 +91,8 @@ export type Transition =
83
91
  export interface Segment<S> {
84
92
  /** What it animates: elements, or anything a binding animates, such as a callback's value. */
85
93
  readonly subjects: ReadonlyArray<S>
86
- /** Each key's value, or its stops. */
87
- readonly target: Readonly<Record<string, Stop | ReadonlyArray<Stop>>>
94
+ /** Each key's value, or its stops, or a function of each subject's index and count that gives them. */
95
+ readonly target: Readonly<Record<string, Value>>
88
96
  /** Each key's transition, as the binding resolved it; a key with none runs on a 0.3 s `easeOut` tween. */
89
97
  readonly transitions: Readonly<Record<string, Transition>>
90
98
  /** Where it starts: after the Segment before, when left out. */
@@ -297,9 +305,16 @@ const repeated = (pass: Pass, transition: Transition, repeat: number): Pass => {
297
305
  }
298
306
  }
299
307
 
308
+ /** A key's value or stops for the subject at `index` of `count`: a function's, called for it. */
309
+ const valueOf = (given: Value, index: number, count: number): Stop | ReadonlyArray<Stop> =>
310
+ Bool.match(Predicate.isFunction(given), {
311
+ onTrue: () => (given as (index: number, count: number) => Stop | ReadonlyArray<Stop>)(index, count),
312
+ onFalse: () => given as Stop | ReadonlyArray<Stop>,
313
+ })
314
+
300
315
  /** A key's {@link Pass} in its Segment, for the subject at `index` of `count`. */
301
- const passOf = (given: Stop | ReadonlyArray<Stop>, transition: Transition, index: number, count: number): Pass => {
302
- const listed = stopsOf(given)
316
+ const passOf = (given: Value, transition: Transition, index: number, count: number): Pass => {
317
+ const listed = stopsOf(valueOf(given, index, count))
303
318
  const { ease, duration } = timingOf(transition, listed)
304
319
  // A single value starts from the stop before it.
305
320
  const stops = Bool.match(listed.length === 1, { onTrue: () => Arr.prepend(listed, null), onFalse: () => listed })
package/src/index.ts CHANGED
@@ -18,6 +18,7 @@ export * as Announcer from "./Announcer.ts"
18
18
  export * as Arc from "./Arc.ts"
19
19
  export * as AutoScroll from "./AutoScroll.ts"
20
20
  export * as BaseValue from "./BaseValue.ts"
21
+ export * as Batch from "./Batch.ts"
21
22
  export * as Box from "./Box.ts"
22
23
  export * as Clock from "./Clock.ts"
23
24
  export * as DefaultTransition from "./DefaultTransition.ts"
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Keyframes' and `animate`'s bags resolved (#429): the repeat modifiers, a run of repeats, and a
3
+ * keyframes bag's easings and times, checked once a bag. `Machine`'s `animate`, `keyframes` and
4
+ * `keyframesValues` read them, and a Batch's keyframes (#665), which step each member's key by hand.
5
+ * Not importable from outside core (`package.json`'s `"./internal/*": null`).
6
+ */
7
+ // Moved out of Machine.ts for the Batch (#665, Q36): Machine imports them back.
8
+ import * as Arr from "effect/Array"
9
+ import * as Bool from "effect/Boolean"
10
+ import * as Easing from "../Easing.ts"
11
+ import type { KeyframesOptions } from "../Machine.ts"
12
+ import { array, boolean, cachedResolver, field, finite, literals, nonEmptyArray, nonNegative, number, optionalField, refine, union } from "./options.ts"
13
+ import { EaseDefinition, type ResolvedRun, type ResolvedTween, resolvedTweenOf, TweenFields } from "./stepper.ts"
14
+
15
+ const NOT_REPEAT = "Expected a whole number of repeats, 0 or above, or Infinity"
16
+
17
+ /** A repeat count: a whole number, 0 or above, or `Infinity` to loop forever. */
18
+ const Repeat = refine(number, (n) => n === Infinity || (Number.isInteger(n) && n >= 0) || NOT_REPEAT)
19
+
20
+ /** The repeat modifiers (`Machine.Modifiers`), resolved: as given, defaults filled in. */
21
+ export interface ResolvedModifiers {
22
+ readonly repeat: number
23
+ readonly repeatDelay: number
24
+ readonly repeatType: "loop" | "reverse" | "mirror"
25
+ readonly reverse: boolean
26
+ }
27
+
28
+ /** The repeat modifiers' fields (#66): `animate`'s bag and `keyframes`' (#429) add them to a tween's. */
29
+ export const ModifierFields = {
30
+ repeat: field(Repeat, 0),
31
+ repeatDelay: field(nonNegative, 0),
32
+ repeatType: field(literals(["loop", "reverse", "mirror"]), "loop"),
33
+ reverse: field(boolean, false),
34
+ }
35
+
36
+ /** A decoded bag's run: its tween played `repeat + 1` times, with its tween's `delay` 0 (held outside, by `delay`). */
37
+ export const resolvedRunOf = (tween: ResolvedTween, modifiers: ResolvedModifiers): ResolvedRun => {
38
+ const cycle = tween.duration + modifiers.repeatDelay
39
+ return {
40
+ tween: { ...tween, delay: 0 },
41
+ repeats: modifiers.repeat,
42
+ gap: modifiers.repeatDelay,
43
+ cycle,
44
+ total: cycle * (modifiers.repeat + 1) - modifiers.repeatDelay,
45
+ reverses: modifiers.repeatType === "reverse",
46
+ mirrors: modifiers.repeatType === "mirror",
47
+ }
48
+ }
49
+
50
+ /** `keyframes`' bag resolved (#429): its run (its tween's `delay` 0), an easing per Interval, and each stop's place in time. */
51
+ export interface ResolvedKeyframes extends ResolvedModifiers {
52
+ readonly run: ResolvedRun
53
+ readonly delay: number
54
+ readonly seconds: number
55
+ readonly eases: Arr.NonEmptyReadonlyArray<Easing.Easing>
56
+ readonly times: ReadonlyArray<number> | undefined
57
+ }
58
+
59
+ /** One `ease` or several (#360): a list is an array whose first item isn't a number, which a bézier's is. */
60
+ const EaseOrList = union([EaseDefinition, nonEmptyArray(EaseDefinition)])
61
+
62
+ /** Whether `times` run from 0 to 1, none before the one ahead of it. */
63
+ const inOrder = (times: ReadonlyArray<number>): boolean => {
64
+ // The pairs only once every time is in range (#460, Q8).
65
+ if (!Arr.every(times, (time) => Bool.and(time >= 0, time <= 1))) return false
66
+ return Arr.every(Arr.zip(times, Arr.drop(times, 1)), ([before, after]) => after >= before)
67
+ }
68
+
69
+ const NOT_IN_ORDER = "Expected times from 0 to 1, in order"
70
+
71
+ /** Each stop's place in time (#429): numbers from 0 to 1, in order. */
72
+ const Times = refine(array(finite), (times) => inOrder(times) || NOT_IN_ORDER)
73
+
74
+ /**
75
+ * `keyframes`' bag (#66): a tween's fields, its `ease` one Definition or one per Interval (#360), its
76
+ * `times` and the repeat modifiers (#429), checked once a bag.
77
+ */
78
+ export const resolveKeyframes: (options: KeyframesOptions) => ResolvedKeyframes = cachedResolver(
79
+ { ...TweenFields, ...ModifierFields, ease: field(EaseOrList, Easing.linear), times: optionalField(Times) },
80
+ (decoded): ResolvedKeyframes => {
81
+ const list: Arr.NonEmptyReadonlyArray<Easing.Definition> = Bool.match(Bool.and(Arr.isArray(decoded.ease), Bool.not(Easing.isBezier(decoded.ease))), {
82
+ onTrue: () => decoded.ease as Arr.NonEmptyReadonlyArray<Easing.Definition>,
83
+ onFalse: (): Arr.NonEmptyReadonlyArray<Easing.Definition> => [decoded.ease as Easing.Definition],
84
+ })
85
+ const tween = resolvedTweenOf({ ...decoded, ease: list[0] })
86
+ return {
87
+ run: resolvedRunOf(tween, decoded),
88
+ delay: tween.delay,
89
+ seconds: tween.seconds,
90
+ eases: Arr.map(list, Easing.resolve),
91
+ times: decoded.times,
92
+ repeat: decoded.repeat,
93
+ repeatDelay: decoded.repeatDelay,
94
+ repeatType: decoded.repeatType,
95
+ reverse: decoded.reverse,
96
+ }
97
+ },
98
+ )
@@ -0,0 +1,19 @@
1
+ /**
2
+ * What a Playhead's drivers share (#433, #665): the Playhead as they write it, and a tick at its speed.
3
+ * `Playback`'s operations and driven machines use them, and so does a Batch's driven change.
4
+ */
5
+ import type * as Playback from "../Playback.ts"
6
+
7
+ /** A Playhead as its operations and its drivers write it. */
8
+ export interface Writable {
9
+ time: number
10
+ speed: number
11
+ paused: boolean
12
+ }
13
+
14
+ /** `head`, to write. */
15
+ export const writableOf = (head: Playback.Playhead): Writable => head as unknown as Writable
16
+
17
+ /** A tick of `dt` at `head`'s speed, at most `most` either way. */
18
+ // Per frame, per driver (ADR-0025): `Math.min` / `Math.max`.
19
+ export const tickOf = (head: Playback.Playhead, dt: number, most: number): number => Math.max(-most, Math.min(most, dt * head.speed))
@@ -242,6 +242,22 @@ export const intervalProgress = (time: number, stopTimes: ReadonlyArray<number>,
242
242
  return Scalar.clamp((time - start) / length, 0, 1)
243
243
  }
244
244
 
245
+ /**
246
+ * A keyframes run's value at `pass` (#429): the Interval its time is in, eased whole, between its two
247
+ * stops, read from last to first in a flipped pass. `Machine.keyframes` and a Batch's keyframes (#665)
248
+ * read it. Per frame (ADR-0025).
249
+ */
250
+ export const keyframeAt = (stops: ArrayLike<number>, stopTimes: ReadonlyArray<number>, eases: ReadonlyArray<Easing.Easing>, pass: Pass, duration: number): number => {
251
+ // Read before the ease runs: it's the app's code, and may step another run, which writes a shared pass (#618).
252
+ const flipped = pass.flipped
253
+ const time = timeIn(pass, duration)
254
+ const i = intervalAt(time, stopTimes)
255
+ const eased = eases[i % eases.length](intervalProgress(time, stopTimes, i))
256
+ const last = stops.length - 1
257
+ if (flipped) return Scalar.lerp(stops[last - i], stops[last - i - 1], eased)
258
+ return Scalar.lerp(stops[i], stops[i + 1], eased)
259
+ }
260
+
245
261
  // --- Decay -------------------------------------------------------------------
246
262
 
247
263
  export interface DecayState {
@@ -7,6 +7,7 @@ import { constFalse } from "effect/Function"
7
7
  import * as Queue from "effect/Queue"
8
8
  import type * as Scope from "effect/Scope"
9
9
  import * as Stream from "effect/Stream"
10
+ import * as UndefinedOr from "effect/UndefinedOr"
10
11
  import * as InputFeed from "../InputFeed.ts"
11
12
  import { tracedScoped } from "./tracing.ts"
12
13
 
@@ -53,3 +54,17 @@ export const streamOf = <A, R>(
53
54
  },
54
55
  })
55
56
  )
57
+
58
+ /** An InputSource's feed over many targets, or a defect naming it: an Environment without one can't watch many targets as one. */
59
+ // #665's PR 5; shared by the hover's, the press's and the drag's watches over many targets (#712).
60
+ export const amongFeed = <A>(feed: A | undefined, name: string): Effect.Effect<A> =>
61
+ UndefinedOr.match(feed, {
62
+ onUndefined: () => Effect.die(new Error(`wardic: the Environment's InputSource has no \`${name}\`, which a gesture over many targets needs`)),
63
+ onDefined: Effect.succeed,
64
+ })
65
+
66
+ /** A watch's handlers over many targets: `on`, each target's start and end, with the target. */
67
+ // #665's PR 5 (Q56).
68
+ export interface AmongHandlers<A> extends Pick<InputFeed.Handlers<never>, "onDefect" | "onEnd" | "onStop"> {
69
+ readonly on: (target: unknown, value: A) => void
70
+ }