diff --git a/CHANGELOG.md b/CHANGELOG.md index 161a6a9..7ad9664 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- **Your model tries the journeys too.** Ask it to book the hike, or to give up halfway: it clicks through the mockup + looking at each screen, as a user would, and tells you where it got stuck, the clicks that did nothing and the screens + no click opens. + +### Fixed + +- In the light theme, a screen being presented or tried has the thin outline it has on the board: one with a white or + cream ground no longer fades into the window. + ## [0.5.0] - 2026-12-03 ### Added diff --git a/DESIGN.md b/DESIGN.md index 6032ca5..5aa7ef6 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -43,8 +43,8 @@ A status color tints its own background at `1f` alpha (the status pill). Every dark color has a light one that takes its role (`lightColors` in `theme.go`, the one place they are listed): ground `#f7f1eb` with `#dbccbf` dots, white surfaces with `#ebe0d7` borders, text `#241a15`, -`#5e4c43`, `#948177`, the accent a deeper `#d93d1f` for contrast on white. Frames get a hairline -`#ebe0d7` edge, white on the light ground. The theme follows the system's (read when the app opens) until +`#5e4c43`, `#948177`, the accent a deeper `#d93d1f` for contrast on white. Frames, and the screen +presented or tried, get a hairline `#ebe0d7` edge, or a white or cream one is lost in the light ground. The theme follows the system's (read when the app opens) until the user picks Light or Dark in the settings; System, the default, follows it again. ### Shape diff --git a/docs/AUTHORING.md b/docs/AUTHORING.md index 5573ec5..21429b5 100644 --- a/docs/AUTHORING.md +++ b/docs/AUTHORING.md @@ -15,6 +15,7 @@ What a mockup of more than one screen needs, learned building lich's screens wit - A **journey** per thing the user came to do (`journey "Create account" from="Login" to="Welcome"`). The board shows the shortest way there: `via="Register"` takes it through a screen that one skips. Trying it tells the clicks that did nothing and the screens no click opens: link every step, the ways out too. + The model tries it with `try_journey`: ask it to book, sign up or give up halfway, and to tell where it got stuck. - `theme=light` on a screen draws it in another look of the registry; copy a screen to compare both. - Files are for versioning: `export` writes a project as one `.gockup`, `import` reads one back (its own `import "lib/…"` lines inlined). Outside a project, a library file shared with `import` still works. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index ca73c75..8bdf1be 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -133,7 +133,8 @@ Tools: `list_design_systems`, `add_design_system`, `remove_design_system`, `list `list_places`, `place_screens` (where frames sit on the board, moved as one undoable change), `write_item` (one screen, fragment, note or journey; the whole project is validated, nothing invalid is written), `edit_item` (replace a snippet), `rename_item` (the gotos, calls, notes and journeys pointing at it follow), `delete_item`, `move_item`, `validate_item`, `render_screen` (PNG via the headless GPU renderer), -`render_overview` (every screen on one PNG). Keep the projects window open to watch the model work live. +`render_overview` (every screen on one PNG), `try_journey` (the model walks a journey click by click, with live widgets, and is told +what each click did, the ones that did nothing and the screens no click opens). Keep the projects window open to watch the model work live. The `from_app` prompt (`/mcp__gockup__from_app` in Claude Code) mocks up an app you already have: the model reads its UI code and rebuilds every screen as a project, with your design system's components, diff --git a/docs/ceilings.md b/docs/ceilings.md index 78c1c43..612b091 100644 --- a/docs/ceilings.md +++ b/docs/ceilings.md @@ -48,6 +48,9 @@ file is the trap alone. place, so the screen is laid out once more, each goto labelled. It is as the screen opens, so on a live frame scrolled by hand the ring stays where the goto was. A goto in a `When` not shown as the screen starts has no place: its arrow leaves from the frame's edge, with no ring. +- **`try_journey` starts over at every call** and does all its clicks again: nothing is kept between calls, so a project + changed in between is walked as it is now. It clicks and scrolls and does not type, as nothing reads what is typed. + A click by text finds its place as a goto's is found, so what a list has not scrolled to is not there. - **A `When` is never laid out**: `Ctx.Children` gives its parent what is in it, in its place, or nothing. So it takes no `weight`, `goto` or `set`, cannot be a screen's root, and picking one in the layers outlines nothing. - **A click that did nothing is told by the state its node keeps** (`Session.answers`): a leaf that keeps only a diff --git a/journeys.go b/journeys.go index 3c536ba..503fad6 100644 --- a/journeys.go +++ b/journeys.go @@ -106,7 +106,12 @@ func (s *Session) gotoAreas(sc *dsl.Screen, px float32) []image.Rectangle { Constraints: layout.Exact(image.Pt(metric.Dp(unit.Dp(sc.Width)), metric.Dp(unit.Dp(sc.Height)))), }, sc) router.Frame(ops) - areas := make([]image.Rectangle, len(nodes)) + return areasIn(&router, len(nodes)) +} + +// areasIn are where the n nodes measured in the router's last frame were laid out. +func areasIn(router *input.Router, n int) []image.Rectangle { + areas := make([]image.Rectangle, n) for _, n := range router.AppendSemantics(nil) { if at, ok := strings.CutPrefix(n.Desc.Label, areaLabel); ok { if i, err := strconv.Atoi(at); err == nil { diff --git a/mcp.go b/mcp.go index 5119d8c..f4518b5 100644 --- a/mcp.go +++ b/mcp.go @@ -76,7 +76,8 @@ screen "Name" width=360 height=640 theme=dark { // size in dp, defaults 360x64 journey "Create account" from="Login" via="Register" to="Welcome" from is where it starts, to the screen it is meant to get to (left out, one nothing leads out of). The board shows the shortest way; via, optional, is a screen it must go through when a shorter one skips the point. Link every - step with a goto: the journey tells the clicks that did nothing and the screens no click opens. + step with a goto: the journey tells the clicks that did nothing and the screens no click opens. try_journey walks it + with your clicks: do it after linking a flow, and tell the user where you got stuck. - Notes give context on the board, for the user and for you: why a screen is the way it is, what is still to do. One line each, on its own item: note "Why the eye" on="Login" status=decided x=40 y=600 text="The user asked for it in the review." @@ -235,6 +236,7 @@ func (s *mcpServer) handle(req rpcRequest) (any, *rpcError) { "when the user's own is not installed, import it first (it tells how: write an adapter, then add_design_system), and tell the user you are doing so. " + "Then list_projects; create_project names the design system, and list_components shows its components. " + "Add or replace one screen or fragment per write_item, change one with edit_item and always check them with render_screen. " + + "Once a flow is linked, write its journey and walk it with try_journey before showing it. " + "To version a project in the user's repository, run `gockup export \"\" -o .gockup` in a shell: it writes the file and the project's assets beside it.", }, nil case "ping": @@ -362,6 +364,21 @@ var ( "project": projectArg, "scale": map[string]any{"type": "number", "description": "pixels per dp, default 1"}, }, "project")}, + {"name": "try_journey", "description": "Use the mockup as its user would: walk a journey from its start, with live widgets, and see where it gets stuck. " + + "Every call starts over and does all the clicks, so add one to the list after looking at the picture of where the last got to. " + + "Click what someone who only sees the picture would, not what the source says is linked; then tell the user the clicks that did nothing, " + + "the screens no click opens and where it was not clear what to do. Nothing is written.", + "inputSchema": schema(map[string]any{ + "project": projectArg, + "journey": map[string]any{"type": "string", "description": "the journey's name"}, + "clicks": map[string]any{"type": "array", "description": "what is done, in order; none shows where the journey starts", + "items": map[string]any{"type": "object", "properties": map[string]any{ + "text": map[string]any{"type": "string", "description": "click what says exactly this: a button's text, a field's hint"}, + "x": map[string]any{"type": "number", "description": "with y, click this point instead, in dp: an icon, or one of two with the same text"}, + "y": map[string]any{"type": "number"}, + "scroll": map[string]any{"type": "number", "description": "turn the wheel instead of clicking, in dp, down when positive; at x and y, or the screen's middle"}, + }}}, + }, "project", "journey")}, } ) @@ -382,6 +399,8 @@ func (s *mcpServer) call(name string, raw json.RawMessage) (toolResult, error) { Group *string `json:"group"` SVG string `json:"svg"` DesignSystem string `json:"design_system"` + Journey string `json:"journey"` + Clicks []walkClick `json:"clicks"` Places map[string]struct { X float32 `json:"x"` Y float32 `json:"y"` @@ -516,6 +535,8 @@ func (s *mcpServer) call(name string, raw json.RawMessage) (toolResult, error) { return s.renderScreen(args.Project, args.Screen, args.Scale, args.State) case "render_overview": return s.renderOverview(args.Project, args.Scale) + case "try_journey": + return s.tryJourney(args.Project, args.Journey, args.Clicks) } return toolResult{}, fmt.Errorf("unknown tool %q", name) } diff --git a/present.go b/present.go index 60fb14e..c630221 100644 --- a/present.go +++ b/present.go @@ -11,6 +11,7 @@ import ( "gioui.org/layout" "gioui.org/op" "gioui.org/op/clip" + "gioui.org/op/paint" "gioui.org/unit" "github.com/lichdotdev/gockup/dsl" @@ -117,6 +118,10 @@ func layoutAlone(gtx layout.Context, sess *Session, sc *dsl.Screen, left int) la free := room.Sub(image.Pt(left, 2*gtx.Dp(presentRoom))) k := min(1, float32(free.X)/float32(size.X), float32(free.Y)/float32(size.Y)) at := f32.Pt(float32(left), 0).Add(layout.FPt(room.Sub(image.Pt(left, 0))).Sub(layout.FPt(size).Mul(k)).Mul(0.5)) + w := gtx.Dp(1) + edge := image.Rectangle{Min: at.Round(), Max: at.Add(layout.FPt(size).Mul(k)).Round()}.Inset(-w) + // under the screen, not stroked as the board's: a 1px stroke there falls on half pixels and fades + paint.FillShape(gtx.Ops, frameEdge, clip.UniformRRect(edge, int(float32(gtx.Dp(presentRadius))*k)+w).Op(gtx.Ops)) defer op.Affine(f32.Affine2D{}.Scale(f32.Point{}, f32.Pt(k, k)).Offset(at)).Push(gtx.Ops).Pop() defer clip.UniformRRect(image.Rectangle{Max: size}, gtx.Dp(presentRadius)).Push(gtx.Ops).Pop() fgtx := gtx diff --git a/present_test.go b/present_test.go index 092a14b..e066366 100644 --- a/present_test.go +++ b/present_test.go @@ -1,6 +1,8 @@ package gockup import ( + "image" + "image/color" "strings" "testing" @@ -40,3 +42,48 @@ func TestPresenting(t *testing.T) { } s.frame() } + +// A screen as light as the window's ground still shows where it ends in the +// light theme, presented or tried. +func TestAScreenAloneHasAnEdgeInTheLight(t *testing.T) { + // what the eye takes for a line, in levels of a color's channel + const seen = 8 + t.Cleanup(func() { applyTheme(false) }) + reg := NewRegistry() + reg.Background = color.NRGBA{R: 0xfa, G: 0xf7, B: 0xf1, A: 0xff} + s := newStudioDrawing(t, reg, dsl.Decl{Kind: dsl.JourneyDecl, Name: "Look", Text: `journey "Look" from="A"`}) + s.a.setTheme(true) + s.act("sel:screen:A") + for _, c := range []struct { + action string + left int + }{{"present", 0}, {"try:Look", s.a.sidebarSpan()}} { + s.act(c.action) + window := *s.a.view + window.Width, window.Height = 1200, 800 + img, err := s.a.uiSess.render(&window, 1) + if err != nil { + t.Fatal(err) + } + x, y := c.left+(1200-c.left-360)/2, (800-640)/2 + if got := img.RGBAAt(x+180, y+320); got != color.RGBA(reg.Background) { + t.Fatalf("%s: the middle of the screen is %v", c.action, got) + } + ground := img.RGBAAt(x-20, y+320) + for side, at := range map[string][2]image.Point{ + "left": {{X: x, Y: y + 320}, {X: 1}}, + "right": {{X: x + 360, Y: y + 320}, {X: 1}}, + "top": {{X: x + 180, Y: y}, {Y: 1}}, + "bottom": {{X: x + 180, Y: y + 640}, {Y: 1}}, + } { + most := 0 + for d := -2; d <= 2; d++ { + p := img.RGBAAt(at[0].X+d*at[1].X, at[0].Y+d*at[1].Y) + most = max(most, min(int(ground.B), int(reg.Background.B))-int(p.B)) + } + if most < seen { + t.Errorf("%s: the %s edge is %d levels from the ground, want %d", c.action, side, most, seen) + } + } + } +} diff --git a/render.go b/render.go index c7a2c04..d38d7c9 100644 --- a/render.go +++ b/render.go @@ -166,6 +166,21 @@ func offscreenOf(size image.Point) (*headless.Window, error) { return w, nil } +// lockLayout waits for this session's turn to lay out off screen, and returns +// what gives it back. +func (s *Session) lockLayout() func() { + layoutTurn.Lock() + if s.layoutMu != nil { + s.layoutMu.Lock() + } + return func() { + if s.layoutMu != nil { + s.layoutMu.Unlock() + } + layoutTurn.Unlock() + } +} + func (s *Session) render(sc *dsl.Screen, scale float32) (*image.RGBA, error) { return s.renderLaidOutAt(sc, scale, scale) } @@ -185,12 +200,7 @@ func (s *Session) renderLaidOutAt(sc *dsl.Screen, layoutPx, scale float32) (*ima // the first frame starts enter animations (a dialog growing in); the one // shot is laid out once they have settled frame := func(at time.Duration) { - layoutTurn.Lock() - defer layoutTurn.Unlock() - if s.layoutMu != nil { - s.layoutMu.Lock() - defer s.layoutMu.Unlock() - } + defer s.lockLayout()() ops.Reset() k := scale / layoutPx op.Affine(f32.AffineId().Scale(f32.Point{}, f32.Pt(k, k))).Add(ops) diff --git a/site/img/tried-light.png b/site/img/tried-light.png index 36629ae..5929979 100644 Binary files a/site/img/tried-light.png and b/site/img/tried-light.png differ diff --git a/theme.go b/theme.go index e2b23b1..f9bc25c 100644 --- a/theme.go +++ b/theme.go @@ -77,8 +77,9 @@ var ( }() ) -// frameEdge outlines the frames that have no other outline: none in the dark, -// where white frames stand out; a hairline in the light. +// frameEdge outlines the board's frames that have no other outline and the +// screen presented or tried: none in the dark, where white frames stand out; a +// hairline in the light. var frameEdge color.NRGBA // applyTheme sets the Go code's colors for the light theme or the dark one. diff --git a/trial.go b/trial.go index 635cb67..d24b495 100644 --- a/trial.go +++ b/trial.go @@ -71,50 +71,58 @@ func (a *studio) try(name string) { } func (a *studio) restartTrial() { - t := &a.trial - t.steps, t.idle = []trialStep{{screen: t.from}}, nil - t.sess = NewSession(a.reg) - t.sess.SetAssets(a.assets) + sess := NewSession(a.reg) + sess.SetAssets(a.assets) // called while a frame is laid out, with a.mu already held - t.sess.Goto = func(screen string) { - a.innermost() + a.trial.start(sess, func() *dsl.File { return a.file }, func() { + a.regen() + a.invalidate() + }) +} + +// start begins the trial at its first screen, on a new session. file is the +// project as it is now, and moved is called after each click it notes. +func (t *trial) start(sess *Session, file func() *dsl.File, moved func()) { + t.steps, t.idle, t.sess = []trialStep{{screen: t.from}}, nil, sess + walk := func(screen string, from []string) { + t.walk(file(), screen, from) + moved() + } + sess.Goto = func(screen string) { + t.innermost() at := t.steps[len(t.steps)-1] - a.walk(screen, append(slices.Clone(at.from), at.screen)) + walk(screen, append(slices.Clone(at.from), at.screen)) } - t.sess.back = func() { - a.innermost() + sess.back = func() { + t.innermost() from := t.steps[len(t.steps)-1].from if n := len(from); n > 0 { - a.walk(from[n-1], from[:n-1]) + walk(from[n-1], from[:n-1]) } } - t.sess.changed = func() { - a.walk(t.screen(), t.steps[len(t.steps)-1].from) + sess.changed = func() { + walk(t.screen(), t.steps[len(t.steps)-1].from) } - t.sess.idle = func(n *dsl.Node) { + sess.idle = func(n *dsl.Node) { if c := (idleClick{nodeText(n), t.screen()}); !slices.Contains(t.idle, c) { t.idle = append(t.idle, c) - a.regen() - a.invalidate() + moved() } } } // innermost takes back the step of a goto around the one running now: one // click runs both, the outer first, and is one step. -func (a *studio) innermost() { - if a.trial.sess.went { - a.trial.dropStep() +func (t *trial) innermost() { + if t.sess.went { + t.dropStep() } } // walk takes the trial to screen by the click that just came. -func (a *studio) walk(screen string, from []string) { - t := &a.trial +func (t *trial) walk(f *dsl.File, screen string, from []string) { t.steps[len(t.steps)-1].did = nodeText(t.sess.clicked) - t.steps = append(t.steps, trialStep{screen: screen, from: from, vars: cloneVars(t.sess.vars), state: a.stateText(screen)}) - a.regen() - a.invalidate() + t.steps = append(t.steps, trialStep{screen: screen, from: from, vars: cloneVars(t.sess.vars), state: t.stateText(f, screen)}) } // trialBack takes the last step back, as if it was not walked. @@ -140,15 +148,17 @@ func cloneVars(vars map[string]map[string]string) map[string]map[string]string { return out } +func (a *studio) stateText(screen string) string { return a.trial.stateText(a.file, screen) } + // stateText tells the states of screen that are not as it starts. -func (a *studio) stateText(screen string) string { - sc := a.file.Screen(screen) +func (t *trial) stateText(f *dsl.File, screen string) string { + sc := f.Screen(screen) if sc == nil { return "" } var out []string for _, p := range sc.State { - if now := a.trial.sess.stateNow(sc, p.Name); now != p.Value.Plain() { + if now := t.sess.stateNow(sc, p.Name); now != p.Value.Plain() { out = append(out, p.Name+"="+now) } } @@ -208,33 +218,35 @@ func nodeText(n *dsl.Node) string { return s } +func (a *studio) arrived() bool { return a.trial.arrived(a.file) } + // arrived reports whether the trial is where the journey ends: the screen it // is to, or without one, a screen nothing leads out of, once through the // screen it is via. -func (a *studio) arrived() bool { - t := &a.trial +func (t *trial) arrived(f *dsl.File) bool { if t.via != "" && !slices.ContainsFunc(t.steps, func(s trialStep) bool { return s.screen == t.via }) { return false } if t.to != "" { return t.screen() == t.to } - return len(gotos(a.file.Screen(t.screen()).Root)) == 0 + return len(gotos(f.Screen(t.screen()).Root)) == 0 } +func (a *studio) unopened() []string { return a.trial.unopened(a.file, a.decls) } + // unopened are the screens no click opens from the journey's first, of the // pages the trial walked. -func (a *studio) unopened() []string { - t := &a.trial - reached := way{steps: reachable(a.file, t.from)} +func (t *trial) unopened(f *dsl.File, decls []dsl.Decl) []string { + reached := way{steps: reachable(f, t.from)} pages := map[string]bool{} - for _, d := range a.decls { + for _, d := range decls { if d.Kind == dsl.ScreenDecl && slices.ContainsFunc(t.steps, func(s trialStep) bool { return s.screen == d.Name }) { pages[d.Group] = true } } var out []string - for _, d := range a.decls { + for _, d := range decls { if d.Kind == dsl.ScreenDecl && pages[d.Group] && reached.step(d.Name) < 0 { out = append(out, d.Name) } diff --git a/walk.go b/walk.go new file mode 100644 index 0000000..8d6c7f9 --- /dev/null +++ b/walk.go @@ -0,0 +1,248 @@ +package gockup + +import ( + "encoding/base64" + "fmt" + "image" + "math" + "slices" + "strings" + "time" + + "gioui.org/f32" + "gioui.org/io/input" + "gioui.org/io/pointer" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" + + "github.com/lichdotdev/gockup/dsl" +) + +// walkClick is one thing the model does on a screen: a click on what says +// Text, or at X and Y, or a turn of the wheel there. +type walkClick struct { + Text string `json:"text"` + X *float32 `json:"x"` + Y *float32 `json:"y"` + Scroll float32 `json:"scroll"` +} + +// walker tries a journey off screen, with the events a window would send. +type walker struct { + trial + file *dsl.File + router input.Router + now time.Time +} + +func newWalker(f *dsl.File, j *dsl.Journey, sess *Session) *walker { + w := &walker{file: f, now: time.Now(), trial: trial{journey: j.Name, from: j.From, via: j.Via, to: j.To}} + w.start(sess, func() *dsl.File { return w.file }, func() {}) + w.frame() + return w +} + +// frame lays out the screen the walk is on, as render_screen draws it, with +// every animation of the frame before settled. +func (w *walker) frame() { + defer w.sess.lockLayout()() + sc := w.file.Screen(w.screen()) + ops := new(op.Ops) + w.now = w.now.Add(settleTime) + metric := unit.Metric{PxPerDp: defaultRenderScale, PxPerSp: defaultRenderScale} + w.sess.Layout(layout.Context{ + Ops: ops, Source: w.router.Source(), Now: w.now, Metric: metric, + Constraints: layout.Exact(image.Pt(metric.Dp(unit.Dp(sc.Width)), metric.Dp(unit.Dp(sc.Height)))), + }, sc) + w.router.Frame(ops) +} + +// do does c and tells what came of it; ok is false when there was nothing to +// click. +func (w *walker) do(c walkClick) (told string, ok bool) { + sc := w.file.Screen(w.screen()) + at := f32.Pt(float32(sc.Width)/2, float32(sc.Height)/2) + what := "the middle" + switch { + case c.X != nil && c.Y != nil: + at = f32.Pt(*c.X, *c.Y) + what = fmt.Sprintf("%g,%g", at.X, at.Y) + if at.X < 0 || at.Y < 0 || at.X >= float32(sc.Width) || at.Y >= float32(sc.Height) { + return fmt.Sprintf("%s is off the screen, %d×%d dp", what, sc.Width, sc.Height), false + } + case c.Text != "": + var problem string + if at, problem = w.find(sc, c.Text); problem != "" { + return problem, false + } + what = fmt.Sprintf("%q", c.Text) + case c.Scroll == 0: + return "a click needs the text of what is clicked, or x and y", false + } + px := at.Mul(defaultRenderScale) + if c.Scroll != 0 { + w.send(pointer.Event{Kind: pointer.Scroll, Source: pointer.Mouse, Position: px, Scroll: f32.Pt(0, c.Scroll*defaultRenderScale)}) + return fmt.Sprintf("scrolled %g at %s", c.Scroll, what), true + } + steps := len(w.steps) + w.send(pointer.Event{Kind: pointer.Press, Source: pointer.Mouse, Buttons: pointer.ButtonPrimary, Position: px}) + w.send(pointer.Event{Kind: pointer.Release, Source: pointer.Mouse, Position: px}) + answered := w.sess.hit != nil && w.sess.answers(w.sess.hitPath) + now := w.steps[len(w.steps)-1] + told = "clicked " + what + ": " + switch { + case len(w.steps) == steps && answered: + told += "it answered, on the same screen" + case len(w.steps) == steps: + told += "nothing happened" + case now.screen != sc.Name: + told += "opened " + now.screen + case now.state != "": + told += "the screen changed, now with " + now.state + default: + told += "the screen is as it starts again" + } + // what it opened takes the clicks only once laid out + w.frame() + return told, true +} + +func (w *walker) send(e pointer.Event) { + e.Time = time.Duration(w.now.UnixNano()) + w.router.Queue(e) + w.frame() +} + +// find is the middle, in dp, of what says text on sc, or why there is no one +// such place. +func (w *walker) find(sc *dsl.Screen, text string) (at f32.Point, problem string) { + nodes := saying(sc.Root, text) + if len(nodes) == 0 { + return at, fmt.Sprintf("nothing on %s says %q", sc.Name, text) + } + w.sess.measured = make(map[*dsl.Node]int, len(nodes)) + for i, n := range nodes { + w.sess.measured[n] = i + } + w.frame() + w.sess.measured = nil + seen := image.Rectangle{Max: image.Pt(sc.Width, sc.Height).Mul(defaultRenderScale)} + var places []string + for _, r := range areasIn(&w.router, len(nodes)) { + if r = r.Intersect(seen); r.Empty() { + continue + } + at = f32.Pt(float32(r.Min.X+r.Max.X), float32(r.Min.Y+r.Max.Y)).Div(2 * defaultRenderScale) + if p := fmt.Sprintf("%g,%g", math.Round(float64(at.X)), math.Round(float64(at.Y))); !slices.Contains(places, p) { + places = append(places, p) + } + } + switch len(places) { + case 0: + return at, fmt.Sprintf("%q is not in sight on %s: it is further down a list to scroll, or shown only in another state", text, sc.Name) + case 1: + return at, "" + } + return at, fmt.Sprintf("%d things on %s say %q, at %s: click one by its x and y", len(places), sc.Name, text, strings.Join(places, " and ")) +} + +// saying are the nodes of n with text in a property, whatever the component +// calls it. +func saying(n *dsl.Node, text string) []*dsl.Node { + plain := func(s string) string { return strings.Join(strings.Fields(s), " ") } + var out []*dsl.Node + if slices.ContainsFunc(n.Props, func(p dsl.Prop) bool { + return p.Value.Kind == dsl.String && p.Name != dsl.GotoProp && p.Name != dsl.SetProp && strings.EqualFold(plain(p.Value.Str), plain(text)) + }) { + out = append(out, n) + } + for _, c := range n.Children { + out = append(out, saying(c, text)...) + } + return out +} + +// tryJourney walks a journey from its start with the clicks given, and tells +// the way they took and what the screen it got to looks like. +func (s *mcpServer) tryJourney(project, name string, clicks []walkClick) (toolResult, error) { + f, _, sess, err := s.load(project) + if err != nil { + return toolResult{}, err + } + j := f.Journey(name) + if j == nil { + names := make([]string, len(f.Journeys)) + for i, j := range f.Journeys { + names[i] = fmt.Sprintf("%q", j.Name) + } + if len(names) == 0 { + return toolResult{}, fmt.Errorf("%s has no journeys: write one with write_item", project) + } + return toolResult{}, fmt.Errorf("no journey %q in %s, which has %s", name, project, strings.Join(names, ", ")) + } + if f.Screen(j.From) == nil { + return toolResult{}, fmt.Errorf("the journey starts at %q, which is not a screen of %s", j.From, project) + } + decls, err := s.db.Decls(project) + if err != nil { + return toolResult{}, err + } + w := newWalker(f, j, sess) + var b strings.Builder + fmt.Fprintf(&b, "%q starts at %s", j.Name, j.From) + if j.Via != "" { + b.WriteString(", goes through " + j.Via) + } + if j.To != "" { + b.WriteString(" and is meant to get to " + j.To) + } + b.WriteString("\n") + for i, c := range clicks { + on := w.screen() + told, ok := w.do(c) + if ok { + told = "on " + on + ", " + told + } + fmt.Fprintf(&b, "%d. %s\n", i+1, told) + if !ok { + if left := len(clicks) - i - 1; left > 0 { + fmt.Fprintf(&b, "Stopped there, with %s not tried.\n", plural(left, "click")) + } + break + } + } + w.tellEnd(&b, decls) + sc := f.Screen(w.screen()) + img, err := sess.RenderPNG(sc, defaultRenderScale) + if err != nil { + return toolResult{}, err + } + fmt.Fprintf(&b, "The picture is %s as it is now, %d×%d dp at %d pixels per dp; x, y and scroll are in dp.", sc.Name, sc.Width, sc.Height, defaultRenderScale) + return toolResult{Content: []content{ + {Type: "text", Text: b.String()}, + {Type: "image", Data: base64.StdEncoding.EncodeToString(img), MimeType: "image/png"}, + }}, nil +} + +// tellEnd writes where the walk is and what it showed. +func (w *walker) tellEnd(b *strings.Builder, decls []dsl.Decl) { + if len(w.idle) > 0 { + idle := make([]string, len(w.idle)) + for i, c := range w.idle { + idle[i] = c.what + " on " + c.screen + } + fmt.Fprintf(b, "Clicks that did nothing: %s.\n", strings.Join(idle, ", ")) + } + if !w.arrived(w.file) { + fmt.Fprintf(b, "Not there yet: on %s.\n", w.screen()) + if lost := wayOf(w.file, w.file.Journey(w.journey)).lost; lost != "" { + fmt.Fprintf(b, "It cannot get there: no click leads to %s.\n", lost) + } + return + } + fmt.Fprintf(b, "Got to %s in %s.\n", w.screen(), plural(len(w.steps), "step")) + if unopened := w.unopened(w.file, decls); len(unopened) > 0 { + fmt.Fprintf(b, "Screens of its pages no click opens: %s.\n", strings.Join(unopened, ", ")) + } +} diff --git a/walk_test.go b/walk_test.go new file mode 100644 index 0000000..26a7a7a --- /dev/null +++ b/walk_test.go @@ -0,0 +1,146 @@ +package gockup + +import ( + "image" + "strings" + "testing" + + "gioui.org/layout" + "gioui.org/widget" + + "github.com/lichdotdev/gockup/dsl" +) + +// tried calls try_journey on the project decls make, and returns what it tells. +func tried(t *testing.T, decls []dsl.Decl, journey string, clicks ...map[string]any) string { + t.Helper() + text, isErr := toolText(t, tryCall(t, decls, journey, clicks...)) + if isErr { + t.Fatalf("try_journey: %s", text) + } + return text +} + +func tryCall(t *testing.T, decls []dsl.Decl, journey string, clicks ...map[string]any) map[string]any { + t.Helper() + reg := NewRegistry() + box := func(gtx layout.Context) layout.Dimensions { + return layout.Dimensions{Size: image.Pt(gtx.Dp(360), gtx.Dp(100))} + } + reg.Register("Text", Component{ + Props: []Prop{{Name: "text", Type: String}}, + Layout: func(c *Ctx) layout.Dimensions { return box(c.Gtx) }, + }) + reg.Register("Toggle", Component{ + Props: []Prop{{Name: "label", Type: String}}, + Layout: func(c *Ctx) layout.Dimensions { return State[widget.Bool](c, nil).Layout(c.Gtx, box) }, + }) + db := testDB(t) + if err := db.CreateProject("P", ""); err != nil { + t.Fatal(err) + } + for _, d := range decls { + if err := db.Put("P", "", d); err != nil { + t.Fatal(err) + } + } + return mcpCall(t, reg, db, call("try_journey", map[string]any{"project": "P", "journey": journey, "clicks": clicks}))[0] +} + +func says(text string) map[string]any { return map[string]any{"text": text} } + +func wantTold(t *testing.T, told string, want ...string) { + t.Helper() + for _, w := range want { + if !strings.Contains(told, w) { + t.Errorf("want %q in:\n%s", w, told) + } + } +} + +func TestTheModelWalksAJourneyToItsEnd(t *testing.T) { + told := tried(t, journeyDecls(), "Create account", + says("forgot it"), says("Create an account"), says("Cancel"), map[string]any{"x": 20, "y": 20}, says("Create")) + wantTold(t, told, + `1. on Login, clicked "forgot it": nothing happened`, + `2. on Login, clicked "Create an account": opened Register`, + `3. on Register, clicked "Cancel": opened Login`, + `4. on Login, clicked 20,20: opened Register`, + `5. on Register, clicked "Create": opened Welcome`, + "Clicks that did nothing: Forgot it on Login.", + "Got to Welcome in 5 steps.", + "Screens of its pages no click opens: Locked.", + ) +} + +func TestTheModelSeesWhereItIs(t *testing.T) { + resp := tryCall(t, journeyDecls(), "Create account") + text, _ := toolText(t, resp) + wantTold(t, text, `"Create account" starts at Login and is meant to get to Welcome`, "Not there yet: on Login.") + content := resp["result"].(map[string]any)["content"].([]any) + if len(content) != 2 || content[1].(map[string]any)["type"] != "image" { + t.Errorf("want the screen's picture after the text, got %d parts", len(content)) + } +} + +func TestAWalkStopsAtWhatIsNotThere(t *testing.T) { + told := tried(t, journeyDecls(), "Create account", says("Sign in with a passkey"), says("Create an account")) + wantTold(t, told, `nothing on Login says "Sign in with a passkey"`, "Stopped there, with 1 click not tried.", "Not there yet: on Login.") + wantTold(t, tried(t, journeyDecls(), "Create account", map[string]any{"x": 400, "y": 20}), "400,20 is off the screen, 360×640 dp") + wantTold(t, tried(t, journeyDecls(), "Create account", map[string]any{}), "a click needs the text of what is clicked, or x and y") +} + +func TestAWalkTellsAJourneyWithNoWay(t *testing.T) { + decls := journeyDecls() + decls[4].Text = `journey "Create account" from="Login" to="Locked"` + wantTold(t, tried(t, decls, "Create account"), "It cannot get there: no click leads to Locked.") +} + +func TestAWalkOfAJourneyThatIsNot(t *testing.T) { + text, isErr := toolText(t, tryCall(t, journeyDecls(), "Nope")) + if !isErr { + t.Errorf("no error: %s", text) + } + wantTold(t, text, `no journey "Nope" in P, which has "Create account"`) +} + +func walkDecls(body string) []dsl.Decl { + return []dsl.Decl{ + {Kind: dsl.ScreenDecl, Name: "Form", Text: `screen "Form" width=360 height=300 { ` + body + ` }`}, + {Kind: dsl.ScreenDecl, Name: "Done", Text: `screen "Done" width=360 height=300 { Text text="Done" }`}, + {Kind: dsl.JourneyDecl, Name: "Fill", Text: `journey "Fill" from="Form" to="Done"`}, + } +} + +func TestAWalkThroughAScreensStates(t *testing.T) { + decls := walkDecls(`state error=no + Flex axis=vertical { + When error=no { Sized width=360 height=100 set="error=yes" { Text text="Send" } } + When error=yes { Sized width=360 height=100 goto="Done" { Text text="Send again" } } + Toggle label="Remember" + }`) + told := tried(t, decls, "Fill", says("Remember"), says("Send"), says("Send again")) + wantTold(t, told, + `1. on Form, clicked "Remember": it answered, on the same screen`, + `2. on Form, clicked "Send": the screen changed, now with error=yes`, + `3. on Form, clicked "Send again": opened Done`, + ) + wantTold(t, tried(t, decls, "Fill", says("Send again")), `"Send again" is not in sight on Form`) +} + +func TestAWalkScrollsToWhatIsFurtherDown(t *testing.T) { + decls := walkDecls(`Scroll { + Text text="One" Text text="Two" Text text="Three" Text text="Four" + Sized width=360 height=100 goto="Done" { Text text="Go" } + }`) + wantTold(t, tried(t, decls, "Fill", says("Go")), `"Go" is not in sight on Form`) + wantTold(t, tried(t, decls, "Fill", map[string]any{"scroll": 300}, says("Go")), + "1. on Form, scrolled 300 at the middle", `2. on Form, clicked "Go": opened Done`) +} + +func TestAWalkAsksWhichOfTwo(t *testing.T) { + decls := walkDecls(`Flex axis=vertical { Text text="Open" Sized width=360 height=100 goto="Done" { Text text="Open" } }`) + told := tried(t, decls, "Fill", says("Open")) + wantTold(t, told, `2 things on Form say "Open", at 180,50 and 180,150: click one by its x and y`) + wantTold(t, tried(t, decls, "Fill", map[string]any{"x": 180, "y": 150}), "opened Done") +}