diff --git a/core/accessibility.go b/core/accessibility.go index f809eb274..90819587a 100644 --- a/core/accessibility.go +++ b/core/accessibility.go @@ -23,7 +23,7 @@ const ( // SetAccessibilityFocus moves the screen reader's focus to the element, as after a change the user should hear about first. The web and desktops move the keyboard focus with it, to a field at least, so under a confined owner it does only as Scope.Confine allows. func (r *Ref) SetAccessibilityFocus() { - if r.n != nil && !r.n.deleted && r.t.mayMoveFocus(r.n.owner) { + if r.placed() && r.t.mayMoveFocus(r.n.owner) { r.t.command(driver.ItemAccessibilityFocus, r.n) } } diff --git a/core/element.go b/core/element.go index 108b56200..37226c65d 100644 --- a/core/element.go +++ b/core/element.go @@ -570,12 +570,18 @@ func (s Scroll) mountIn(t *Tree, cx *Scope, parent *node) { t.mountScroll(cx, pa // Ref refers to a mounted element: an overlay's anchor, focus, its // bounds. Its zero value is ready to use; pass its address in an -// element's Ref field. +// element's Ref field. Focus, blur and scroll requests are dropped in +// unplaced Holder content; placing it again does not replay them. type Ref struct { t *Tree n *node } +// placed reports whether a live element carries the ref in the tree. +func (r *Ref) placed() bool { + return r != nil && r.n != nil && !r.n.deleted && !r.t.detached(r.n) +} + // Bounds returns the element's frame in surface points after the last // commit, and false while it is not mounted. func (r *Ref) Bounds() (Bounds, bool) { @@ -619,9 +625,9 @@ func (r *Ref) Frame() (Bounds, bool) { return r.n.frame, true } -// Focus moves keyboard focus to the element, a text field. Under a confined owner it does only as Scope.Confine allows. +// Focus moves keyboard focus to the element, a text field. Under a confined owner it does only as Scope.Confine allows. It does nothing in unplaced Holder content, with no focus deferred until it is placed again. func (r *Ref) Focus() { - if r.n != nil && !r.n.deleted && r.t.mayMoveFocus(r.n.owner) { + if r.placed() && r.t.mayMoveFocus(r.n.owner) { r.t.command(driver.ItemFocus, r.n) } } @@ -668,7 +674,7 @@ func (r *Ref) path() []int { // ScrollTo scrolls the element, a Scroll or List, so its content's // offset is at. func (r *Ref) ScrollTo(at Point, animated bool) { - if r.n == nil || r.n.deleted { + if !r.placed() { return } if ln := r.n.list; ln != nil { @@ -684,7 +690,7 @@ func (r *Ref) ScrollTo(at Point, animated bool) { // content. A list keeps following the end as the rows there are // measured, until the user scrolls away. func (r *Ref) ScrollToEnd(animated bool) { - if r.n == nil || r.n.deleted { + if !r.placed() { return } if ln := r.n.list; ln != nil { @@ -705,7 +711,7 @@ func (r *Ref) ScrollToEnd(animated bool) { // its limits), with content point center (unzoomed) in the middle of the // viewport, or keeping the middle when center is nil. func (r *Ref) ZoomTo(scale float32, center *Point, animated bool) { - if r.n == nil || r.n.deleted || r.n.scroll == nil { + if !r.placed() || r.n.scroll == nil { return } z := &driver.ZoomRequest{Scale: r.n.scroll.config.ClampZoom(zoomOr(scale, 1))} @@ -729,7 +735,7 @@ func (r *Ref) ScrollToIndex(index int, animated bool) { // list keeps following the row as the rows around it are measured, until // the user scrolls away or the rows change. func (r *Ref) ScrollToIndexAt(index int, viewPosition float32, viewOffset Points, animated bool) { - if r.n == nil || r.n.deleted || r.n.list == nil { + if !r.placed() || r.n.list == nil { return } r.t.listCommand(r.n.list, listCommand{pin: &listPin{index: max(index, 0), viewPosition: viewPosition, viewOffset: viewOffset}, @@ -738,7 +744,7 @@ func (r *Ref) ScrollToIndexAt(index int, viewPosition float32, viewOffset Points // Blur takes keyboard focus away from the element. func (r *Ref) Blur() { - if r.n != nil && !r.n.deleted { + if r.placed() { r.t.command(driver.ItemBlur, r.n) } } diff --git a/core/list.go b/core/list.go index 38909b889..ebf29c048 100644 --- a/core/list.go +++ b/core/list.go @@ -328,9 +328,10 @@ type listCell struct { // listCommand is a scroll a Ref asked a list for, resolved with the // sizes known in the next update. type listCommand struct { - pin *listPin // ScrollToIndex or ScrollToEnd; nil for to - to Point - animated bool + pin *listPin // ScrollToIndex or ScrollToEnd; nil for to + to Point + animated bool + transient bool // a Ref command, rather than the list's initial position } func (t *Tree) mountList(cx *Scope, parent *node, l List) { @@ -1085,6 +1086,10 @@ func (t *Tree) updateLists() bool { continue } live = append(live, l) + if t.detached(l) { + l.list.cmds = slices.DeleteFunc(l.list.cmds, func(c listCommand) bool { return c.transient }) + continue + } if l.list.st.parent { _, l.list.depth = l.list.findOuter() parents = append(parents, l) @@ -1132,6 +1137,9 @@ func (t *Tree) sendSticky() { } t.stuckIn = t.stuckIn[:0] for v := range views { + if t.detached(v) { + continue + } sc := v.scroll var cells []StickyCell if v.list != nil { @@ -1223,6 +1231,7 @@ func pinRange(n *node) (*node, StickyCell, bool) { // listCommand queues a scroll for list ln's next update. func (t *Tree) listCommand(ln *listNode, c listCommand) { + c.transient = true ln.cmds = append(ln.cmds, c) t.relayout(ln.view) } diff --git a/core/pace.go b/core/pace.go index a7aeccc05..125410f0b 100644 --- a/core/pace.go +++ b/core/pace.go @@ -4,6 +4,8 @@ import ( "math" "slices" "time" + + "github.com/nsgo-dev/nsgo/internal/driver" ) // Views made over frames, as NSH's (performance.md): a list row bound in @@ -186,33 +188,62 @@ func (t *Tree) makeNow(n *node) { } } -// makeCommanded makes the views the commit's commands name, which a -// backend must have. +// makeCommanded drops commands whose targets left the tree, then makes +// the views the remaining commands name before a backend receives them. func (t *Tree) makeCommanded() { - if len(t.waiting) == 0 { - return - } - at := func(id NodeID) { - if int(id) < len(t.nodes) { - if n := t.nodes[id]; n != nil && !n.created { - t.makeNow(n) - } + kept := t.commands[:0] + // Queued scrolls have already contributed to core's predicted offset. + // Cancel them in reverse order so no unsent offset or count survives. + for i := len(t.commands) - 1; i >= 0; i-- { + it := &t.commands[i] + if it.ID == 0 { + continue + } + n := t.nodes[it.ID] + if n != nil && (n.deleted || t.detached(n)) && n.scroll != nil && + (it.Kind == driver.ItemScrollTo || it.Kind == driver.ItemScrollBy) { + sc := n.scroll + last := len(sc.pending) - 1 + sc.offset = sc.pending[last].before + sc.pending = sc.pending[:last] + sc.issued-- } } - for i := range t.commands { - it := &t.commands[i] + for _, it := range t.commands { if it.ID != 0 { - at(it.ID) + n := t.nodes[it.ID] + if n == nil || n.deleted || t.detached(n) && (!n.created || commandNeedsPlacement(it.Kind)) { + continue + } + if !n.created { + t.makeNow(n) + } } for _, c := range it.Sticky { - at(c.Cell) + if n := t.nodes[c.Cell]; n != nil && !n.deleted && !t.detached(n) && !n.created { + t.makeNow(n) + } } + kept = append(kept, it) } - if t.focus != nil && !t.focus.created { + clear(t.commands[len(kept):]) + t.commands = kept + if t.focus != nil && !t.focus.created && !t.detached(t.focus) { t.makeNow(t.focus) } } +// Commands on retained web or native views may still run out of the tree; +// moving focus or scrolling instead requires a place showing the content. +func commandNeedsPlacement(kind driver.ItemKind) bool { + switch kind { + case driver.ItemFocus, driver.ItemBlur, driver.ItemAccessibilityFocus, + driver.ItemScrollTo, driver.ItemScrollBy, driver.ItemZoomTo: + return true + } + return false +} + // syncPaced makes the waiting views that show, down to their leaves, then // as many of the others as the budget allows, nearest first. func (t *Tree) syncPaced() { diff --git a/core/ref_command_test.go b/core/ref_command_test.go new file mode 100644 index 000000000..d8b9cf255 --- /dev/null +++ b/core/ref_command_test.go @@ -0,0 +1,250 @@ +package core + +import ( + "fmt" + "testing" + + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// commandViews checks items in delivery order, including across commits. +func commandViews(t *testing.T, made map[NodeID]bool, b *driver.MountBatch) { + t.Helper() + for _, it := range b.Items { + switch it.Kind { + case driver.ItemCreate: + made[it.ID] = true + case driver.ItemDelete: + delete(made, it.ID) + default: + if it.ID != 0 && !made[it.ID] { + t.Fatalf("item kind %d names view %d before its creation", it.Kind, it.ID) + } + } + } +} + +func refCommands(b *driver.MountBatch) int { + n := 0 + for _, it := range b.Items { + switch it.Kind { + case driver.ItemFocus, driver.ItemBlur, driver.ItemAccessibilityFocus, driver.ItemScrollTo, driver.ItemScrollBy, driver.ItemZoomTo: + n++ + } + } + return n +} + +func TestRefCommandsInUnplacedHolder(t *testing.T) { + for _, pacing := range []bool{false, true} { + for _, existed := range []bool{false, true} { + t.Run(fmt.Sprintf("pacing=%v/created=%v", pacing, existed), func(t *testing.T) { + var shown, content *Signal[bool] + input, scroll, list := &Ref{}, &Ref{}, &Ref{} + h := newHost(t, Size{Width: 200, Height: 300}, nil) + h.tree.SetViewPacing(pacing) + h.tree.Mount(func(cx *Scope) Node { + shown, content = NewSignal(cx, true), NewSignal(cx, existed) + held := NewHolder(cx, func(cx *Scope) Node { + return Show{When: content.Get, Then: func(cx *Scope) Node { + return View{Children: []Node{ + Input{Ref: input}, + Scroll{Ref: scroll, Style: Style{Height: Pt(50)}, Children: []Node{View{Style: Style{Height: Pt(500)}}}}, + List{Ref: list, Style: Style{Height: Pt(50)}, Count: func() int { return 20 }, EstimatedSize: 30, + Row: func(*Scope, ListRow) Node { return View{Style: Style{Height: Pt(30)}} }}, + }} + }} + }) + return Show{When: shown.Get, Then: func(*Scope) Node { return held.Place() }} + }) + made := map[NodeID]bool{} + commit := func() *driver.MountBatch { + b := h.commit() + commandViews(t, made, b) + return b + } + commit() + shown.Set(false) + commit() + content.Set(true) + commit() + commands := func() { + input.Focus() + input.Blur() + input.SetAccessibilityFocus() + input.Reveal(RevealOptions{}) + input.RevealBox(Bounds{Size: Size{Width: 10, Height: 10}}, RevealOptions{}) + scroll.ScrollTo(Point{Y: 10}, false) + scroll.ScrollToEnd(false) + scroll.ZoomTo(2, nil, false) + list.ScrollTo(Point{Y: 10}, false) + list.ScrollToEnd(false) + list.ScrollToIndex(3, false) + } + commands() + if n := refCommands(commit()); n != 0 { + t.Fatalf("unplaced content sent %d commands", n) + } + // Calls while detached are dropped even if it is placed before commit. + commands() + shown.Set(true) + if n := refCommands(commit()); n != 0 { + t.Fatalf("placing content replayed %d commands", n) + } + input.Focus() + scroll.ScrollTo(Point{Y: 20}, false) + if n := refCommands(commit()); n != 2 { + t.Fatalf("placed content sent %d commands, want 2", n) + } + // A command queued while placed must not survive its removal. + sc := scroll.n.scroll + issued, pending, offset := sc.issued, len(sc.pending), sc.offset + input.Focus() + input.Blur() + scroll.ScrollToEnd(false) + list.ScrollToIndex(4, false) + shown.Set(false) + if n := refCommands(commit()); n != 0 { + t.Fatalf("removal sent %d queued commands", n) + } + if sc.issued != issued || len(sc.pending) != pending || sc.offset != offset { + t.Fatalf("dropped scroll changed count, pending or offset: %d, %d, %v", sc.issued, len(sc.pending), sc.offset) + } + shown.Set(true) + if n := refCommands(commit()); n != 0 { + t.Fatalf("placing content replayed %d queued commands", n) + } + }) + } + } +} + +func TestRefCommandsForDeletedViews(t *testing.T) { + for _, pacing := range []bool{false, true} { + t.Run(fmt.Sprint(pacing), func(t *testing.T) { + var shown *Signal[bool] + input, scroll := &Ref{}, &Ref{} + h := newHost(t, Size{Width: 200, Height: 300}, nil) + h.tree.SetViewPacing(pacing) + h.tree.Mount(func(cx *Scope) Node { + shown = NewSignal(cx, false) + return Show{When: shown.Get, Then: func(cx *Scope) Node { + cx.Effect(func() { scroll.ScrollToEnd(false) }) + return Scroll{Ref: scroll, Children: []Node{Input{Ref: input}}} + }} + }) + made := map[NodeID]bool{} + commandViews(t, made, h.commit()) + shown.Set(true) + input.Focus() + input.Blur() + shown.Set(false) + b := h.commit() + commandViews(t, made, b) + if n := refCommands(b); n != 0 { + t.Fatalf("deleted views sent %d commands", n) + } + }) + } +} + +func TestRefCommandCreatesPacedView(t *testing.T) { + ref := &Ref{} + h := newHost(t, Size{Width: 200, Height: 50}, func(*Scope) Node { + kids := make([]Node, 200) + for i := range kids { + kids[i] = View{Style: Style{Height: Pt(30)}} + } + kids = append(kids, Input{Ref: ref}) + return Scroll{Style: Style{Height: Pt(50)}, Children: kids} + }) + made := map[NodeID]bool{} + commandViews(t, made, h.commit()) + if ref.n.created { + t.Fatal("test target did not wait for pacing") + } + ref.Focus() + b := h.commit() + commandViews(t, made, b) + if !ref.n.created || refCommands(b) != 1 { + t.Fatal("command did not create and focus the paced view") + } +} + +func TestUnplacedListKeepsItsInitialPosition(t *testing.T) { + var shown, content *Signal[bool] + ref := &Ref{} + h := newHost(t, Size{Width: 200, Height: 300}, func(cx *Scope) Node { + shown, content = NewSignal(cx, true), NewSignal(cx, false) + held := NewHolder(cx, func(cx *Scope) Node { + return Show{When: content.Get, Then: func(*Scope) Node { + return List{Ref: ref, ContentOffset: Point{Y: 120}, Style: Style{Height: Pt(60)}, + Count: func() int { return 30 }, EstimatedSize: 30, + Row: func(*Scope, ListRow) Node { return View{Style: Style{Height: Pt(30)}} }} + }} + }) + return Show{When: shown.Get, Then: func(*Scope) Node { return held.Place() }} + }) + h.commit() + shown.Set(false) + h.commit() + content.Set(true) + h.commit() + ref.ScrollToIndex(20, false) + h.commit() + shown.Set(true) + b := h.commit() + var offsets []Point + for _, it := range b.Items { + if it.Kind == driver.ItemScrollTo && it.ID == ref.n.id { + offsets = append(offsets, it.Point) + } + } + if len(offsets) != 1 || offsets[0].Y != 120 { + t.Fatalf("initial position = %v, want 120 without replaying the Ref command", offsets) + } +} + +func TestDroppedScrollKeepsLatestPlatformReport(t *testing.T) { + var shown *Signal[bool] + ref := &Ref{} + h := newHost(t, Size{Width: 200, Height: 300}, func(cx *Scope) Node { + shown = NewSignal(cx, true) + held := NewHolder(cx, func(*Scope) Node { + return Scroll{Ref: ref, Style: Style{Height: Pt(60)}, Children: []Node{View{Style: Style{Height: Pt(500)}}}} + }) + return Show{When: shown.Get, Then: func(*Scope) Node { return held.Place() }} + }) + h.commit() + ref.ScrollTo(Point{Y: 900}, false) + h.commit() + ref.ScrollTo(Point{Y: 50}, false) + // The preceding scroll was clamped before the queued one is dropped. + h.tree.Dispatch(driver.Event{Kind: driver.EventScroll, ID: ref.n.id, Point: Point{Y: 440}, Count: 1}) + shown.Set(false) + h.commit() + sc := ref.n.scroll + if sc.offset.Y != 440 || sc.issued != 1 || len(sc.pending) != 0 { + t.Fatalf("cancelled scroll: offset %v, count %d, pending %v", sc.offset, sc.issued, sc.pending) + } +} + +func TestUnplacedHolderKeepsCommandsForRetainedWebView(t *testing.T) { + var shown *Signal[bool] + web := &Ref{} + h := newHost(t, Size{Width: 200, Height: 300}, func(cx *Scope) Node { + shown = NewSignal(cx, true) + held := NewHolder(cx, func(*Scope) Node { return WebView{Ref: web, Source: WebHTML("
kept
", "")} }) + return Show{When: shown.Get, Then: func(*Scope) Node { return held.Place() }} + }) + made := map[NodeID]bool{} + commandViews(t, made, h.commit()) + shown.Set(false) + commandViews(t, made, h.commit()) + web.PostMessage("background") + b := h.commit() + commandViews(t, made, b) + if kinds(b)[driver.ItemWebCommand] != 1 { + t.Fatal("retained web view lost its background command") + } +} diff --git a/core/reveal.go b/core/reveal.go index d7d1d6f70..516b4f3cf 100644 --- a/core/reveal.go +++ b/core/reveal.go @@ -37,7 +37,7 @@ type reveal struct { // lands. The word is NSH's (`reveal`), as GPUI Kit's `reveal_item`; the // alignments are physical, as NSH's. func (r *Ref) Reveal(opts RevealOptions) { - if r == nil || r.n == nil || r.n.deleted { + if !r.placed() { return } r.t.reveals = append(r.t.reveals, reveal{n: r.n, opts: opts}) @@ -46,7 +46,7 @@ func (r *Ref) Reveal(opts RevealOptions) { // RevealBox scrolls every scroll view around the element until box, in the element's frame as TextRangeBoxes gives a text's ranges, shows, as Reveal shows the whole element: a match in a long line of code reaches its column, not only the code's block. func (r *Ref) RevealBox(box Bounds, opts RevealOptions) { - if r == nil || r.n == nil || r.n.deleted { + if !r.placed() { return } r.t.reveals = append(r.t.reveals, reveal{n: r.n, opts: opts, box: &box}) @@ -57,7 +57,7 @@ func (r *Ref) RevealBox(box Bounds, opts RevealOptions) { // views around each view, from this commit's layout. func (t *Tree) revealViews() { for _, rv := range t.reveals { - if !rv.n.deleted { + if !rv.n.deleted && !t.detached(rv.n) { box := Bounds{Size: rv.n.frame.Size} if rv.box != nil { box = *rv.box diff --git a/core/tree.go b/core/tree.go index ce4967d5c..10f65a153 100644 --- a/core/tree.go +++ b/core/tree.go @@ -602,15 +602,16 @@ type scrollNode struct { // pendingScroll is a scroll the core sent and the platform has not shown // applied. type pendingScroll struct { - n uint32 - to bool // an ItemScrollTo; else an ItemScrollBy - p Point + n uint32 + to bool // an ItemScrollTo; else an ItemScrollBy + p Point + before Point // predicted offset before this command, for cancellation } // issue records a scroll sent to the platform. func (sc *scrollNode) issue(to bool, p Point) { sc.issued++ - sc.pending = append(sc.pending, pendingScroll{sc.issued, to, p}) + sc.pending = append(sc.pending, pendingScroll{n: sc.issued, to: to, p: p, before: sc.offset}) if to { sc.offset = p } else { @@ -629,7 +630,9 @@ func (sc *scrollNode) report(p Point, applied uint32) { k++ } sc.pending = sc.pending[k:] - for _, s := range sc.pending { + for i := range sc.pending { + s := &sc.pending[i] + s.before = p if s.to { p = s.p } else { diff --git a/docs/architecture/core.md b/docs/architecture/core.md index adb52366f..940883450 100644 --- a/docs/architecture/core.md +++ b/docs/architecture/core.md @@ -45,7 +45,7 @@ A component is any type whose `Render(cx) Node` returns its nodes, like `http.Ha - Go methods cannot take type parameters, so `Each` is a generic function rather than a method or struct. - Region nodes are never laid out. Layout marks pass through them, so a change inside a branch or row still reaches the root. - A `Holder` is NSH's render keys as a value: content built once, owned by the scope given to `NewHolder` rather than the running owner, and shown in the newest place mounted with `Place`. -- A held content moves to its place with its native views, keeping its state; with no place it stays built out of the tree, its overlays hidden. +- A held content moves to its place with its native views, keeping its state; with no place it stays built out of the tree, its overlays hidden. Focus, blur and scroll requests made while unplaced, or queued for content that leaves before commit, are dropped rather than replayed when placed again. Unsent scrolls also leave no predicted offset or pending count. ## Layers and navigation @@ -143,7 +143,7 @@ The protocol is defined in `mount.go` and `events.go`. Backends apply items in o - A view that changes parents, or comes back after `ItemRemove`, is inserted after the round's other inserts, once its new parent is in place. - Backends move such a view in one step, so scroll offsets and iframes' pages stay: the web with `moveBefore`, parking removed views in a hidden element. - Each round's deletes come last. -- Commands, such as `Ref.Seek`'s `ItemVideoSeek`, follow the round's view items. A video's seeks go ahead of its `ItemVideo` in the update that changes its config and keeps its source, so a video at its end leaves it before an unpause in the same update plays it, where AVPlayer would reach the end again and stop; they stay after an `ItemVideo` that opens a source, which they apply to. +- Commands whose targets are deleted or have no view in unplaced Holder content are dropped, with or without view pacing. Focus and scroll commands also require a place showing the content; other commands may reach retained native views while unplaced. Commands for placed content make their waiting views before delivery. Commands, such as `Ref.Seek`'s `ItemVideoSeek`, follow the round's view items. A video's seeks go ahead of its `ItemVideo` in the update that changes its config and keeps its source, so a video at its end leaves it before an unpause in the same update plays it, where AVPlayer would reach the end again and stop; they stay after an `ItemVideo` that opens a source, which they apply to. - A text field counts the user's edits. `ItemInputValue` carries the edit count the engine had seen, and the field ignores a value older than its last edit. - Platforms report only the events in a view's mask, and never wait for the engine. The engine queue is unbounded, merges scroll events per view and keeps only the last resize. diff --git a/docs/public/en/forms.md b/docs/public/en/forms.md index cbc2078aa..4371358c8 100644 --- a/docs/public/en/forms.md +++ b/docs/public/en/forms.md @@ -27,6 +27,8 @@ ui.Input{ ## Focus and the keyboard +A `Ref`'s focus, blur and scroll commands do nothing while its element belongs to unplaced `Holder` content. Commands queued before the element leaves are also dropped. Place the content and issue a new command to act on it; old commands are never replayed. + `Ref` focuses a field and blurs it, and `cx.DismissKeyboard()` closes the software keyboard. `OnFocus` and `OnBlur` follow the focus, and `View.OnFocus`/`OnBlur` do the same for any focusable view. A focused view that leaves the tree, as its `Show` closes or its row goes, hears `OnBlur` once, after the commit that removed it or, when the platform reports the next focus first, before that view's `OnFocus`, and the views around it that stay hear `OnFocusOut`. ```go diff --git a/examples/gallery/app_test.go b/examples/gallery/app_test.go index cb7fa66f6..8a9e55b4c 100644 --- a/examples/gallery/app_test.go +++ b/examples/gallery/app_test.go @@ -1547,6 +1547,8 @@ func TestTerminal(t *testing.T) { if runtime.GOOS == "windows" { t.Skip("runs a Unix shell") } + // A plain sh rather than the user's shell, whose prompt may set a title of its own over the test's. + t.Setenv("SHELL", "/bin/sh") app := startDesktop(t) open(app, "Terminal") app.Find("id:terminal") diff --git a/examples/orbit/wheel.go b/examples/orbit/wheel.go index cc8f94ad8..5386fc9f6 100644 --- a/examples/orbit/wheel.go +++ b/examples/orbit/wheel.go @@ -41,7 +41,7 @@ func (s *swipe) wheel(e core.WheelEvent) { } switch e.Phase { case core.GestureBegan: - *s = swipe{r: s.r, live: true, last: time.Now()} + *s = swipe{r: s.r, live: true, last: s.r.cx.Now()} s.r.grab() case core.GestureChanged: if !s.live || s.along { @@ -60,7 +60,8 @@ func (s *swipe) wheel(e core.WheelEvent) { s.across = true e.Delta.X = s.lock.X } - if now, dt := time.Now(), time.Since(s.last); dt >= minSample { + now := s.r.cx.Now() + if dt := now.Sub(s.last); dt >= minSample { s.speed = 0.6*s.speed + 0.4*float64(e.Delta.X)/dt.Seconds() s.last = now } @@ -77,7 +78,7 @@ func (s *swipe) wheel(e core.WheelEvent) { return } speed := float64(e.Velocity.X) - if speed == 0 && time.Since(s.last) < 80*time.Millisecond { + if speed == 0 && s.r.cx.Now().Sub(s.last) < 80*time.Millisecond { speed = s.speed } speed = max(min(speed, maxSpeed), -maxSpeed) diff --git a/examples/orbit/wheel_test.go b/examples/orbit/wheel_test.go new file mode 100644 index 000000000..6fb9e564d --- /dev/null +++ b/examples/orbit/wheel_test.go @@ -0,0 +1,48 @@ +package main + +import ( + "math" + "testing" + "time" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/nsgotest" +) + +// TestASwipeIsTimedOnTheAppClock measures a swipe's speed and lets it go stale on the app's clock, which the test moves, so how fast the test runs changes neither: a swipe let go within 80 ms flings on with its speed, a later one rests on the nearest card. +func TestASwipeIsTimedOnTheAppClock(t *testing.T) { + headless(t) + for _, c := range []struct { + name string + pause time.Duration + target float64 + }{ + // -120 points turn the ring -36 degrees; the speed, -4800 points a second capped to -3000, carries it 180 degrees further, to -216, whose nearest card is at -240. + {"fresh", 50 * time.Millisecond, -4 * step}, + {"stale", 100 * time.Millisecond, -step}, + } { + t.Run(c.name, func(t *testing.T) { + var s swipe + app := nsgotest.Start(t, func(cx *core.Scope) core.Node { + s.r = newRing(cx) + return core.View{} + }, nsgotest.Environment(core.Environment{ReduceMotion: true})) + app.Post(func() { s.wheel(core.WheelEvent{Touchpad: true, Phase: core.GestureBegan}) }) + app.Settle() + app.Advance(10 * time.Millisecond) + app.Post(func() { + s.wheel(core.WheelEvent{Touchpad: true, Phase: core.GestureChanged, Delta: core.Point{X: -120}}) + }) + app.Settle() + if math.Abs(s.speed+4800) > 0.001 { + t.Fatalf("speed %g, want -4800 points a second after 10 ms", s.speed) + } + app.Advance(c.pause) + app.Post(func() { s.wheel(core.WheelEvent{Touchpad: true, Phase: core.GestureEnded}) }) + app.Settle() + if s.r.target != c.target { + t.Fatalf("let go after %v, the ring rests at %g, want %g", c.pause, s.r.target, c.target) + } + }) + } +} diff --git a/internal/platform/android/java/dev/oneo/nsgo/NsgoView.java b/internal/platform/android/java/dev/oneo/nsgo/NsgoView.java index bc76b1059..778e30ef8 100644 --- a/internal/platform/android/java/dev/oneo/nsgo/NsgoView.java +++ b/internal/platform/android/java/dev/oneo/nsgo/NsgoView.java @@ -2285,13 +2285,13 @@ private void apply(int kind, Node n, DataInputStream in) throws IOException { break; } case Protocol.ITEM_FOCUS: - if (n.field != null && n.field.requestFocus()) { + if (n != null && n.field != null && n.field.requestFocus()) { EditText field = n.field; field.post(() -> ime.showSoftInput(field, InputMethodManager.SHOW_IMPLICIT)); } break; case Protocol.ITEM_BLUR: - if (n.field != null && n.field.hasFocus()) { + if (n != null && n.field != null && n.field.hasFocus()) { n.field.clearFocus(); ime.hideSoftInputFromWindow(n.field.getWindowToken(), 0); } @@ -2325,6 +2325,7 @@ private void apply(int kind, Node n, DataInputStream in) throws IOException { case Protocol.ITEM_SCROLL_TO: { float x = in.readFloat(), y = in.readFloat(); boolean animated = Protocol.flag(in.readUnsignedByte(), 0); + if (n == null || !(n.scroller instanceof Scrolling.Scroller)) break; Scrolling.Scroller scroller = (Scrolling.Scroller) n.scroller; // Scroll views clamp to their content, which takes its new // size at the next layout. Counted as applied, the scroll @@ -2337,6 +2338,7 @@ private void apply(int kind, Node n, DataInputStream in) throws IOException { } case Protocol.ITEM_SCROLL_BY: { float x = in.readFloat(), y = in.readFloat(); + if (n == null || !(n.scroller instanceof Scrolling.Scroller)) break; Scrolling.Scroller scroller = (Scrolling.Scroller) n.scroller; afterLayout(n.scroller, () -> { n.applied++; @@ -2369,7 +2371,7 @@ private void apply(int kind, Node n, DataInputStream in) throws IOException { boolean centered = Protocol.flag(in.readUnsignedByte(), 0); float x = in.readFloat(), y = in.readFloat(); boolean animated = Protocol.flag(in.readUnsignedByte(), 0); - if (n.scroller instanceof Scrolling.ZoomScroll) { + if (n != null && n.scroller instanceof Scrolling.ZoomScroll) { Scrolling.ZoomScroll z = (Scrolling.ZoomScroll) n.scroller; afterLayout(z, () -> z.zoomTo(scale, centered, x, y, animated)); } diff --git a/internal/platform/android/runtime/classes.dex b/internal/platform/android/runtime/classes.dex index 99f71bcb8..44830972e 100644 Binary files a/internal/platform/android/runtime/classes.dex and b/internal/platform/android/runtime/classes.dex differ diff --git a/internal/platform/android/runtime/classes.jar b/internal/platform/android/runtime/classes.jar index 07a387793..f97646ebd 100644 Binary files a/internal/platform/android/runtime/classes.jar and b/internal/platform/android/runtime/classes.jar differ diff --git a/internal/platform/ios/ios.go b/internal/platform/ios/ios.go index 89e85fcde..5707cb5ef 100644 --- a/internal/platform/ios/ios.go +++ b/internal/platform/ios/ios.go @@ -992,6 +992,9 @@ func (s *surface) apply(b *driver.MountBatch) { case driver.ItemTitle, driver.ItemBackUnhandled, driver.ItemBackPreview, driver.ItemWindow, driver.ItemMenu: continue } + if int(it.ID) >= len(s.views) || s.views[it.ID] == nil { + continue + } v := s.views[it.ID] switch it.Kind { case driver.ItemDelete: diff --git a/internal/platform/macos/macos.go b/internal/platform/macos/macos.go index 03af1994e..49c3a22f9 100644 --- a/internal/platform/macos/macos.go +++ b/internal/platform/macos/macos.go @@ -1582,6 +1582,9 @@ func (s *surface) apply(b *driver.MountBatch) { case driver.ItemStatusBar, driver.ItemBackUnhandled, driver.ItemBackPreview, driver.ItemHistory: continue } + if int(it.ID) >= len(s.views) || s.views[it.ID] == nil { + continue + } v := s.views[it.ID] switch it.Kind { case driver.ItemDelete: diff --git a/internal/platform/macos/mount_test.go b/internal/platform/macos/mount_test.go new file mode 100644 index 000000000..a9bca9413 --- /dev/null +++ b/internal/platform/macos/mount_test.go @@ -0,0 +1,32 @@ +//go:build darwin && !ios + +package macos + +import ( + "testing" + + "github.com/ebitengine/purego/objc" + "github.com/nsgo-dev/nsgo/internal/driver" +) + +func TestMountIgnoresCommandsForMissingViews(t *testing.T) { + onMain(func() { + loadAppKit() + s := &surface{native: objc.ID(classView).Send(selNew), animator: driver.NewAnimator(nil)} + defer s.native.Send(selRelease) + root := s.create(driver.KindView, 1) + defer root.native.Send(selRelease) + defer delete(views, root.native) + s.views = []*view{nil, root, nil} + var items []driver.MountItem + for _, id := range []driver.NodeID{0, 2, 1 << 30} { + for _, kind := range []driver.ItemKind{driver.ItemFocus, driver.ItemBlur, driver.ItemScrollTo, driver.ItemScrollBy, driver.ItemZoomTo} { + items = append(items, driver.MountItem{Kind: kind, ID: id}) + } + } + s.apply(&driver.MountBatch{Root: 1, Items: items}) + if root.native.Send(selSuperview) != s.native { + t.Error("valid root was not mounted after ignoring invalid commands") + } + }) +} diff --git a/nsgotest/model.go b/nsgotest/model.go index da04035aa..6c65a377e 100644 --- a/nsgotest/model.go +++ b/nsgotest/model.go @@ -249,6 +249,47 @@ func (a *App) send(v *View, ev driver.Event) { } } +// viewItemNames identifies items that require a view even when ID is zero. +// Names also keep malformed batches useful as test failures. +var viewItemNames = map[driver.ItemKind]string{ + driver.ItemInsert: "ItemInsert", + driver.ItemRemove: "ItemRemove", + driver.ItemDelete: "ItemDelete", + driver.ItemFrame: "ItemFrame", + driver.ItemViewStyle: "ItemViewStyle", + driver.ItemText: "ItemText", + driver.ItemInput: "ItemInput", + driver.ItemInputValue: "ItemInputValue", + driver.ItemEvents: "ItemEvents", + driver.ItemViewProps: "ItemViewProps", + driver.ItemScrollConfig: "ItemScrollConfig", + driver.ItemScrollContent: "ItemScrollContent", + driver.ItemFocus: "ItemFocus", + driver.ItemBlur: "ItemBlur", + driver.ItemImage: "ItemImage", + driver.ItemModal: "ItemModal", + driver.ItemScrollTo: "ItemScrollTo", + driver.ItemCanvas: "ItemCanvas", + driver.ItemWeb: "ItemWeb", + driver.ItemWebCommand: "ItemWebCommand", + driver.ItemVideo: "ItemVideo", + driver.ItemVideoSeek: "ItemVideoSeek", + driver.ItemNative: "ItemNative", + driver.ItemNativeCommand: "ItemNativeCommand", + driver.ItemZoomTo: "ItemZoomTo", + driver.ItemSelection: "ItemSelection", + driver.ItemScrollBy: "ItemScrollBy", + driver.ItemStickyCells: "ItemStickyCells", + driver.ItemAccessibilityLabel: "ItemAccessibilityLabel", + driver.ItemAccessibilityFocus: "ItemAccessibilityFocus", + driver.ItemScreen: "ItemScreen", + driver.ItemOverflow: "ItemOverflow", + driver.ItemShader: "ItemShader", + driver.ItemShaderTransition: "ItemShaderTransition", + driver.ItemShaderInput: "ItemShaderInput", + driver.ItemMatch: "ItemMatch", +} + func (a *App) apply(b *driver.MountBatch) { a.rootID = b.Root if b.LayoutAnimation != nil { @@ -256,6 +297,12 @@ func (a *App) apply(b *driver.MountBatch) { } for _, it := range b.Items { v := a.views[it.ID] + if name := viewItemNames[it.Kind]; v == nil && (name != "" || it.ID != 0 && it.Kind != driver.ItemCreate) { + if name == "" { + name = fmt.Sprintf("item kind %d", it.Kind) + } + a.t.Fatalf("nsgotest: %s names unknown view %d", name, it.ID) + } switch it.Kind { case driver.ItemCreate: a.views[it.ID] = &View{ID: it.ID, Kind: it.View, Style: driver.DefaultViewStyle, anim: a.anim} @@ -271,6 +318,9 @@ func (a *App) apply(b *driver.MountBatch) { case driver.ItemInsert: v.detach() p := a.views[it.Parent] + if p == nil { + a.t.Fatalf("nsgotest: ItemInsert for view %d names unknown parent %d", it.ID, it.Parent) + } at := len(p.Children) for i, c := range p.Children { if c.ID == it.Before { diff --git a/nsgotest/mount_test.go b/nsgotest/mount_test.go new file mode 100644 index 000000000..c5d395e3a --- /dev/null +++ b/nsgotest/mount_test.go @@ -0,0 +1,102 @@ +package nsgotest + +import ( + "fmt" + "strings" + "testing" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/internal/driver" +) + +func TestRefFocusInUnplacedHolder(t *testing.T) { + ref, scroll := &core.Ref{}, &core.Ref{} + var shown, content *core.Signal[bool] + app := Start(t, func(cx *core.Scope) core.Node { + shown, content = core.NewSignal(cx, true), core.NewSignal(cx, false) + held := core.NewHolder(cx, func(cx *core.Scope) core.Node { + return core.Show{When: content.Get, Then: func(*core.Scope) core.Node { + return core.Scroll{Ref: scroll, Style: core.Style{Height: core.Pt(100)}, Children: []core.Node{ + core.Input{Ref: ref, TestID: "field"}, core.View{Style: core.Style{Height: core.Pt(500)}}, + }} + }} + }) + return core.Show{When: shown.Get, Then: func(*core.Scope) core.Node { return held.Place() }} + }) + app.Post(func() { shown.Set(false) }) + app.Settle() + app.Post(func() { content.Set(true) }) + app.Settle() + app.Post(func() { ref.Focus(); ref.Blur(); scroll.ScrollToEnd(false) }) + app.Settle() + app.Post(func() { shown.Set(true) }) + app.Settle() + if app.Find("field").Focused { + t.Fatal("detached focus was replayed") + } + app.Post(func() { ref.Focus(); scroll.ScrollTo(core.Point{Y: 20}, false) }) + app.Settle() + if !app.Find("field").Focused { + t.Fatal("placed input did not take focus") + } + // A scroll queued just before detaching is dropped; it must not leave + // an unacknowledged scroll count that offsets later reports forever. + app.Post(func() { scroll.ScrollToEnd(false); shown.Set(false) }) + app.Settle() + app.Post(func() { shown.Set(true); scroll.ScrollTo(core.Point{Y: 30}, false) }) + app.Settle() + if got := app.Find("field").Parent.Offset.Y; got != 30 { + t.Fatalf("new scroll offset = %v, want 30", got) + } +} + +func TestMountFailsWithItemAndMissingView(t *testing.T) { + for _, item := range []struct { + kind driver.ItemKind + name string + }{ + {driver.ItemFocus, "ItemFocus"}, {driver.ItemBlur, "ItemBlur"}, + {driver.ItemScrollTo, "ItemScrollTo"}, {driver.ItemScrollBy, "ItemScrollBy"}, + {driver.ItemFrame, "ItemFrame"}, {driver.ItemInsert, "ItemInsert"}, + } { + for _, id := range []driver.NodeID{0, 1 << 30} { + t.Run(fmt.Sprintf("%s/%d", item.name, id), func(t *testing.T) { + msg := fails(t, func(tb testing.TB) { + app := Start(tb, func(*core.Scope) core.Node { return core.View{} }) + app.apply(&driver.MountBatch{Items: []driver.MountItem{{Kind: item.kind, ID: id}}}) + }) + if !strings.Contains(msg, item.name) || !strings.Contains(msg, fmt.Sprintf("unknown view %d", id)) { + t.Fatalf("missing-view diagnostic = %q", msg) + } + }) + } + } + msg := fails(t, func(tb testing.TB) { + app := Start(tb, func(*core.Scope) core.Node { return core.View{TestID: "child", Style: core.Style{Height: core.Pt(20)}} }) + app.apply(&driver.MountBatch{Items: []driver.MountItem{{Kind: driver.ItemInsert, ID: app.Find("child").ID, Parent: 1 << 30}}}) + }) + if !strings.Contains(msg, "ItemInsert") || !strings.Contains(msg, "unknown parent 1073741824") { + t.Fatalf("missing-parent diagnostic = %q", msg) + } +} + +func TestScrollEffectOnReplacedView(t *testing.T) { + var page *core.Signal[int] + scroll := &core.Ref{} + effects := 0 + app := Start(t, func(cx *core.Scope) core.Node { + page = core.NewSignal(cx, 0) + return core.Dynamic(func(cx *core.Scope) core.Node { + if page.Get() != 1 { + return core.View{} + } + cx.Effect(func() { effects++; scroll.ScrollToEnd(false) }) + return core.Scroll{Ref: scroll, Children: []core.Node{core.Text{Content: "temporary"}}} + }) + }) + app.Post(func() { page.Set(1); page.Set(2) }) + app.Settle() + if effects != 1 { + t.Fatalf("temporary view effect ran %d times, want 1", effects) + } +} diff --git a/skills/nsgo/references/components.md b/skills/nsgo/references/components.md index 545872564..1ae4353ac 100644 --- a/skills/nsgo/references/components.md +++ b/skills/nsgo/references/components.md @@ -28,3 +28,5 @@ Use `ui`'s component whenever one exists: it is `base`'s control with NSGo's loo - Give each control a label screen readers hear (`Label`, or the button's text); icon-only buttons need one. - `ui.NavPage` and `ui.NavHeader` draw the system's own header and back gesture on phones; do not build a header of views there. - `ui.Menu` and `ui.Select` open beside their trigger on any device, or as a sheet when their `Presentation` asks; choose it explicitly instead of switching by device. + +- `core.Ref` focus, blur and scroll commands are dropped in unplaced `core.Holder` content, or when their target leaves before commit. Place the content and issue a fresh command; showing it does not replay earlier focus or scroll requests.