diff --git a/CHANGELOG.md b/CHANGELOG.md index 35c9ccc16..16962da3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,7 @@ - Search a `ui/chat` transcript from Mod+F in a find bar that unfolds folded turns and reasoning, marks the matches in `ui.TextView` and reasoning, reveals each match clear of the bar and the composer and gives the focus back as it closes, with `core.FocusedRef` to read the focused view (#47 by @houko). - Add `desktop.QuickLook` and `desktop.CanQuickLook` to preview files in macOS's Quick Look panel (#370 by @houko). - Move the native field's selection with `nsgotest`'s `App.Select` under `-target` on macOS, Windows, Linux and the web, so the next edit acts on the selected range (#772 by @houko). +- Add `Scope.Tween` and TSX's `Animated.tween`, which step a number for what an animated value cannot reach, such as a figure counting up in a text; an `nsgotest` step waits for its end and reduced motion shows the end at once (#336 by @houko). - Add `TabStyle` and `IndicatorStyle` to `ui.Tabs` to restyle its tabs, the selected tab and the indicator (#958 by @houko). - Reload a TSX `` in place with the new script when `injectedJavaScriptBeforeContentLoaded` changes, as `core.WebView.InjectedJavaScriptBeforeContentFunc` does, rather than replacing the web view (#895 by @houko). - Keep partial borders above Apple backdrop, material and glass layers while leaving app children above the border (#935 by @houko). diff --git a/core/animated.go b/core/animated.go index 337e33c2f..b4b235971 100644 --- a/core/animated.go +++ b/core/animated.go @@ -259,26 +259,40 @@ func AtFrameRate(a *Animation, rate float64) *Animation { return a } -// AnimationRun is an animation StartAnimation runs on the platform. +// AnimationRun is an animation StartAnimation runs on the platform, or a Tween. type AnimationRun struct { t *Tree - id uint32 + id uint32 // 0 for a tween reduced motion ended at once, which the platform never ran ended bool + // halt stops a tween's frames; rewind gives its update its from again. + halt, rewind func() } // Stop ends the run where its values are, unfinished. func (r *AnimationRun) Stop() { if !r.ended { r.ended = true - r.t.anim.add(driver.AnimationOp{Kind: driver.AnimStop, ID: r.id}) + if r.halt != nil { + r.halt() + } + if r.id != 0 { + r.t.anim.add(driver.AnimationOp{Kind: driver.AnimStop, ID: r.id}) + } } } -// Reset ends the run, unfinished if it still runs, and puts the values it -// moves back where they were as it started. +// Reset ends the run, unfinished if it still runs, and puts the values it moves back where they were as it started. func (r *AnimationRun) Reset() { r.ended = true - r.t.anim.add(driver.AnimationOp{Kind: driver.AnimReset, ID: r.id}) + if r.halt != nil { + r.halt() + } + if r.rewind != nil { + r.rewind() + } + if r.id != 0 { + r.t.anim.add(driver.AnimationOp{Kind: driver.AnimReset, ID: r.id}) + } } // StartAnimation runs a on the platform and calls done, if not nil, @@ -289,6 +303,36 @@ func (cx *Scope) StartAnimation(a *Animation, done func(finished bool)) *Animati return cx.startAnimation(a, done, false) } +// Tween calls update with numbers from from to to on each display frame, over c's duration after its delay, eased as Timing moves a value: for what the animation graph cannot draw, such as a figure counting up in a text. It calls done, if not nil, under the current owner with whether it reached to, once, as StartAnimation does. It counts as an animation that ends, so an nsgotest step that starts it waits for to; under reduced motion it calls update with from, then to, at once. Its run's Stop leaves the number where it is and Reset gives update from again; the owner going stops it. +func (cx *Scope) Tween(from, to float64, c TimingConfig, update func(float64), done func(finished bool)) *AnimationRun { + update(from) + if Untracked(cx, cx.Env().ReduceMotion) { + update(to) + if done != nil { + done(true) + } + return &AnimationRun{t: cx.tree(), ended: true, rewind: func() { update(from) }} + } + // The platform runs a Timing of a value nothing shows for the step's sake, and its end gives update to; the frames between are Go's. + a := Timing(NewAnimatedValue(cx, from), to, c) + var halt func() + run := cx.StartAnimation(a, func(finished bool) { + halt() + if finished { + update(to) + } + if done != nil { + done(finished) + } + }) + halt = cx.animate(c.Delay, a.Timing.Duration, c.Easing, func(progress float64) { + update(from + (to-from)*progress) + }) + run.halt = halt + run.rewind = func() { update(from) } + return run +} + // startAnimation is StartAnimation; endless marks a run its done starts // again, which tests need not wait for. func (cx *Scope) startAnimation(a *Animation, done func(finished bool), endless bool) *AnimationRun { diff --git a/core/frame.go b/core/frame.go index 926f2c1f2..4dc56570d 100644 --- a/core/frame.go +++ b/core/frame.go @@ -83,14 +83,15 @@ func (rt *runtime) removeFrame(cb *frameCallback) { } } -// Animate calls step with the eased progress from 0 to 1 once a display -// frame for d, on the graph's goroutine, ending with exactly 1, unless the -// current owner is disposed or stop is called first. Each step's changes -// commit as one batch, so prefer a style Transition for what a platform -// can animate itself. +// Animate calls step with the eased progress from 0 to 1 once a display frame for d, on the graph's goroutine, ending with exactly 1, unless the current owner is disposed or stop is called first. Each step's changes commit as one batch, so prefer a style Transition for what a platform can animate itself. func (cx *Scope) Animate(d time.Duration, curve Curve, step func(progress float64)) (stop func()) { + return cx.animate(0, d, BezierEasing(curve), step) +} + +// animate is Animate after delay, with any of the animation graph's easings, so Tween steps a number as Timing moves a value. +func (cx *Scope) animate(delay, d time.Duration, easing Easing, step func(progress float64)) (stop func()) { o := cx.current() - start := cx.rt.clock.Now() + start := cx.rt.clock.Now().Add(delay) stopped := false var cancel func() var tick func(at time.Time) @@ -98,11 +99,15 @@ func (cx *Scope) Animate(d time.Duration, curve Curve, step func(progress float6 if stopped { return } + if at.Before(start) { + cancel = o.RequestAnimationFrame(tick) + return + } x := 1.0 if d > 0 { x = math.Min(float64(at.Sub(start))/float64(d), 1) } - step(curve.At(x)) + step(easing.At(x)) if x < 1 { cancel = o.RequestAnimationFrame(tick) } diff --git a/core/gate_test.go b/core/gate_test.go index c0516bea7..64aad6472 100644 --- a/core/gate_test.go +++ b/core/gate_test.go @@ -88,7 +88,7 @@ var exempt = map[string][]string{ "Access itself, Confine, and what ProvideHost, ProvideStorage and ProvideSecrets scope to the owner": {"ProvideAccess", "CheckAccess", "ProvideHost", "HasHost", "HostParams", "OnHostEvent", "ProvideStorage", "Storage", "ProvideSecrets", "Confine"}, "the view the code shows and the user's input to it, which no capability holds": {"StartAnimation", "AnimateLayout", - "MeasureText", "RequestAnimationFrame", "RunFrame", "Animate", "PlayHaptic", "OnKey", "OnKeyWith", "OnBackPress", + "MeasureText", "RequestAnimationFrame", "RunFrame", "Animate", "Tween", "PlayHaptic", "OnKey", "OnKeyWith", "OnBackPress", "SetTitle", "DismissKeyboard", "Announce", "SetScrollbars", "WatchScroll", "PopupMenu", "ShowAlert", "RegisterFont", "SetTheme", "SetSubtreeAppearance", "SetAppearance", "SetLocale", "SelectInputSource", "RestoreInputSource", "ServeScheme"}, diff --git a/docs/architecture/animation.md b/docs/architecture/animation.md index 8ac80b2ff..d78e344f1 100644 --- a/docs/architecture/animation.md +++ b/docs/architecture/animation.md @@ -21,6 +21,7 @@ Headless tests run frames as the manual clock advances: `nsgotest.App.Advance` m The app builds a graph once: `AnimatedValue`s, nodes derived with `Interpolate` (numbers or colors, with React Native's extrapolation and easings), `Add`, `Sub`, `Mul`, `Div`, `Mod`, `DiffClamp` and `SnappingDiffClamp`, and animations that move values. `Style.Animated` binds a view's opacity, translation, scales, rotations about each axis, background, border color, shadow color, shadow radius, shadow opacity and text color to nodes, over its style, and a sticky list header's inset (`StickyInset`). A bound text color tints the whole drawn text, as NSH's does. - `Timing`, `Spring` and `Decay` move one value; `Sequence`, `Parallel`, `Stagger`, `Delay` and `Loop` compose them. `Scope.StartAnimation` runs one, calls back once with whether it finished, and returns an `AnimationRun` whose `Stop` ends it where it is and `Reset` puts its values back where they were as it started. Each step of a composite starts at the exact end of the one before. +- `Scope.Tween` steps a number for what the graph cannot draw, such as text: Go's frames (`Scope.Animate`'s, with the delay and any of the graph's easings) call its function, while the platform runs a `Timing` of a value nothing shows, whose end gives the function the last number and holds `nsgotest` steps as any run that ends does. Its run's `Stop` halts the frames where they are and `Reset` gives the function its start again; reduced motion gives the end at once. TSX's `Animated.tween` returns that run with a promise of whether it finished. - Drivers are closed-form functions of the time since they started, so dropped frames change nothing: React Native's damped spring, and NSH's decay, which stops at or bounces off its bounds at the exact time it reaches them. `SampleEasing`, `SampleSpring` and `SampleDecay` return their curves from the same code, to draw them. - A value's `Set`, `Stop`, or another animation of it ends its run unfinished; so does the owner going. `Read` asks the platform for a value. - `AtFrameRate` caps how often a run moves its values, for what loops as long as work lasts: the animator holds it to the rate on every target, Android's Java animator too, and macOS and iOS slow their display links to the fastest rate the runs ask for while nothing else needs the clock (a layout animation, a moving scroll view, a waiting frame, a selection's drag or the performance monitor), applying batches as they land meanwhile rather than holding them for frames that far apart, as iOS always does. diff --git a/docs/public/en/animation.md b/docs/public/en/animation.md index f574cd6c1..c64530deb 100644 --- a/docs/public/en/animation.md +++ b/docs/public/en/animation.md @@ -38,6 +38,15 @@ angle := core.Interpolate(scroll, core.Interpolation{ `Scope.RequestAnimationFrame` runs a function once at the next display frame, and `Scope.Animate` steps a duration on that clock. Both run on the graph's goroutine, so they can set signals. +`Scope.Tween` steps a number on that clock for what an animated value cannot reach, such as a figure counting up in a text: it calls a function with each number from one to another, as `Timing` would move a value, and once more with the last. An `nsgotest` step that starts it waits for the last, as for an animation, and under reduced motion it gives the last at once. TSX's `Animated.tween` is the same. + +```go +freed := core.NewSignal(cx, 0.0) +cx.Tween(0, 18.7, core.TimingConfig{Duration: 600 * time.Millisecond, Easing: core.BezierEasing(core.EaseOut)}, freed.Set, nil) + +core.Text{ContentFunc: func() string { return fmt.Sprintf("%.1f GB can be freed", freed.Get()) }} +``` + ## Transitions A `Transition` animates a view's style or classes when they change, on the platform, with no work for the engine per frame. `Properties` says what moves; 0 means every property but the frame. diff --git a/docs/public/zh/animation.md b/docs/public/zh/animation.md index fbe6b9936..bdbe03143 100644 --- a/docs/public/zh/animation.md +++ b/docs/public/zh/animation.md @@ -38,6 +38,15 @@ angle := core.Interpolate(scroll, core.Interpolation{ `Scope.RequestAnimationFrame` 在下一个显示帧运行一次函数,`Scope.Animate` 在该时钟上推进一段时间。两者都运行在响应式图的 goroutine 上,因此可以设置 signal。 +`Scope.Tween` 在该时钟上推进一个数字,用于动画值够不到的地方,比如文本里向上滚动的数字:它像 `Timing` 移动值那样,把从一个数到另一个数的每个值传给一个函数,最后再传一次终值。启动它的 `nsgotest` 步骤会像等待动画一样等到终值;开启减弱动态效果时,它立即给出终值。TSX 的 `Animated.tween` 与之相同。 + +```go +freed := core.NewSignal(cx, 0.0) +cx.Tween(0, 18.7, core.TimingConfig{Duration: 600 * time.Millisecond, Easing: core.BezierEasing(core.EaseOut)}, freed.Set, nil) + +core.Text{ContentFunc: func() string { return fmt.Sprintf("%.1f GB 可释放", freed.Get()) }} +``` + ## 过渡 `Transition` 在视图的样式或类名变化时,由平台播放过渡,每帧不需要引擎参与。`Properties` 指定哪些属性移动;为 0 时表示除尺寸位置外的所有属性。 diff --git a/nsgotest/tween_test.go b/nsgotest/tween_test.go new file mode 100644 index 000000000..d5a7b690c --- /dev/null +++ b/nsgotest/tween_test.go @@ -0,0 +1,72 @@ +package nsgotest + +import ( + "fmt" + "testing" + "time" + + "github.com/nsgo-dev/nsgo/core" +) + +func TestTweenUpdatesAValueAndSettlesInAStep(t *testing.T) { + var value *core.Signal[float64] + var ended []bool + app := Start(t, func(cx *core.Scope) core.Node { + value = core.NewSignal(cx, float64(0)) + cx.Tween(0, 100, core.TimingConfig{Duration: 100 * time.Millisecond}, value.Set, func(finished bool) { ended = append(ended, finished) }) + return core.Text{TestID: "value", ContentFunc: func() string { return fmt.Sprintf("%.0f", value.Get()) }} + }) + if got := app.Find("id:value").Text; got != "100" { + t.Fatalf("tween settled at %q, want 100", got) + } + if len(ended) != 1 || !ended[0] { + t.Fatalf("done got %v, want [true]", ended) + } +} + +func TestTweenRespectsReducedMotion(t *testing.T) { + var updates []float64 + var run *core.AnimationRun + Start(t, func(cx *core.Scope) core.Node { + run = cx.Tween(2, 8, core.TimingConfig{Duration: time.Second}, func(value float64) { updates = append(updates, value) }, nil) + return core.Text{Content: "done"} + }, Environment(core.Environment{ReduceMotion: true})) + if len(updates) != 2 || updates[0] != 2 || updates[1] != 8 { + t.Fatalf("reduced-motion updates = %v, want [2 8]", updates) + } + run.Stop() + run.Reset() + if len(updates) != 3 || updates[2] != 2 { + t.Fatalf("after Stop and Reset updates = %v, want [2 8 2]", updates) + } +} + +// A tween waits out its delay, moves on the frames between, and its run's Stop leaves the number where it is, Reset puts it back at from. +func TestTweenFollowsTheClockAndStopsWhereItIs(t *testing.T) { + var value *core.Signal[float64] + var run *core.AnimationRun + app := Start(t, func(cx *core.Scope) core.Node { + value = core.NewSignal(cx, float64(0)) + run = cx.Tween(0, 100, core.TimingConfig{Duration: 400 * time.Millisecond, Delay: 100 * time.Millisecond}, value.Set, nil) + return core.Text{Content: "tween"} + }, ManualFrames()) + app.Advance(80 * time.Millisecond) + if v := value.Get(); v != 0 { + t.Fatalf("the tween moved to %v within its delay", v) + } + app.Advance(220 * time.Millisecond) + mid := value.Get() + if mid <= 0 || mid >= 100 { + t.Fatalf("the tween is at %v halfway, want between 0 and 100", mid) + } + run.Stop() // headless, the test goroutine is the graph's + app.Advance(time.Second) + if v := value.Get(); v != mid { + t.Fatalf("a stopped tween moved from %v to %v", mid, v) + } + run.Reset() + app.Advance(time.Second) + if v := value.Get(); v != 0 { + t.Fatalf("a reset tween is at %v, want 0", v) + } +} diff --git a/tsx/animated.go b/tsx/animated.go index d4983965b..6a6de649c 100644 --- a/tsx/animated.go +++ b/tsx/animated.go @@ -699,6 +699,33 @@ func (r *runtime) animatedModule() js.Value { o := r.options(arg(call, 0)) return r.vm.ToValue(core.SampleDecay(o.float("from", 0), r.decayConfig(arg(call, 0)))) }) + // tween runs Scope.Tween at once: update gets each number, and the run it returns stops or resets it and promises whether it reached toValue. + set("tween", func(call js.FunctionCall) js.Value { + cfg, update := arg(call, 0), arg(call, 1) + if !isFunction(update) { + panic(r.vm.NewTypeError("nsgo: Animated.tween takes an update function")) + } + o := r.options(cfg) + dl := r.current + if dl != nil { + r.watch(dl) + } + p, resolve, _ := r.newPromise() + run := r.cx.Tween(o.float("from", 0), o.float("toValue", 0), r.timingConfig(cfg), func(v float64) { + r.under(dl, func() { r.call(update, r.vm.ToValue(v)) }) + }, func(finished bool) { r.inJS(func() { _ = resolve(finished) }) }) + h := r.vm.NewObject() + _ = h.Set("finished", p) + _ = h.Set("stop", r.function(func(js.FunctionCall) js.Value { + run.Stop() + return js.Undefined() + })) + _ = h.Set("reset", r.function(func(js.FunctionCall) js.Value { + run.Reset() + return js.Undefined() + })) + return h + }) return m } diff --git a/tsx/bindings_test.go b/tsx/bindings_test.go index 377ba45b4..73654dd8c 100644 --- a/tsx/bindings_test.go +++ b/tsx/bindings_test.go @@ -197,6 +197,18 @@ mount(App);`) } } +// Animated.tween hands each number to its update and lands on toValue in the step that starts it; its run's finished promise says it got there. +func TestAnimatedTweenCountsUp(t *testing.T) { + app := run(t, `import { mount, signal, Animated, Text } from "nsgo"; +function App() { + const n = signal(0), said = signal(""); + Animated.tween({ from: 0, toValue: 40, duration: 200 }, v => n.set(Math.round(v))).finished.then(f => said.set("finished " + f)); + return {() => "n " + n() + " " + said()}; +} +mount(App);`) + app.WaitFor("text:n 40 finished true", time.Second) +} + func TestAnimatedNodesCompute(t *testing.T) { app := run(t, `import { mount, signal, createAnimatedValue, createMotion, Animated, LayoutAnimation, Text, View } from "nsgo"; function App() { diff --git a/tsx/testdata/sandbox-surface.txt b/tsx/testdata/sandbox-surface.txt index 19f9e6d1c..68ddf41b4 100644 --- a/tsx/testdata/sandbox-surface.txt +++ b/tsx/testdata/sandbox-surface.txt @@ -16,6 +16,7 @@ nsgo.Animated.spring nsgo.Animated.stagger nsgo.Animated.subtract nsgo.Animated.timing +nsgo.Animated.tween nsgo.AnimatedNode nsgo.AnimatedValue nsgo.AuthSession diff --git a/tsx/types/index.d.ts b/tsx/types/index.d.ts index 3feaaf16c..94e63301c 100644 --- a/tsx/types/index.d.ts +++ b/tsx/types/index.d.ts @@ -527,6 +527,12 @@ export interface CompositeAnimation { stop(): void; reset(): void; } +/** A tween Animated.tween started: finished promises whether it reached its toValue; stop leaves the number where it is, reset gives update its from again. */ +export interface TweenRun { + finished: Promise; + stop(): void; + reset(): void; +} export interface AnimatedModule { timing(value: AnimatedValue, config: { toValue: number; duration?: number; easing?: Easing; delay?: number }): CompositeAnimation; spring(value: AnimatedValue, config: SpringConfig): CompositeAnimation; @@ -546,6 +552,8 @@ export interface AnimatedModule { diffClamp(a: AnimatedNode, min: number, max: number, options?: { snap?: boolean }): AnimatedNode; sampleSpring(config: SpringConfig & { from?: number }): number[]; sampleDecay(config: DecayConfig & { from?: number }): number[]; + /** Calls update with numbers from from (default 0) to toValue on each display frame, as timing moves a value, for what an AnimatedNode cannot reach, such as a figure counting up in a text; under reduced motion it calls update with from, then toValue, at once. */ + tween(config: { from?: number; toValue: number; duration?: number; easing?: Easing; delay?: number }, update: (value: number) => void): TweenRun; } export declare const Animated: AnimatedModule; export interface EasingCurves {