diff --git a/CHANGELOG.md b/CHANGELOG.md index 7094fc5..eb30c10 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - **Your agent knows how to version a project.** Ask it to keep the mockups in your repository and it runs `gockup export`, which writes the `.gockup` file and its assets. +- **Journeys**: name a way through your mockup, from the screen it starts at to the one it is meant to get to. The board + flags where each starts and marks the screens it goes through; a click on the flag lights the way, numbered, with what + is clicked on each screen: the shortest way, or the one through a screen you name with `via`. J, or the route button beside Present, lists them in the sidebar. +- **Try a journey**: use the mockup as if it were the app. The path shows each screen and what you clicked, and at the + end, the clicks that did nothing and the screens no click opens. +- `goto=back`, for a back arrow or a Cancel: while a journey is tried, it opens the screen the user came from. + +### Fixed + +- The tooltip of Present, in the top bar, was cut by the window's edge: it opens below the button. ## [0.3.0] - 2026-12-03 diff --git a/DESIGN.md b/DESIGN.md index 9cefa7d..0d22f93 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -123,6 +123,32 @@ centered, scaled down to fit and never up. Its gotos navigate; ← and → and t (name, "i / n") go through its page in the board's order and stop at the ends. Esc, or the "Back to the board" pill, comes back with the last screen presented selected. +## Trying a journey + +Present shows screens; trying a journey is using the app, to find where it fails. They stay two modes. + +- A journey is in sight on the board: a flag with its name over the screen it starts at, and the route mark in the + title of every screen one goes through. Nothing has to be opened to know it is there. +- A click on the flag **lights** it, the board staying where it is: its screens outlined in coral and numbered, a ring + around what is clicked on each, the arrow leaving from it, and the rest dimmed, with no other arrows. The way is the + shortest to the journey's end, through the screen it is `via` if it names one; one with no end lights every screen its start leads to, with no numbers. The + selected frame, when not on the way, is outlined in gray. A second click or Esc turns it off. +- The lit journey has a bar at the board's bottom left: name, how many screens, "Try it". The flag's ▶ tries it too. +- The sidebar's **Journeys** are listed only when asked for, by the route button beside ▶, J, or a route mark, which + also lights the journey. They stay under the tree, over Settings, and scroll past 280dp. The lit one has its steps + ("1 Login · Create an account"), a click on one going to it, a pencil and a bin; one no click leads to the end of + says so in yellow. "New journey from Login" makes one from the selected screen, its name ready to be written. +- The window is the app, live and alone, as Present draws it, and the path in the sidebar's place: each screen gone + through, numbered, with what was clicked on it, the one it is on in coral. The last 8 are listed. +- The bottom pill has a step back, the screen's name, start over, and the route button, which hides the path and + stays as it was left. There is no next: only the app's own links lead on. +- What is typed stays on the way back; starting over clears it. A step back undoes the step, the app's own back + (`goto=back`) is one more. +- At the end, the journey's `to` or a screen nothing leads out of, once through its `via`, the path says "Got to Welcome in 4 steps" and + **what it showed**: the clicks that did nothing, in yellow, and the screens of its pages no click opens, in blue. + Three names at most, then "and 2 more"; with neither, one green line says so. +- Esc goes back to the board with the screen it was on selected. + ## Settings - Settings is a row at the foot of a project's sidebar, under a rule, there whatever the list's length (the @@ -206,7 +232,8 @@ overview: it opens on the board, with every screen. changed screens are selected. - Over the cards, while there are any, a strip names the pages the model changed, four at most, each with how many screens and a click to open it: their cards can be far down. "Mark all as seen" at its right takes every mark off. -- Nothing is selected on it: no row but Overview is filled, and there are no tools, zoom or Present. +- Nothing is selected on it: no row but Overview is filled, and there are no tools, zoom or Present; the + journeys are the project's, so their button stays, and lighting one opens its page. ## Dialogs @@ -247,7 +274,7 @@ light); a click on the veil or Esc closes it and does nothing else. always live. A frame that is live but not selected takes no clicks itself: a click selects it. - Tools as in Figma: Move (V) drags frames and, on the bare board, draws a box to pick them; Hand (H, or Space or Ctrl held, or the middle button, or scrolling) pans; Note (N) places a note. Each tool shows its - name and shortcuts in a tooltip. + name and shortcuts in a tooltip, above it; the top bar's open below, where there is room. - Frames are picked together by Shift+click (on a picked one, it leaves), by the box (the frames it touches; with Shift, added) or Ctrl+A (the page's); Esc or a click on one frame goes back to one. Each picked frame is outlined, the whole of them in a coral hairline 4dp out, the crumbs say "3 screens", diff --git a/README.md b/README.md index c833529..88aecc5 100644 --- a/README.md +++ b/README.md @@ -73,6 +73,8 @@ one to check its own work. You watch it happen. - **The model at work, in the open.** What it changes lights up on the board, and one click takes it back. - **Notes that stay.** Pin the why to a screen. The model reads it before touching that screen again. - **A flow you can click.** Present a screen and walk the app through its links, with live widgets. +- **A journey you can try.** Use the mockup as if it were the app, and see the clicks that did nothing and the + screens nobody can reach. - **An app you already have.** The `from_app` prompt reads your UI code and rebuilds its screens as a project. - **Plain text underneath.** A project exports to one `.gockup` file you can review and version; screens export to PNG. diff --git a/app.go b/app.go index 2b7a8cd..7b1ea8c 100644 --- a/app.go +++ b/app.go @@ -160,8 +160,11 @@ func layoutTip(c *Ctx, th *material.Theme) layout.Dimensions { }, ) call := m.Stop() - // above the child, centered, drawn after everything else so nothing covers it + // centered on the child, drawn after everything else so nothing covers it at := image.Pt((dims.Size.X-tip.Size.X)/2, -tip.Size.Y-gtx.Dp(8)) + if c.String("side") == "below" { + at.Y = dims.Size.Y + gtx.Dp(8) + } m = op.Record(gtx.Ops) st := op.Offset(at).Push(gtx.Ops) call.Add(gtx.Ops) @@ -272,6 +275,15 @@ type studio struct { picked []string // presenting is the screen shown alone, live, for its flow to be tried presenting string + // trial is the journey being tried; pathHidden, whether its path is out + // of the way, kept from one to the next. + trial trial + pathHidden bool + // journeysOpen is whether the sidebar lists the journeys, whose ways are by + // name, and lit the one shown on the board, "" for none. + journeysOpen bool + ways map[string]way + lit string // explorer opens the system's file dialogs; nil off a window explorer *explorer.Explorer searchQuery string @@ -450,6 +462,11 @@ func (a *studio) registry(th *material.Theme) *Registry { Props: []Prop{{Name: "color", Type: Color, Default: textColor}}, Layout: a.layoutVeil, }) + ui.Register("Tried", Component{ + Doc: "the journey's screen, live", + Props: []Prop{{Name: "left", Type: Number, Doc: "what the path takes of the window, dp"}}, + Layout: a.layoutTried, + }) ui.Register("Presented", Component{ Doc: "the screen being presented, live, in the middle of the window; the arrow keys go through the page", Layout: func(c *Ctx) layout.Dimensions { return a.layoutPresented(c.Gtx) }, @@ -474,9 +491,10 @@ func (a *studio) registry(th *material.Theme) *Registry { }, }) ui.Register("Tip", Component{ - Doc: "shows text and a shortcut in a tooltip above its child while the pointer is over it", + Doc: "shows text and a shortcut in a tooltip beside its child while the pointer is over it", Children: true, - Props: []Prop{{Name: "text", Type: String}, {Name: "key", Type: String}}, + Props: []Prop{{Name: "text", Type: String}, {Name: "key", Type: String}, + {Name: "side", Type: Enum, Enum: []string{"above", "below"}, Doc: "below for a child at the window's top, where there is no room above"}}, Layout: func(c *Ctx) layout.Dimensions { return layoutTip(c, th) }, @@ -753,7 +771,7 @@ func (a *studio) act(action string) { var err error switch verb { case "home": - a.project, a.presenting = "", "" + a.project, a.presenting, a.trial, a.lit, a.journeysOpen = "", "", trial{}, "", false case "toast-undo": err = a.undoToast() case "toast-go": @@ -770,7 +788,7 @@ func (a *studio) act(action string) { a.leavePage() case "open": a.paged = false - a.project, a.selKind, a.selName, a.presenting = arg, "", "", "" + a.project, a.selKind, a.selName, a.presenting, a.trial, a.lit, a.journeysOpen = arg, "", "", "", trial{}, "", false a.opened = time.Now() a.board, a.snaps = board{fit: true}, nil case "tab": @@ -957,6 +975,26 @@ func (a *studio) act(action string) { a.exportProjectTo(arg) case "import": a.importPicked() + case "journeys": + a.journeysOpen = !a.journeysOpen + case "journeys-on": + a.journeysOn(arg) + case "light": + a.lightJourney(arg) + case "journey-new": + err = a.newJourney() + case "journey-rename": + a.renaming = arg + case "try": + a.try(arg) + case "try-back": + a.trialBack() + case "try-restart": + a.restartTrial() + case "try-path": + a.pathHidden = !a.pathHidden + case "try-exit": + a.trialExit() case "present": if a.selKind == dsl.ScreenDecl { a.present(a.selName) @@ -1128,6 +1166,8 @@ func (a *studio) renameItem(kind dsl.DeclKind, old, name string) error { next, err = dsl.RenameScreen(a.decls, old, name) case dsl.FragmentDecl: next, err = dsl.RenameFragment(a.decls, old, name) + case dsl.JourneyDecl: + next, err = dsl.RenameJourney(a.decls, old, name) case assetKind: next, err = dsl.RenameAsset(a.decls, old, name) assets = maps.Clone(a.assets) @@ -1148,6 +1188,9 @@ func (a *studio) renameItem(kind dsl.DeclKind, old, name string) error { if a.selKind == kind && a.selName == old { a.selName = name } + if kind == dsl.JourneyDecl && a.lit == old { + a.lit = name + } return nil } @@ -1322,6 +1365,8 @@ func (a *studio) regen() { switch { case a.settings: src = a.settingsScreen() + case a.trial.on(): + src = a.trialScreen() case a.presenting != "": src = a.presentScreen() case a.project != "": @@ -1422,7 +1467,7 @@ func (a *studio) useDesignSystem() error { func (a *studio) loadProject() { decls, err := a.db.Decls(a.project) if errors.Is(err, store.ErrNotFound) { - a.project = "" + a.project, a.trial = "", trial{} return } a.decls, a.loadErr = decls, err @@ -1449,6 +1494,11 @@ func (a *studio) loadProject() { } snaps := a.snaps snaps.SetAssets(assets) + a.board.measure = func(sc *dsl.Screen, px float32) []image.Rectangle { + sess := NewSession(reg) + sess.SetAssets(assets) + return sess.gotoAreas(sc, px) + } a.board.render = func(sc *dsl.Screen, px, scale float32) (*image.RGBA, error) { return snaps.renderLaidOutAt(sc, px, scale) } @@ -1475,7 +1525,7 @@ func (a *studio) loadProject() { break } } - if first.Kind != dsl.NoteDecl { + if first.Kind != dsl.NoteDecl && first.Kind != dsl.JourneyDecl { a.selKind, a.selName = first.Kind, first.Name } } @@ -1494,6 +1544,8 @@ func (a *studio) loadProject() { a.enterPage(decls[i].Group) } a.canvas = a.canvasScreen() + a.loadJourneys() + a.keepTrying() } // canvasScreen is the selected screen, or the selected component laid out @@ -1574,7 +1626,7 @@ func (a *studio) projectScreen() string { if a.overview() { a.overviewCards(&b, time.Now()) } - fmt.Fprintf(&b, "ProjectSidebar width=%d {\nBackLink\n", a.sideWidth) + fmt.Fprintf(&b, "ProjectSidebar width=%d {\nSidebarTree weight=1 {\nBackLink\n", a.sideWidth) if ref := "project:" + a.project; a.renaming == ref { fmt.Fprintf(&b, "Inset top=6 { RenameTitle name=%q key=%q submit=%q }\n", a.project, ref, "rename-to:"+ref+groupSep) } else { @@ -1583,6 +1635,10 @@ func (a *studio) projectScreen() string { b.WriteString("SearchField\n") a.sidebarTree(&b, broken) b.WriteString("}\n") + if a.journeysOpen { + a.journeysSection(&b) + } + b.WriteString("}\n") fmt.Fprintf(&b, "Inset left=%d top=10 { Flex axis=vertical spacing=8 {\nPill { Inset top=6 bottom=6 { Flex axis=horizontal align=center spacing=8 {\n", a.sidebarSpan()) fmt.Fprintf(&b, "Crumb text=\"Projects\" open=\"home\"\nCrumb text=\"/\" color=%q\nCrumb text=%q open=\"page-all\"\n", mutedColor, a.project) if a.paged { @@ -1602,6 +1658,11 @@ func (a *studio) projectScreen() string { a.notices(&b) b.WriteString("} }\n}\n") b.WriteString("Inset top=10 right=10 { Flex axis=vertical spacing=10 align=end {\nPill top=6 bottom=6 left=6 right=8 { Flex axis=horizontal align=center spacing=8 {\n") + if a.journeysOpen { + fmt.Fprintf(&b, "JourneysButton color=%q bg=%q\n", pickedText, pickedFill) + } else { + b.WriteString("JourneysButton\n") + } if a.selKind == dsl.ScreenDecl { b.WriteString("PresentButton\n") } @@ -1641,6 +1702,10 @@ func (a *studio) projectScreen() string { fmt.Fprintf(&b, "ToolBar %s\nZoomBar zoom=%q\n} }\n", tools, fmt.Sprintf("%d%%", int(math.Round(float64(a.board.zoom*100))))) } b.WriteString("}\n") + if w, ok := a.ways[a.lit]; ok && a.selKind == dsl.ScreenDecl { + fmt.Fprintf(&b, "Inset left=%d bottom=10 { JourneyBar name=%q text=%q try=%q close=%q }\n", + a.sidebarSpan(), a.lit, plural(len(w.steps), "screen"), "try:"+a.lit, "light:"+a.lit) + } if len(a.toast) > 0 { first, more := a.toast[0], "" if n := len(a.toast) - 1; n > 0 { @@ -1988,6 +2053,7 @@ func (a *studio) layoutCanvas(gtx layout.Context) layout.Dimensions { key.Filter{Name: "E", Required: key.ModShortcut | key.ModShift}, key.Filter{Name: "A", Required: key.ModShortcut}, key.Filter{Name: "P", Optional: key.ModShift}, + key.Filter{Name: "J", Optional: key.ModShift}, ) if !ok { break @@ -2001,6 +2067,8 @@ func (a *studio) layoutCanvas(gtx layout.Context) layout.Dimensions { } case e.Name == "P": a.act("present") + case e.Name == "J": + a.act("journeys") case e.Name == "A": if a.selKind == dsl.ScreenDecl { a.pickAll() @@ -2031,7 +2099,15 @@ func (a *studio) layoutCanvas(gtx layout.Context) layout.Dimensions { } a.board.picked[name] = true } + a.board.lit, a.board.way = a.lit, nil + if w, ok := a.ways[a.lit]; ok { + a.board.way = &w + } zoomed := a.board.layout(gtx, a.th, a.sess, screens, a.places, a.boardNotes(screens), a.selName) + if did := a.board.did; did != "" { + a.board.did = "" + a.act(did) + } if a.boardPicks() { zoomed = true } diff --git a/app.gockup b/app.gockup index adc445c..cedcd11 100644 --- a/app.gockup +++ b/app.gockup @@ -163,17 +163,12 @@ fragment Sidebar width=270 { } } -// a project's sidebar: its rows scrolling, and Settings in the footer under a rule +// a project's sidebar: its tree scrolling (SidebarTree) and what is open under it, then Settings +// in the footer under a rule fragment ProjectSidebar width=270 { SideCard width=$width { Flex axis=vertical align=stretch { - Inset top=8 weight=1 { - Scroll axis=vertical { - Inset top=6 bottom=6 left=14 right=14 { - Flex axis=vertical align=stretch { Slot } - } - } - } + Slot Inset left=14 right=14 bottom=10 { Flex axis=vertical align=stretch { HLine @@ -184,6 +179,16 @@ fragment ProjectSidebar width=270 { } } +fragment SidebarTree { + Inset top=8 { + Scroll axis=vertical { + Inset top=6 bottom=6 left=14 right=14 { + Flex axis=vertical align=stretch { Slot } + } + } + } +} + // a pill floating over the board, for the top bar's crumbs and status fragment Pill top=4 bottom=4 left=16 right=16 { Surface { Box color="#1a1614" radius=999 border=1 borderColor="#302824" { @@ -493,7 +498,7 @@ fragment ThemeSegment name="" bg="#00000000" color="#9c8d84" open="" { // starts presenting the selected screen fragment PresentButton { - Tip text="Present" key="P" { + Tip text="Present" key="P" side=below { Box radius=999 goto="present" { Inset all=6 { Image src="play.svg" width=16 color="#9c8d84" } } } } @@ -889,3 +894,144 @@ fragment AgentsMain text="" open="" { Inset top=7 bottom=7 left=16 right=16 { Text text=$text bold=true color="#0e0b0a" } } } + +fragment JourneysButton color="#9c8d84" bg="#00000000" { + Tip text="Journeys" key="J" side=below { + Box color=$bg radius=999 goto="journeys" { Inset all=6 { Image src="route.svg" width=16 color=$color } } + } +} + +// the project's journeys in its sidebar, under the tree +fragment JourneysSection count="" { + Inset left=14 right=14 bottom=6 { + Flex axis=vertical align=stretch { + HLine + GroupHead name="Journeys" count=$count icon="route.svg" fold="journeys" open="journeys" + Slot + } + } +} + +fragment JourneyRow name="" open="" try="" { + HoverBox color="#231d1a" radius=8 { + Inset top=6 bottom=6 left=30 right=8 { + Flex axis=horizontal align=center spacing=8 { + Text text=$name size=13 color="#bbaca3" lines=1 weight=1 goto=$open + Image src="play.svg" width=13 color="#9c8d84" goto=$try + } + } + } +} + +// the journey lit on the board; its screens follow +fragment JourneyLitRow name="" open="" try="" rename="" delete="" trash="#9c8d84" { + Box color="#3a2019" radius=8 { + Inset top=6 bottom=6 left=30 right=8 { + Flex axis=horizontal align=center spacing=8 { + Text text=$name size=13 color="#fbf3ee" lines=1 weight=1 goto=$open + Image src="edit.svg" width=13 color="#9c8d84" goto=$rename + Image src="trash.svg" width=13 color=$trash goto=$delete + Image src="play.svg" width=13 color="#ff9a80" goto=$try + } + } + } +} + +fragment JourneyStep n="" name="" did="" open="" { + Inset top=3 bottom=3 left=30 right=8 goto=$open { + Flex axis=horizontal align=center spacing=8 { + Sized width=16 height=16 { Overlay { Box color="#ff5f3d" radius=8 fill=true { Spacer } Text text=$n size=11 color="#ffffff" } } + Text text=$name size=12 color="#dccfc7" lines=1 weight=1 + Text text=$did size=12 color="#9c8d84" lines=1 + } + } +} + +fragment JourneyNew text="" { + HoverBox color="#231d1a" radius=8 goto="journey-new" { + Inset top=6 bottom=6 left=10 right=8 { + Flex axis=horizontal align=center spacing=8 { + Image src="plus.svg" width=13 color="#9c8d84" + Text text=$text size=13 color="#9c8d84" lines=1 weight=1 + } + } + } +} + +// the lit journey, at the board's bottom +fragment JourneyBar name="" text="" try="" close="" { + Surface { Box color="#1a1614" radius=999 border=1 borderColor="#ff5f3d" { + Inset top=4 bottom=4 left=14 right=10 { + Flex axis=horizontal align=center spacing=10 { + Image src="route.svg" width=14 color="#ff5f3d" + Text text=$name size=13 bold=true + Text text=$text size=12 color="#9c8d84" + Box color="#ff5f3d" radius=999 goto=$try { + Inset top=5 bottom=5 left=10 right=12 { + Flex axis=horizontal align=center spacing=6 { Image src="play.svg" width=12 color="#0e0b0a" Text text="Try it" size=12 bold=true color="#0e0b0a" } + } + } + Keycap text="Esc" goto=$close + } + } + } } +} + +fragment TrialExit { + Flex axis=horizontal align=center spacing=8 goto="try-exit" { + Keycap text="Esc" + Text text="Back to the board" size=13 color="#9c8d84" + } +} + +// the path's head, in the sidebar's place: the way out, the journey, where it started or got to +fragment TrialHead title="" text="" { + Flex axis=vertical align=stretch { + TrialExit + Inset top=12 left=6 { Text text=$title size=20 bold=true } + Inset top=2 left=6 bottom=12 { Text text=$text size=12 color="#9c8d84" } + HLine + Sized height=6 { Spacer } + } +} + +// a screen the journey went through, and what was clicked on it +fragment TrialStep n="" name="" did="" bg="#00000000" ring="#302824" num="#fbf3ee" color="#dccfc7" { + Box color=$bg radius=8 { + Inset top=7 bottom=7 left=8 right=8 { + Flex axis=horizontal align=center spacing=10 { + Sized width=22 height=22 { Overlay { Box color=$ring radius=11 fill=true { Spacer } Text text=$n size=12 color=$num } } + Flex axis=vertical spacing=1 weight=1 { + Text text=$name color=$color lines=1 + Text text=$did size=12 color="#9c8d84" lines=2 + } + } + } + } +} + +fragment TrialHere n="" name="" did="" { + TrialStep n=$n name=$name did=$did bg="#3a2019" ring="#ff5f3d" num="#ffffff" color="#fbf3ee" +} + +fragment TrialFinding text="" where="" color="#ffcf4a" { + Flex axis=horizontal spacing=10 { + Inset top=6 { Box color=$color radius=4 { Sized width=7 height=7 { Spacer } } } + Flex axis=vertical spacing=1 weight=1 { + Text text=$text color="#dccfc7" + Text text=$where size=12 color="#9c8d84" + } + } +} + +// under the app being tried: a step back, where it is, start over, the path shown or not +fragment TrialBar name="" back="#dccfc7" path="#ff9a80" pathBg="#3a2019" { + Pill top=4 bottom=4 left=4 right=4 { + Flex axis=horizontal align=center spacing=4 { + Tip text="Step back" key="" { Box radius=999 goto="try-back" { Inset all=6 { Image src="back.svg" width=16 color=$back } } } + Inset left=4 right=4 { Text text=$name bold=true } + Tip text="Start over" key="" { Box radius=999 goto="try-restart" { Inset all=6 { Image src="restart.svg" width=16 color="#dccfc7" } } } + Tip text="Path" key="" { Box color=$pathBg radius=999 goto="try-path" { Inset all=6 { Image src="route.svg" width=16 color=$path } } } + } + } +} diff --git a/appicons/restart.svg b/appicons/restart.svg new file mode 100644 index 0000000..8899d0e --- /dev/null +++ b/appicons/restart.svg @@ -0,0 +1 @@ + diff --git a/appicons/route.svg b/appicons/route.svg new file mode 100644 index 0000000..67fb7f0 --- /dev/null +++ b/appicons/route.svg @@ -0,0 +1 @@ + diff --git a/board.go b/board.go index d62343a..939d8a1 100644 --- a/board.go +++ b/board.go @@ -166,6 +166,21 @@ type board struct { // cover is the tag over the live frames that are not selected cover byte + // flags are the project's journeys, onWay the screens they go through, + // and lit the one shown, its way over the frames; none when way is nil. + flags []journeyFlag + onWay map[string]bool + lit string + way *way + // hits are where the last frame drew the flags and the route marks, and + // did the action of one clicked, which the caller does, then clears. + hits []boardHit + did string + // areas are where the screens' gotos are, which measure finds. + areas map[areaKey][]image.Rectangle + measure func(sc *dsl.Screen, px float32) []image.Rectangle + icons map[iconKey]paint.ImageOp + dots paint.ImageOp dotsKey image.Point @@ -235,6 +250,7 @@ func (b *board) loaded(reg *Registry, screens []*dsl.Screen, assets map[string][ contents[sc.Name] = c } b.contents = contents + maps.DeleteFunc(b.areas, func(k areaKey, _ []image.Rectangle) bool { return contents[k.screen].version != k.version }) if b.snaps != nil { drawn := func(name string) bool { _, ok := contents[name]; return ok } b.snaps.keep(drawn) @@ -556,15 +572,25 @@ func flowPlaces(screens []*dsl.Screen) map[string]f32.Point { // gotos lists the screens a node and its children lead to. func gotos(n *dsl.Node) []string { + var out []string + for _, n := range gotoNodes(n) { + v, _ := n.Prop(dsl.GotoProp) + out = append(out, v.Str) + } + return out +} + +// gotoNodes are the nodes a click on opens a screen, in the order written. +func gotoNodes(n *dsl.Node) []*dsl.Node { if n == nil { return nil } - var out []string + var out []*dsl.Node if v, ok := n.Prop(dsl.GotoProp); ok && v.Kind == dsl.String && v.Str != "" { - out = append(out, v.Str) + out = append(out, n) } for _, c := range n.Children { - out = append(out, gotos(c)...) + out = append(out, gotoNodes(c)...) } return out } @@ -611,6 +637,11 @@ var changedColor = color.NRGBA{R: 0x34, G: 0xe0, B: 0x8f, A: 0xff} // or the one of a frame the model changed. func (b *board) outlineColor(name, selected string) (color.NRGBA, bool) { switch { + case b.way != nil && b.way.step(name) >= 0: + return accent, true + case b.way != nil && name == selected: + // coral is the journey's while one is lit + return frameTitleColor, true case name == selected, b.picked[name]: return accent, true case b.outlined[name]: @@ -733,6 +764,9 @@ func (b *board) events(gtx layout.Context) bool { b.commitNote() b.startNote(e.Position, pxPerDp(gtx)) b.pressed, zoomed = false, true + case b.hitAt(e.Position) != "": + b.commitNote() + b.did, b.pressed = b.hitAt(e.Position), false case b.pressNote(e.Position, e.Time): default: for _, f := range slices.Backward(b.frames) { @@ -888,8 +922,9 @@ func (b *board) layout(gtx layout.Context, th *material.Theme, sess *Session, sc hi = f32.Pt(max(hi.X, places[i].X+float32(sc.Width)), max(hi.Y, places[i].Y+float32(sc.Height))) } if len(screens) > 0 { - b.zoom, b.offset = fitTo(hi.Sub(lo), b.size.Sub(b.covered), px) - b.offset = b.offset.Add(layout.FPt(b.covered)).Sub(lo.Mul(px * b.zoom)) + covered := b.covered.Add(image.Pt(0, b.flagsRoom(gtx))) + b.zoom, b.offset = fitTo(hi.Sub(lo), b.size.Sub(covered), px) + b.offset = b.offset.Add(layout.FPt(covered)).Sub(lo.Mul(px * b.zoom)) } else { b.zoom = 1 } @@ -945,18 +980,23 @@ func (b *board) layout(gtx layout.Context, th *material.Theme, sess *Session, sc } } } - layoutFlow(gtx, flowArrows(screens, rects, selected, float32(gtx.Dp(flowApart)))) + b.hits = b.hits[:0] + if b.way == nil { + layoutFlow(gtx, flowArrows(screens, rects, selected, float32(gtx.Dp(flowApart)))) + } for i, sc := range screens { place, r := places[i], rects[i] at := b.offset.Add(place.Mul(px * b.zoom)) size := image.Pt(gtx.Dp(unit.Dp(sc.Width)), gtx.Dp(unit.Dp(sc.Height))) b.frames = append(b.frames, boardFrame{sc.Name, place, image.Rectangle{Min: r.Min.Sub(image.Pt(0, titleH)), Max: r.Max}}) if titleFits(image.Rect(r.Min.X, r.Min.Y-titleH, r.Max.X, r.Min.Y), rects, i) { - dims := layoutFrameTitle(gtx, th, sc.Name, at, r.Dx()) - b.layoutTitleShimmer(gtx, th, sc.Name, at, r.Dx(), dims.Size) + left, right := b.titleMarks(gtx, th, sc.Name, r) + at, room := at.Add(f32.Pt(float32(left), 0)), r.Dx()-left-right + dims := layoutFrameTitle(gtx, th, sc.Name, at, room) + b.layoutTitleShimmer(gtx, th, sc.Name, at, room, dims.Size) if s, ok := statuses[sc.Name]; ok { gap := gtx.Dp(6) - layoutTitleStatus(gtx, th, s, image.Pt(r.Min.X+dims.Size.X+gap, int(at.Y)-gtx.Dp(frameTitle)-dims.Size.Y/2), r.Dx()-dims.Size.X-gap) + layoutTitleStatus(gtx, th, s, image.Pt(int(at.X)+dims.Size.X+gap, int(at.Y)-gtx.Dp(frameTitle)-dims.Size.Y/2), room-dims.Size.X-gap) } } @@ -994,6 +1034,11 @@ func (b *board) layout(gtx layout.Context, th *material.Theme, sess *Session, sc cl.Pop() st.Pop() } + if b.way != nil && b.way.step(sc.Name) < 0 { + veil := appCanvasBg + veil.A = veilAlpha + paint.FillShape(gtx.Ops, veil, clip.Rect(r).Op()) + } rounded.Pop() if col, ok := b.outlineColor(sc.Name, selected); ok { w := gtx.Dp(2) @@ -1007,6 +1052,10 @@ func (b *board) layout(gtx layout.Context, th *material.Theme, sess *Session, sc b.layoutMotion(gtx, sc.Name, r, radius) arriving() } + if b.way != nil { + b.layoutWay(gtx, screens, rects, px) + } + b.layoutFlags(gtx, th, screens, rects, titleH) b.renderNear(screens, rects, selected, px) framePlaces := make(map[string]f32.Point, len(b.frames)) for _, f := range b.frames { @@ -1019,6 +1068,8 @@ func (b *board) layout(gtx layout.Context, th *material.Theme, sess *Session, sc pointer.CursorGrabbing.Add(gtx.Ops) case b.hand(): pointer.CursorGrab.Add(gtx.Ops) + case b.hover && b.hitAt(b.pointer) != "": + pointer.CursorPointer.Add(gtx.Ops) case b.tool == toolNote: pointer.CursorCrosshair.Add(gtx.Ops) default: diff --git a/board_journeys.go b/board_journeys.go new file mode 100644 index 0000000..a43cb03 --- /dev/null +++ b/board_journeys.go @@ -0,0 +1,247 @@ +package gockup + +import ( + "image" + "image/color" + "slices" + "strconv" + + "gioui.org/f32" + "gioui.org/font" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/op/paint" + "gioui.org/unit" + "gioui.org/widget" + "gioui.org/widget/material" + + "github.com/lichdotdev/gockup/dsl" +) + +const ( + // all in dp + flagHeight, flagGap = 22, 4 + flagIcon, flagPlay = 12, 10 + flagPad = 8 + // flagRoom is how wide a flag may be over a frame narrower than it. + flagRoom = 160 + // markMin is the narrowest frame with room for the route mark. + markMin = 44 + badgeSize = 16 + ringRoom = 3 + ringRound = 5 + // veilAlpha dims the frames a lit journey does not go through. + veilAlpha = 0xa0 +) + +var ( + flagBg = color.NRGBA{R: 0x1a, G: 0x16, B: 0x14, A: 0xff} + flagBorder = color.NRGBA{R: 0x3a, G: 0x30, B: 0x2b, A: 0xff} + flagLitBg = color.NRGBA{R: 0x3a, G: 0x20, B: 0x19, A: 0xff} +) + +// journeyFlag is a journey's, over the screen it starts at. +type journeyFlag struct{ name, from string } + +// boardHit is a part of the board a click on does action. +type boardHit struct { + rect image.Rectangle + action string +} + +type areaKey struct { + screen string + version int + px float32 +} + +type iconKey struct { + name string + size int + color color.NRGBA +} + +// icon draws one of the app's icons, size pixels wide, its corner at at. +func (b *board) icon(gtx layout.Context, name string, size int, col color.NRGBA, at image.Point) { + key := iconKey{name, size, col} + img, ok := b.icons[key] + if !ok { + data, _ := appIconFS.ReadFile("appicons/" + name) + drawn, err := raster(name, data, image.Pt(size, size)) + if err != nil { + return + } + tint(drawn, col) + img = paint.NewImageOp(drawn) + if b.icons == nil { + b.icons = map[iconKey]paint.ImageOp{} + } + b.icons[key] = img + } + defer op.Offset(at).Push(gtx.Ops).Pop() + defer clip.Rect{Max: image.Pt(size, size)}.Push(gtx.Ops).Pop() + img.Add(gtx.Ops) + paint.PaintOp{}.Add(gtx.Ops) +} + +// boardText records a line of text at most width pixels wide. +func boardText(gtx layout.Context, th *material.Theme, text string, col color.NRGBA, width int) (layout.Dimensions, op.CallOp) { + m := op.Record(gtx.Ops) + paint.ColorOp{Color: col}.Add(gtx.Ops) + ink := m.Stop() + m = op.Record(gtx.Ops) + gtx.Constraints = layout.Constraints{Max: image.Pt(max(width, 0), gtx.Dp(40))} + dims := widget.Label{MaxLines: 1}.Layout(gtx, th.Shaper, font.Font{Typeface: "sans-serif"}, 12, text, ink) + return dims, m.Stop() +} + +// titleMarks draws what a frame's title has of the journeys: the step's number +// before it, with one lit, or the route mark at its end. It returns what they +// take of the title's room, left and right. +func (b *board) titleMarks(gtx layout.Context, th *material.Theme, screen string, r image.Rectangle) (left, right int) { + mid := r.Min.Y - gtx.Dp(frameTitle) - gtx.Sp(8) + if b.way != nil { + i := b.way.step(screen) + if i < 0 || !b.way.ordered { + return 0, 0 + } + d := gtx.Dp(badgeSize) + dims, call := boardText(gtx, th, strconv.Itoa(i+1), color.NRGBA{R: 0xff, G: 0xff, B: 0xff, A: 0xff}, gtx.Dp(40)) + w := max(d, dims.Size.X+gtx.Dp(8)) + at := image.Pt(r.Min.X, mid-d/2) + paint.FillShape(gtx.Ops, accent, clip.UniformRRect(image.Rectangle{Min: at, Max: at.Add(image.Pt(w, d))}, d/2).Op(gtx.Ops)) + st := op.Offset(at.Add(image.Pt((w-dims.Size.X)/2, (d-dims.Size.Y)/2))).Push(gtx.Ops) + call.Add(gtx.Ops) + st.Pop() + return w + gtx.Dp(6), 0 + } + if !b.onWay[screen] || r.Dx() < gtx.Dp(markMin) { + return 0, 0 + } + s := gtx.Dp(flagIcon) + at := image.Pt(r.Max.X-s, mid-s/2) + b.icon(gtx, "route.svg", s, accent, at) + b.hits = append(b.hits, boardHit{image.Rectangle{Min: at, Max: at.Add(image.Pt(s, s))}.Inset(-gtx.Dp(4)), "journeys-on:" + screen}) + return 0, s + gtx.Dp(6) +} + +// flagsRoom is how high the flags of a frame stand over its title, the most +// there are, for Fit to leave them in sight. +func (b *board) flagsRoom(gtx layout.Context) int { + over, most := map[string]int{}, 0 + for _, f := range b.flags { + over[f.from]++ + most = max(most, over[f.from]) + } + return most * gtx.Dp(flagHeight+flagGap) +} + +// layoutFlags draws each journey's flag over the screen it starts at, one +// over the other: a click on one lights it, on its play tries it. +func (b *board) layoutFlags(gtx layout.Context, th *material.Theme, screens []*dsl.Screen, rects []image.Rectangle, titleH int) { + h, gap, pad := gtx.Dp(flagHeight), gtx.Dp(flagGap), gtx.Dp(flagPad) + icon, play := gtx.Dp(flagIcon), gtx.Dp(flagPlay) + over := map[string]int{} + for _, f := range b.flags { + i := slices.IndexFunc(screens, func(sc *dsl.Screen) bool { return sc.Name == f.from }) + if i < 0 { + continue + } + over[f.from]++ + r := rects[i] + at := image.Pt(r.Min.X, r.Min.Y-titleH-over[f.from]*(h+gap)) + bg, border, col := flagBg, flagBorder, frameTitleColor + if f.name == b.lit { + bg, border, col = flagLitBg, accent, textColor + } + dims, call := boardText(gtx, th, f.name, col, max(r.Dx(), gtx.Dp(flagRoom))-2*pad-2*gap-icon-play) + box := image.Rectangle{Min: at, Max: at.Add(image.Pt(dims.Size.X+2*pad+2*gap+icon+play, h))} + if !box.Overlaps(image.Rectangle{Max: b.size}) || !titleFits(box, rects, i) || + slices.ContainsFunc(b.hits, func(h boardHit) bool { return h.rect.Overlaps(box) }) { + continue + } + pill := clip.UniformRRect(box, h/2) + paint.FillShape(gtx.Ops, bg, pill.Op(gtx.Ops)) + paint.FillShape(gtx.Ops, border, clip.Stroke{Path: pill.Path(gtx.Ops), Width: float32(gtx.Dp(1))}.Op()) + b.icon(gtx, "route.svg", icon, accent, at.Add(image.Pt(pad, (h-icon)/2))) + st := op.Offset(at.Add(image.Pt(pad+icon+gap, (h-dims.Size.Y)/2))).Push(gtx.Ops) + call.Add(gtx.Ops) + st.Pop() + b.icon(gtx, "play.svg", play, col, image.Pt(box.Max.X-pad-play, at.Y+(h-play)/2)) + split := box.Max.X - pad - play - gap + b.hits = append(b.hits, + boardHit{image.Rect(box.Min.X, box.Min.Y, split, box.Max.Y), "light:" + f.name}, + boardHit{image.Rect(split, box.Min.Y, box.Max.X, box.Max.Y), "try:" + f.name}) + } +} + +// layoutWay draws the lit journey over the frames: a ring around what is +// clicked on each screen, and an arrow from it to the screen it opens. +func (b *board) layoutWay(gtx layout.Context, screens []*dsl.Screen, rects []image.Rectangle, px float32) { + at := map[string]int{} + for i, sc := range screens { + at[sc.Name] = i + } + var arrows []flowArrow + asked := false + for _, s := range b.way.steps { + if s.prev < 0 { + continue + } + i, ok := at[b.way.steps[s.prev].screen] + if !ok { + continue + } + from := rects[i] + // one screen measured a frame: laying a journey's out at once is felt + areas, ok := b.areasOf(screens[i], px, !asked) + if !ok && !asked { + asked = true + } + if s.link < len(areas) && !areas[s.link].Empty() { + a := areas[s.link] + lo := layout.FPt(rects[i].Min).Add(layout.FPt(a.Min).Mul(b.zoom)) + hi := layout.FPt(rects[i].Min).Add(layout.FPt(a.Max).Mul(b.zoom)) + from = image.Rectangle{Min: lo.Round(), Max: hi.Round()}.Inset(-gtx.Dp(ringRoom)) + ring := clip.UniformRRect(from, min(gtx.Dp(ringRound), from.Dx()/2, from.Dy()/2)) + paint.FillShape(gtx.Ops, accent, clip.Stroke{Path: ring.Path(gtx.Ops), Width: float32(gtx.Dp(unit.Dp(2)))}.Op()) + } + if j, ok := at[s.screen]; ok && !rects[i].Overlaps(rects[j]) { + ends := slices.Clone(rects) + ends[i] = from + arrows = append(arrows, flowBetween(ends, i, j, 0, true)) + } + } + layoutFlow(gtx, arrows) + if asked { + gtx.Execute(op.InvalidateCmd{}) + } +} + +// areasOf is where sc's gotos are, in the layout's pixels; ok is false when +// they were not known yet, and they are measured now only if measure says. +func (b *board) areasOf(sc *dsl.Screen, px float32, measure bool) (areas []image.Rectangle, ok bool) { + key := areaKey{sc.Name, b.contents[sc.Name].version, px} + if areas, ok := b.areas[key]; ok { + return areas, true + } + if !measure || b.measure == nil { + return nil, b.measure == nil + } + if b.areas == nil { + b.areas = map[areaKey][]image.Rectangle{} + } + b.areas[key] = b.measure(sc, px) + return b.areas[key], false +} + +// hitAt is the action of what is at p, "" when it is none of the journeys'. +func (b *board) hitAt(p f32.Point) string { + for _, h := range slices.Backward(b.hits) { + if p.Round().In(h.rect) { + return h.action + } + } + return "" +} diff --git a/changes.go b/changes.go index e626172..ff32eb2 100644 --- a/changes.go +++ b/changes.go @@ -9,10 +9,16 @@ type change struct { } // toastOpen is the action of a click on the toast: selecting the item it -// names, a note's screen for a note; none for one deleted or a free note. +// names, a note's screen for a note and a journey's first; none for one deleted or a free note. func (a *studio) toastOpen() string { c := a.toast[0] kind, name := c.decl.Kind, c.decl.Name + if kind == dsl.JourneyDecl && a.file != nil { + kind, name = dsl.ScreenDecl, "" + if j := a.file.Journey(c.decl.Name); j != nil { + name = j.From + } + } if kind == dsl.NoteDecl && a.file != nil { kind, name = dsl.ScreenDecl, "" if n := a.file.Note(c.decl.Name); n != nil { diff --git a/docs/AUTHORING.md b/docs/AUTHORING.md index 33081a6..e9947eb 100644 --- a/docs/AUTHORING.md +++ b/docs/AUTHORING.md @@ -7,7 +7,11 @@ What a mockup of more than one screen needs, learned building lich's screens wit - A project's **fragments** are its component library (Window, Sidebar, SessionRow, MenuItem…): every screen of the project sees all of them, no import needed. - A screen per **state** of a flow (Session → Menu → Confirm); `goto="Screen"` on the node you would click - links them, so the app walks the flow. + links them, so the app walks the flow; `goto=back` on a back arrow or a Cancel opens, while a journey is tried, + wherever the user came from. +- 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. - `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 a369d04..241097a 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -30,7 +30,9 @@ screen "Profile" { Card title="Account" { Body1 text="ana@example.com" } } Fragments can live in their own files: `import "lib/shared.gockup"` pulls in that file's fragments (its screens stay its own showcase). Layout primitives: `Flex`, `Inset`, `Box`, `Center`, `Spacer`, `Sized`, `Scroll` and `Overlay` (draw an open menu or a dialog over a base); `Box border=1 borderColor=` outlines a card, and -`Image src="logo.svg"` draws an asset (.svg or .png, `color=` repaints a one-color icon). `goto="Screen"` on any node walks a flow in the preview, `note "Why" on="Login" status=decided text="…"` +`Image src="logo.svg"` draws an asset (.svg or .png, `color=` repaints a one-color icon). `goto="Screen"` on any node walks a flow in the preview, +`journey "Create account" from="Login" to="Welcome"` names a way through the app, shown on the board and to try as if it +were working (there, `goto=back` opens the screen the user came from), `note "Why" on="Login" status=decided text="…"` leaves context on the board for whoever reads the project next, the model included, `theme=` on a screen picks a look. [AUTHORING.md](AUTHORING.md) is the guide for mockups of many screens. @@ -111,8 +113,8 @@ The `mcp` command serves it on stdio, window or not: `claude mcp add gockup -- g Tools: `list_design_systems`, `add_design_system`, `remove_design_system`, `list_components`, `list_projects`, `create_project`, `rename_project`, `delete_project`, `list_assets`, `add_asset`, `delete_asset`, `read_project`, `read_item`, `list_places`, `place_screens` (where frames sit on the board, moved as one undoable change), -`write_item` (one screen, fragment or note; the whole project is validated, nothing invalid is written), `edit_item` -(replace a snippet), `rename_item` (the gotos, calls and notes pointing at it follow), `delete_item`, `move_item`, `validate_item`, `render_screen` (PNG via the headless GPU renderer), +`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. The `from_app` prompt (`/mcp__gockup__from_app` in Claude Code) mocks up an app you already have: the diff --git a/docs/ceilings.md b/docs/ceilings.md index baf8fea..d003728 100644 --- a/docs/ceilings.md +++ b/docs/ceilings.md @@ -42,7 +42,14 @@ file is the trap alone. - **Events queued between two frames are in the last frame's places**: a handle that moves with what it drags (the sidebar's edge) measures from where it was laid out (`sideLaid`), or it overshoots and flickers. - **A goto passes its click on** to what is under it, so nested gotos all fire. Something that must take a - click alone, as a dialog's veil, is a builtin with an area of its own (`Veil`), never a `Box goto`. + click alone, as a dialog's veil, is a builtin with an area of its own (`Veil`), never a `Box goto`. Trying a + journey takes the innermost one only, as one step. +- **Where a goto is on its screen comes from Gio's semantic tree** (`Session.gotoAreas`): Gio tells no widget its + 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 click that did nothing is told by the state its node keeps** (`Session.answers`): a leaf that keeps only a + `widget.Clickable`, or nothing, did nothing without a goto. An adapter with a click type of its own passes for + one that answers, so its dead buttons are not told; a bare `Box` or `Spacer` never is. - **The window's keys are read on every page** by the `WindowKeys` builtin `overPage` adds; a key for the whole window goes in `windowKeys` and in the `shortcuts` table, which Ctrl+/ shows. @@ -63,7 +70,8 @@ file is the trap alone. - **A note's place lives in its source**: moving or editing a note in the window rewrites its declaration and drops the comments above it. - **`edit_item` refuses a rename that leaves a goto behind**; `rename_item` is the one that carries the - gotos, calls and notes along. + gotos, calls, notes and journeys along. +- **A screen a journey starts at or goes to cannot be deleted** before the journey is, as one a goto leads to. - **The window serves MCP from its own connection** (`serveMCPHTTP`): the window learns of a write by SQLite's `data_version`, which only moves for another connection's writes. - **What the user has seen is a print of each item** (`seen.go`), kept in `projects.seen`: whatever differs is told as diff --git a/dsl/decl.go b/dsl/decl.go index ce04e2b..9b27632 100644 --- a/dsl/decl.go +++ b/dsl/decl.go @@ -13,6 +13,7 @@ const ( FragmentDecl DeclKind = "fragment" ScreenDecl DeclKind = "screen" NoteDecl DeclKind = "note" + JourneyDecl DeclKind = "journey" ) // Decl is one top-level declaration kept on its own, as a project stores it. @@ -26,7 +27,7 @@ type Decl struct { // Label names the declaration in error messages. func (d Decl) Label() string { - if d.Kind == ScreenDecl || d.Kind == NoteDecl { + if d.Kind != FragmentDecl { return string(d.Kind) + " " + strconv.Quote(d.Name) } return string(d.Kind) + " " + d.Name @@ -44,6 +45,9 @@ func ParseDecl(text string) (Decl, error) { if len(f.Notes) == 1 { return Decl{Kind: NoteDecl, Name: f.Notes[0].Name, Text: f.Notes[0].Source}, nil } + if len(f.Journeys) == 1 { + return Decl{Kind: JourneyDecl, Name: f.Journeys[0].Name, Text: f.Journeys[0].Source}, nil + } return Decl{Kind: ScreenDecl, Name: f.Screens[0].Name, Text: f.Screens[0].Source}, nil } @@ -68,8 +72,8 @@ func parseOne(text string) (*File, error) { if len(imports) > 0 { return nil, &Error{imports[0].line, "a stored declaration cannot import; its project's fragments are already in scope"} } - if n := len(f.Fragments) + len(f.Screens) + len(f.Notes); n != 1 { - return nil, &Error{1, fmt.Sprintf("expected exactly one fragment, screen or note, got %d", n)} + if n := len(f.Fragments) + len(f.Screens) + len(f.Notes) + len(f.Journeys); n != 1 { + return nil, &Error{1, fmt.Sprintf("expected exactly one fragment, screen, note or journey, got %d", n)} } return f, nil } @@ -102,9 +106,15 @@ func ParseDecls(decls []Decl) (*File, error) { return nil, fmt.Errorf("%s: duplicate note", label) } } + for _, j := range sub.Journeys { + if f.Journey(j.Name) != nil { + return nil, fmt.Errorf("%s: duplicate journey", label) + } + } f.Fragments = append(f.Fragments, sub.Fragments...) f.Screens = append(f.Screens, sub.Screens...) f.Notes = append(f.Notes, sub.Notes...) + f.Journeys = append(f.Journeys, sub.Journeys...) } if err := expandFile(f); err != nil { return nil, err @@ -129,6 +139,9 @@ func SplitFile(path string) ([]Decl, error) { for _, n := range f.Notes { decls = append(decls, Decl{NoteDecl, n.Name, n.Source, ""}) } + for _, j := range f.Journeys { + decls = append(decls, Decl{JourneyDecl, j.Name, j.Source, ""}) + } return decls, nil } diff --git a/dsl/dsl.go b/dsl/dsl.go index 7c888da..c6e321d 100644 --- a/dsl/dsl.go +++ b/dsl/dsl.go @@ -111,6 +111,7 @@ type File struct { Screens []*Screen Fragments []*Fragment Notes []*Note + Journeys []*Journey // Deps are the files imported, directly or not, so a watcher reloads on their edits too. Deps []string } @@ -333,6 +334,18 @@ func parseRaw(src string) (*File, []importDecl, error) { f.Notes = append(f.Notes, n) return nil } + if start.kind == tIdent && start.text == "journey" { + j, err := p.journey() + if err != nil { + return err + } + if f.Journey(j.Name) != nil { + return &Error{j.Line, fmt.Sprintf("duplicate journey %q", j.Name)} + } + j.Source = source(start) + f.Journeys = append(f.Journeys, j) + return nil + } if start.kind == tIdent && start.text == "fragment" { fr, err := p.fragment() if err != nil { diff --git a/dsl/fragment.go b/dsl/fragment.go index b839942..68998ec 100644 --- a/dsl/fragment.go +++ b/dsl/fragment.go @@ -14,6 +14,12 @@ const WeightProp = "weight" // screen it names, to walk through a flow. const GotoProp = "goto" +// Back is goto's value, an identifier, for where the user came from. +const Back = "back" + +// IsBack reports whether a goto's value is Back, and not a screen so named. +func IsBack(v Value) bool { return v.Kind == Ident && v.Str == Back } + // IsUniversal reports whether every node takes the prop, whatever its type. func IsUniversal(name string) bool { return name == WeightProp || name == GotoProp } diff --git a/dsl/journey.go b/dsl/journey.go new file mode 100644 index 0000000..d1a7f33 --- /dev/null +++ b/dsl/journey.go @@ -0,0 +1,59 @@ +package dsl + +import "fmt" + +// Journey is a way through the app to try: where it starts and, when it says, +// the screen it is meant to get to. +// +// journey "Create account" from="Login" via="Register" to="Welcome" +type Journey struct { + Name, From, To string + // Via is a screen the way goes through, when the shortest one does not. + Via string + Line int + // Source is the declaration's text, the comments above it included. + Source string +} + +func (p *parser) journey() (*Journey, error) { + kw := p.next() + name, err := p.expect(tString, "journey name string") + if err != nil { + return nil, err + } + props, err := p.props() + if err != nil { + return nil, err + } + j := &Journey{Name: name.text, Line: kw.line} + for _, pr := range props { + if pr.Name != "from" && pr.Name != "via" && pr.Name != "to" { + return nil, &Error{pr.Line, fmt.Sprintf("unknown journey property %q; a journey has from, via and to", pr.Name)} + } + if pr.Value.Kind != String { + return nil, &Error{pr.Line, pr.Name + " must be a screen's name, a string"} + } + switch pr.Name { + case "from": + j.From = pr.Value.Str + case "via": + j.Via = pr.Value.Str + default: + j.To = pr.Value.Str + } + } + if j.Name == "" || j.From == "" { + return nil, &Error{kw.line, "a journey needs a name and the screen it starts from, from="} + } + return j, nil +} + +// Journey returns the journey named name, or nil. +func (f *File) Journey(name string) *Journey { + for _, j := range f.Journeys { + if j.Name == name { + return j + } + } + return nil +} diff --git a/dsl/journey_test.go b/dsl/journey_test.go new file mode 100644 index 0000000..19e0add --- /dev/null +++ b/dsl/journey_test.go @@ -0,0 +1,54 @@ +package dsl + +import ( + "strings" + "testing" +) + +func TestJourney(t *testing.T) { + f, err := Parse(`screen "A" { Box } +// the main one +journey "Sign up" from="A" to="B" +journey "Look around" from="A" via="C"`) + if err != nil { + t.Fatal(err) + } + j := f.Journey("Sign up") + if j == nil || j.From != "A" || j.To != "B" || !strings.HasPrefix(j.Source, "// the main one\njourney") { + t.Errorf("Sign up = %+v", j) + } + if j := f.Journey("Look around"); j == nil || j.To != "" || j.Via != "C" { + t.Errorf("Look around = %+v", j) + } + for src, want := range map[string]string{ + `journey "X"`: "needs a name and the screen it starts from", + `journey "X" from=A`: "from must be a screen's name", + `journey "X" from="A" by="B"`: `unknown journey property "by"`, + `journey "X" from="A"` + "\n" + `journey "X" from="B"`: `duplicate journey "X"`, + } { + if _, err := Parse(src); err == nil || !strings.Contains(err.Error(), want) { + t.Errorf("%s: err = %v, want %q", src, err, want) + } + } +} + +func TestRenameReachesJourneys(t *testing.T) { + decls := []Decl{ + {Kind: ScreenDecl, Name: "A", Text: `screen "A" { Box goto=back }`}, + {Kind: JourneyDecl, Name: "A", Text: `journey "A" from="A" via="A" to="A"`}, + } + got, err := RenameScreen(decls, "A", "Login") + if err != nil { + t.Fatal(err) + } + if want := `journey "A" from="Login" via="Login" to="Login"`; got[1].Text != want || got[1].Name != "A" { + t.Errorf("after the screen's rename: %+v, want %s", got[1], want) + } + got, err = RenameJourney(decls, "A", "Sign up") + if err != nil { + t.Fatal(err) + } + if want := `journey "Sign up" from="A" via="A" to="A"`; got[1].Text != want || got[1].Name != "Sign up" || got[0].Text != decls[0].Text { + t.Errorf("after its own rename: %+v", got) + } +} diff --git a/dsl/rename.go b/dsl/rename.go index d3da729..defd4ad 100644 --- a/dsl/rename.go +++ b/dsl/rename.go @@ -7,17 +7,24 @@ import ( ) // RenameScreen renames a screen, every goto leading to it, the ones written -// as a fragment's argument that reaches a goto inside it too, and the notes -// pinned to it. +// as a fragment's argument that reaches a goto inside it too, the notes +// pinned to it and the journeys from it, through it and to it. func RenameScreen(decls []Decl, old, name string) ([]Decl, error) { if name == "" { return nil, fmt.Errorf("a screen needs a name") } return renameStrings(decls, ScreenDecl, old, name, func(comp, prop string) bool { - return prop == GotoProp || comp == "note" && prop == "on" + return prop == GotoProp || comp == "note" && prop == "on" || comp == "journey" && (prop == "from" || prop == "via" || prop == "to") }) } +func RenameJourney(decls []Decl, old, name string) ([]Decl, error) { + if name == "" { + return nil, fmt.Errorf("a journey needs a name") + } + return renameStrings(decls, JourneyDecl, old, name, func(string, string) bool { return false }) +} + // RenameAsset renames an asset in every Image src drawing it, the ones written // as a fragment's argument that reaches an Image's src too. func RenameAsset(decls []Decl, old, name string) ([]Decl, error) { @@ -123,10 +130,10 @@ func renameStrings(decls []Decl, kind DeclKind, old, name string, target func(co at = append(at, v) } } - if kind == ScreenDecl && d.Kind == ScreenDecl && d.Name == old { + if kind != "" && d.Kind == kind && d.Name == old { // the header: screen "old" for j, tk := range toks { - if tk.kind == tIdent && tk.text == "screen" && toks[j+1].kind == tString { + if tk.kind == tIdent && tk.text == string(kind) && toks[j+1].kind == tString { at = append(at, toks[j+1]) break } diff --git a/gockup.go b/gockup.go index 12348a5..8ec953e 100644 --- a/gockup.go +++ b/gockup.go @@ -19,6 +19,7 @@ import ( "gioui.org/op/clip" "gioui.org/op/paint" "gioui.org/unit" + "gioui.org/widget" "github.com/lichdotdev/gockup/dsl" ) @@ -228,7 +229,7 @@ func (r *Registry) Validate(f *dsl.File) []Problem { } if p.Name == GotoProp { // "" is no link: the default of a fragment's optional one - if p.Value.Kind != dsl.String || p.Value.Str != "" && f.Screen(p.Value.Str) == nil { + if !dsl.IsBack(p.Value) && (p.Value.Kind != dsl.String || p.Value.Str != "" && f.Screen(p.Value.Str) == nil) { probs = append(probs, Problem{Line: p.Line, Msg: fmt.Sprintf("goto must name a screen of this file, got %s", p.Value), File: p.File}) } continue @@ -276,6 +277,14 @@ func (r *Registry) Validate(f *dsl.File) []Problem { probs = append(probs, Problem{Line: n.Line, Msg: fmt.Sprintf("on must name a screen of this project, got %q", n.On), File: label}) } } + for _, j := range f.Journeys { + for _, end := range [][2]string{{"from", j.From}, {"via", j.Via}, {"to", j.To}} { + if end[1] != "" && f.Screen(end[1]) == nil { + label := dsl.Decl{Kind: dsl.JourneyDecl, Name: j.Name}.Label() + probs = append(probs, Problem{Line: j.Line, Msg: fmt.Sprintf("%s must name a screen of this project, got %q", end[0], end[1]), File: label}) + } + } + } return probs } @@ -338,6 +347,18 @@ type Session struct { // Goto, when set, makes nodes with goto="Screen" clickable and is called // with the screen to open; the preview sets it, offscreen renders do not. Goto func(screen string) + // back does the same for goto=back; without it one does nothing. + back func() + // idle, when set, is called with what a click landed on and did nothing. + idle func(n *dsl.Node) + // clicked is the node whose goto runs; went tells one already ran this frame, and + // hit is the leaf a click landed on, with its path. + clicked *dsl.Node + // measured are the gotos gotoAreas is after, by node. + measured map[*dsl.Node]int + went bool + hit *dsl.Node + hitPath string reg *Registry state map[string]map[string]*stateEntry // by screen, then by node path and state type @@ -384,7 +405,11 @@ func (s *Session) Layout(gtx layout.Context, sc *dsl.Screen) layout.Dimensions { bg, env = th.Background, &envEntry{key: ThemeKey{}, val: th.Value} } paint.FillShape(gtx.Ops, bg, clip.Rect{Max: gtx.Constraints.Max}.Op()) + s.went, s.hit = false, nil dims := s.layoutNode(gtx, sc.Root, sc.Root.Type, env) + if s.hit != nil && !s.went && !s.answers(s.hitPath) { + s.idle(s.hit) + } // shortcut: state not requested this frame is dropped, so an adapter that // skips laying out a child loses its state; track liveness per subtree if // conditional or virtualized layouts appear. @@ -402,11 +427,18 @@ func (s *Session) layoutNode(gtx layout.Context, n *dsl.Node, path string, env * return errorBox(gtx, fmt.Sprintf("unknown component %q", n.Type)) } ctx := &Ctx{Gtx: gtx, node: n, comp: c, path: path, sess: s, env: env} - var dims layout.Dimensions + lay := c.Layout if v, ok := n.Prop(GotoProp); ok && v.Kind == dsl.String && v.Str != "" && s.Goto != nil { - dims = s.layoutGoto(ctx, v.Str) - } else { - dims = c.Layout(ctx) + lay = func(c *Ctx) layout.Dimensions { return s.layoutGoto(c, func() { s.Goto(v.Str) }) } + } else if dsl.IsBack(v) && s.back != nil { + lay = func(c *Ctx) layout.Dimensions { return s.layoutGoto(c, s.back) } + } + dims := lay(ctx) + if i, ok := s.measured[n]; ok { + markArea(gtx.Ops, i, dims.Size) + } + if s.idle != nil && len(n.Children) == 0 && n.Type != "Spacer" && n.Type != "Box" { + s.watchClicks(ctx, dims.Size) } if h := s.highlight; h.off > 0 && n.WrittenAt(h.file, h.off) { w := gtx.Dp(2) @@ -428,9 +460,56 @@ var highlightColor = color.NRGBA{R: 0xff, G: 0x5f, B: 0x3d, A: 0xff} type gotoClick struct{ pressed bool } +// watchClick tells the clicks on a leaf, which its own handlers get too. +type watchClick struct{ pressed bool } + +// watchClicks notes a click on the node just laid out, size big: the last one +// noted is the one on top. +func (s *Session) watchClicks(c *Ctx, size image.Point) { + click := State[watchClick](c, nil) + for { + ev, ok := c.Gtx.Event(pointer.Filter{Target: click, Kinds: pointer.Press | pointer.Release | pointer.Cancel}) + if !ok { + break + } + switch e, _ := ev.(pointer.Event); e.Kind { + case pointer.Press: + click.pressed = e.Source != pointer.Mouse || e.Buttons.Contain(pointer.ButtonPrimary) + case pointer.Release: + if click.pressed { + s.hit, s.hitPath = c.node, c.path + } + click.pressed = false + case pointer.Cancel: + click.pressed = false + } + } + defer clip.Rect{Max: size}.Push(c.Gtx.Ops).Pop() + defer pointer.PassOp{}.Push(c.Gtx.Ops).Pop() + event.Op(c.Gtx.Ops, click) +} + +// answers reports whether the node at path, or one it is in, does something +// with a click of its own: it keeps a state other than a click's or a +// scroll's, as a field or a switch does. +func (s *Session) answers(path string) bool { + for key, e := range s.cur { + at, _, _ := strings.Cut(key, "|") + if at != path && !strings.HasPrefix(path, at+"/") { + continue + } + switch e.v.(type) { + case *widget.Clickable, *gotoClick, *watchClick, *layout.List, *widget.List: + default: + return true + } + } + return false +} + // layoutGoto lays the node out and lays a click area over it that lets the // node's own pointer handlers see the same events. -func (s *Session) layoutGoto(c *Ctx, screen string) layout.Dimensions { +func (s *Session) layoutGoto(c *Ctx, open func()) layout.Dimensions { click := State[gotoClick](c, nil) for { ev, ok := c.Gtx.Event(pointer.Filter{Target: click, Kinds: pointer.Press | pointer.Release | pointer.Cancel}) @@ -443,7 +522,9 @@ func (s *Session) layoutGoto(c *Ctx, screen string) layout.Dimensions { click.pressed = e.Source != pointer.Mouse || e.Buttons.Contain(pointer.ButtonPrimary) case pointer.Release: if click.pressed { - s.Goto(screen) + s.clicked = c.node + open() + s.went = true } click.pressed = false case pointer.Cancel: diff --git a/gockup_test.go b/gockup_test.go index f0505e0..25579f5 100644 --- a/gockup_test.go +++ b/gockup_test.go @@ -892,6 +892,33 @@ func TestMCPNotes(t *testing.T) { } } +func TestMCPJourneys(t *testing.T) { + resps := mcpCall(t, NewRegistry(), testDB(t), + call("create_project", map[string]any{"project": "P"}), + call("write_item", map[string]any{"project": "P", "source": `screen "A" { Spacer goto=back }`}), + call("write_item", map[string]any{"project": "P", "source": `journey "J" from="A"`}), + call("rename_item", map[string]any{"project": "P", "kind": "screen", "name": "A", "new": "Login"}), + call("rename_item", map[string]any{"project": "P", "kind": "journey", "name": "J", "new": "Sign up"}), + call("read_project", map[string]any{"project": "P"}), + call("write_item", map[string]any{"project": "P", "source": `journey "Lost" from="Nope"`}), + call("delete_item", map[string]any{"project": "P", "kind": "screen", "name": "Login"}), + call("delete_item", map[string]any{"project": "P", "kind": "journey", "name": "Sign up"}), + ) + for _, i := range []int{1, 2, 3, 4, 8} { + if txt, isErr := toolText(t, resps[i]); isErr { + t.Errorf("call %d: %s", i, txt) + } + } + if txt, _ := toolText(t, resps[5]); !strings.Contains(txt, `journey "Sign up" from="Login"`) { + t.Errorf("after the renames:\n%s", txt) + } + for _, i := range []int{6, 7} { + if txt, isErr := toolText(t, resps[i]); !isErr || !strings.Contains(txt, "from must name a screen") { + t.Errorf("call %d went through: %q", i, txt) + } + } +} + func TestMCPRenameItemTakesWhatPointsAtIt(t *testing.T) { db := testDB(t) resps := mcpCall(t, NewRegistry(), db, diff --git a/journeys.go b/journeys.go new file mode 100644 index 0000000..3c536ba --- /dev/null +++ b/journeys.go @@ -0,0 +1,252 @@ +package gockup + +import ( + "fmt" + "image" + "slices" + "strconv" + "strings" + + "gioui.org/io/input" + "gioui.org/io/semantic" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/op/clip" + "gioui.org/unit" + + "github.com/lichdotdev/gockup/dsl" +) + +// way is the screens a journey goes through, the first it starts at. +type way struct { + steps []wayStep + // ordered is a single way; a journey with no end has every screen its + // start leads to. + ordered bool + // lost is the screen it is via or to that no click leads to, "" for none. + lost string +} + +type wayStep struct { + screen string + // prev is the step whose click opens this one and link which of that + // screen's gotos it is, as gotoNodes lists them; -1 on the first. + prev, link int +} + +func (w way) step(screen string) int { + return slices.IndexFunc(w.steps, func(s wayStep) bool { return s.screen == screen }) +} + +// wayOf finds the way of a journey: the shortest to its end, through the +// screen it is via, or every screen its start leads to when it has neither. +func wayOf(f *dsl.File, j *dsl.Journey) way { + if j.Via == "" && j.To == "" { + return way{steps: reachable(f, j.From)} + } + w := way{steps: []wayStep{{j.From, -1, -1}}, ordered: true} + for _, to := range []string{j.Via, j.To} { + if to == "" { + continue + } + last := len(w.steps) - 1 + all := reachable(f, w.steps[last].screen) + i := slices.IndexFunc(all, func(s wayStep) bool { return s.screen == to }) + if i < 0 { + w.lost = to + return w + } + var leg []wayStep + for ; i > 0; i = all[i].prev { + leg = append(leg, all[i]) + } + slices.Reverse(leg) + for k := range leg { + leg[k].prev = last + k + } + w.steps = append(w.steps, leg...) + } + return w +} + +// reachable are the screens from leads to, the nearest first, itself the first. +func reachable(f *dsl.File, from string) []wayStep { + all := way{steps: []wayStep{{from, -1, -1}}} + for i := 0; i < len(all.steps); i++ { + sc := f.Screen(all.steps[i].screen) + if sc == nil { + continue + } + for link, next := range gotos(sc.Root) { + if f.Screen(next) != nil && all.step(next) < 0 { + all.steps = append(all.steps, wayStep{next, i, link}) + } + } + } + return all.steps +} + +// areaLabel starts the semantic labels gotoAreas finds the gotos by. +const areaLabel = "gockup goto " + +// gotoAreas lays sc out, px pixels per dp, and returns where each of its +// gotos is, as gotoNodes lists them; an empty one is out of sight. +func (s *Session) gotoAreas(sc *dsl.Screen, px float32) []image.Rectangle { + nodes := gotoNodes(sc.Root) + s.measured = make(map[*dsl.Node]int, len(nodes)) + for i, n := range nodes { + s.measured[n] = i + } + defer func() { s.measured = nil }() + var router input.Router + ops := new(op.Ops) + metric := unit.Metric{PxPerDp: px, PxPerSp: px} + s.Layout(layout.Context{ + Ops: ops, Source: router.Source(), Metric: metric, + 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)) + for _, n := range router.AppendSemantics(nil) { + if at, ok := strings.CutPrefix(n.Desc.Label, areaLabel); ok { + if i, err := strconv.Atoi(at); err == nil { + areas[i] = n.Desc.Bounds + } + } + } + return areas +} + +// markArea labels the area of a node being measured, size big. +func markArea(ops *op.Ops, i int, size image.Point) { + defer clip.Rect{Max: size}.Push(ops).Pop() + semantic.LabelOp(areaLabel + strconv.Itoa(i)).Add(ops) +} + +// loadJourneys finds the way of each journey of the project just loaded. +func (a *studio) loadJourneys() { + a.ways, a.board.flags, a.board.onWay = map[string]way{}, nil, map[string]bool{} + if a.file != nil { + for _, j := range a.file.Journeys { + w := wayOf(a.file, j) + a.ways[j.Name] = w + a.board.flags = append(a.board.flags, journeyFlag{name: j.Name, from: j.From}) + for _, s := range w.steps { + a.board.onWay[s.screen] = true + } + } + } + if _, ok := a.ways[a.lit]; !ok { + a.lit = "" + } +} + +// lightJourney shows a journey on the board, going to its first screen when the +// board is on others, or stops showing it. +func (a *studio) lightJourney(name string) { + w, ok := a.ways[name] + if !ok || a.lit == name { + a.lit = "" + return + } + a.lit, a.picked = name, nil + from := w.steps[0].screen + onBoard := slices.ContainsFunc(a.boardScreens(), func(sc *dsl.Screen) bool { return sc.Name == from }) + if a.selKind == dsl.ScreenDecl && onBoard { + return + } + a.selKind, a.selName, a.tab, a.board.focus = dsl.ScreenDecl, from, dsl.ScreenDecl, from + if i := findDecl(a.decls, dsl.ScreenDecl, from); i >= 0 && a.pages() != nil { + a.enterPage(a.decls[i].Group) + } +} + +// journeysOn opens the journeys with one that goes through screen lit. +func (a *studio) journeysOn(screen string) { + a.journeysOpen = true + for _, f := range a.board.flags { + if a.ways[f.name].step(screen) >= 0 { + a.lit = f.name + return + } + } +} + +const ( + // journeysRoom is the most the journeys take of the sidebar, in dp, before + // they scroll. + journeysRoom = 280 + journeyRowRoom = 32 + journeyStepRoom = 24 +) + +// journeysSection writes the sidebar's journeys, under its tree: the lit one +// with the screens it goes through and what is clicked to leave each. +func (a *studio) journeysSection(b *strings.Builder) { + room := 0 + var rows strings.Builder + for _, f := range a.board.flags { + ref := string(dsl.JourneyDecl) + ":" + f.name + room += journeyRowRoom + if a.renaming == ref { + fmt.Fprintf(&rows, "RenameRow name=%q icon=\"route.svg\" iconColor=\"#ff5f3d\" key=%q submit=%q\n", f.name, ref, "rename-to:"+ref+groupSep) + continue + } + if f.name != a.lit { + fmt.Fprintf(&rows, "JourneyRow name=%q open=%q try=%q\n", f.name, "light:"+f.name, "try:"+f.name) + continue + } + trash := "#9c8d84" + if a.confirm == "del:"+ref { + trash = errColor + } + fmt.Fprintf(&rows, "JourneyLitRow name=%q open=%q try=%q rename=%q delete=%q trash=%q\n", + f.name, "light:"+f.name, "try:"+f.name, "journey-rename:"+ref, "del:"+ref, trash) + w := a.ways[f.name] + for i, s := range w.steps { + n := "·" + if w.ordered { + n = strconv.Itoa(i + 1) + } + did := "" + if w.ordered && i+1 < len(w.steps) { + did = nodeText(gotoNodes(a.file.Screen(s.screen).Root)[w.steps[i+1].link]) + } + fmt.Fprintf(&rows, "JourneyStep n=%q name=%q did=%q open=%q\n", n, s.screen, did, "toast-go:sel:screen:"+s.screen) + room += journeyStepRoom + } + if w.lost != "" { + fmt.Fprintf(&rows, "Inset left=30 top=4 bottom=4 { Text text=%q size=12 color=%q }\n", "No click leads to "+w.lost, warnColor) + room += journeyStepRoom + } + } + fmt.Fprintf(b, "JourneysSection count=\"%d\" {\n", len(a.board.flags)) + if room > journeysRoom { + fmt.Fprintf(b, "Sized height=%d { Scroll axis=vertical {\n%s} }\n", journeysRoom, rows.String()) + } else { + b.WriteString(rows.String()) + } + if a.selKind == dsl.ScreenDecl && a.selName != "" { + fmt.Fprintf(b, "JourneyNew text=%q\n", "New journey from "+a.selName) + } else if len(a.board.flags) == 0 { + b.WriteString("Inset left=10 top=4 bottom=8 { Text text=\"Select a screen to start a journey from it.\" size=12 color=\"#9c8d84\" }\n") + } + b.WriteString("}\n") +} + +// newJourney makes a journey from the selected screen, its name to be written. +func (a *studio) newJourney() error { + if a.selKind != dsl.ScreenDecl || a.selName == "" { + return nil + } + name := "" + for i := 1; name == "" || findDecl(a.decls, dsl.JourneyDecl, name) >= 0; i++ { + name = fmt.Sprintf("Journey %d", i) + } + d := dsl.Decl{Kind: dsl.JourneyDecl, Name: name, Text: fmt.Sprintf("journey %s from=%s", strconv.Quote(name), strconv.Quote(a.selName))} + if err := a.db.Put(a.project, "", d); err != nil { + return err + } + a.lit, a.renaming = name, string(dsl.JourneyDecl)+":"+name + return nil +} diff --git a/journeys_test.go b/journeys_test.go new file mode 100644 index 0000000..48f7a68 --- /dev/null +++ b/journeys_test.go @@ -0,0 +1,163 @@ +package gockup + +import ( + "image" + "slices" + "strings" + "testing" + + "gioui.org/f32" + "gioui.org/layout" + + "github.com/lichdotdev/gockup/dsl" +) + +func screensOf(w way) string { + var out []string + for _, s := range w.steps { + out = append(out, s.screen) + } + return strings.Join(out, " ") +} + +func TestWayOf(t *testing.T) { + f, err := dsl.Parse(` +screen "A" { Flex { Box goto="Long" Box goto=back Box goto="B" } } +screen "Long" { Box goto="Longer" } +screen "Longer" { Box goto="End" } +screen "B" { Flex { Box goto="A" Box goto="End" } } +screen "End" { Box } +screen "Alone" { Box }`) + if err != nil { + t.Fatal(err) + } + w := wayOf(f, &dsl.Journey{From: "A", To: "End"}) + if screensOf(w) != "A B End" || !w.ordered || w.steps[1].link != 1 || w.steps[2].link != 1 || w.steps[2].prev != 1 { + t.Errorf("the shortest way: %+v", w) + } + if w := wayOf(f, &dsl.Journey{From: "A", To: ""}); screensOf(w) != "A Long B Longer End" || w.ordered { + t.Errorf("no end: %+v", w) + } + if w := wayOf(f, &dsl.Journey{From: "A", To: "Alone"}); screensOf(w) != "A" || w.lost != "Alone" { + t.Errorf("an end no click leads to: %+v", w) + } + w = wayOf(f, &dsl.Journey{From: "A", Via: "Longer", To: "End"}) + if screensOf(w) != "A Long Longer End" || w.steps[3].prev != 2 || w.steps[1].link != 0 { + t.Errorf("via Longer: %+v", w) + } + if w := wayOf(f, &dsl.Journey{From: "A", Via: "B"}); screensOf(w) != "A B" || !w.ordered { + t.Errorf("via B with no end: %+v", w) + } + if w := wayOf(f, &dsl.Journey{From: "A", Via: "Alone", To: "End"}); w.lost != "Alone" { + t.Errorf("via a screen no click leads to: %+v", w) + } + if w := wayOf(f, &dsl.Journey{From: "A", To: "A"}); screensOf(w) != "A" || w.lost != "" { + t.Errorf("to where it starts: %+v", w) + } +} + +func TestGotoAreas(t *testing.T) { + r := NewRegistry() + r.Register("Cell", Component{Layout: func(c *Ctx) layout.Dimensions { return layout.Dimensions{Size: image.Pt(40, 20)} }}) + f, _, err := r.LoadSource(`screen "A" width=200 height=100 { Inset left=10 top=30 { Flex axis=horizontal spacing=6 { Cell goto="A" Cell Cell goto="A" } } }`, "") + if err != nil { + t.Fatal(err) + } + got := NewSession(r).gotoAreas(f.Screens[0], 1) + if want := []image.Rectangle{image.Rect(10, 30, 50, 50), image.Rect(102, 30, 142, 50)}; !slices.Equal(got, want) { + t.Errorf("areas = %v, want %v", got, want) + } +} + +// hit is the middle of what does action on the board. +func (s *noteStudio) hit(action string) f32.Point { + s.t.Helper() + for _, h := range s.a.board.hits { + if h.action == action { + return layout.FPt(h.rect.Min.Add(h.rect.Max)).Mul(0.5) + } + } + s.t.Fatalf("nothing on the board does %q: %v", action, s.a.board.hits) + return f32.Point{} +} + +func TestJourneyOnTheBoard(t *testing.T) { + s := newJourneyStudio(t) + s.act("sel:screen:Register") + s.act("zoom-fit") + if s.a.journeysOpen || strings.Contains(s.a.projectScreen(), "JourneysSection") { + t.Error("the journeys are listed before they are asked for") + } + selected, offset := s.a.selName, s.a.board.offset + s.click(s.hit("light:Create account")) + if s.a.lit != "Create account" || s.a.journeysOpen || s.a.selName != selected || s.a.board.offset != offset { + t.Fatalf("the flag: lit %q, list open %v, selected %q, board moved %v", s.a.lit, s.a.journeysOpen, s.a.selName, s.a.board.offset != offset) + } + for range 4 { + s.frame() + } + if len(s.a.board.areas) != 2 { + t.Errorf("%d screens measured, want Login and Register", len(s.a.board.areas)) + } + s.a.escape() + if s.a.lit != "" { + t.Error("Esc left the journey lit") + } + s.frame() + s.click(s.hit("journeys-on:Register")) + if !s.a.journeysOpen || s.a.lit != "Create account" { + t.Errorf("the route mark: list open %v, lit %q", s.a.journeysOpen, s.a.lit) + } + s.frame() + s.click(s.hit("try:Create account")) + if !s.a.trial.on() { + t.Error("the flag's play does not try the journey") + } + s.frame() +} + +func TestJourneysList(t *testing.T) { + s := newJourneyStudio(t) + s.act("sel:screen:Register") + s.act("journeys") + s.act("light:Create account") + src := s.a.projectScreen() + for _, want := range []string{`JourneyStep n="1" name="Login" did="Create an account"`, `JourneyStep n="3" name="Welcome" did=""`} { + if !strings.Contains(src, want) { + t.Errorf("no %s in the list", want) + } + } + s.act("journey-new") + if s.a.renaming != "journey:Journey 1" || s.a.file.Journey("Journey 1") == nil || s.a.file.Journey("Journey 1").From != "Register" { + t.Fatalf("new: renaming %q, status %q", s.a.renaming, s.a.status) + } + s.act("rename-to:journey:Journey 1" + groupSep + "Sign up") + if s.a.file.Journey("Sign up") == nil || s.a.lit != "Sign up" { + t.Fatalf("rename: status %q, lit %q", s.a.status, s.a.lit) + } + s.act("del:journey:Sign up") + if s.a.file.Journey("Sign up") == nil { + t.Fatal("deleted at the first click") + } + s.act("del:journey:Sign up") + if s.a.file.Journey("Sign up") != nil || s.a.lit != "" { + t.Errorf("deleted: status %q, lit %q", s.a.status, s.a.lit) + } + s.act("journeys") + if strings.Contains(s.a.projectScreen(), "JourneysSection") { + t.Error("the icon does not close the list") + } +} + +func TestLightingAJourneyOfAnotherPageOpensIt(t *testing.T) { + decls := journeyDecls() + for i := range decls[:4] { + decls[i].Group = "Account" + } + s := newNoteStudio(t, decls...) + s.act("page-all") + s.act("light:Create account") + if !s.a.paged || s.a.page != "Account" || s.a.selName != "Login" { + t.Errorf("paged %v, page %q, selected %q", s.a.paged, s.a.page, s.a.selName) + } +} diff --git a/mcp.go b/mcp.go index 3cf15dc..f862ffa 100644 --- a/mcp.go +++ b/mcp.go @@ -58,6 +58,12 @@ screen "Name" width=360 height=640 theme=dark { // size in dp, defaults 360x64 - Image src="logo.svg" draws an asset of the project (.svg or .png; add_asset adds one); width or height alone keeps its aspect, color="#rrggbb" repaints a one-color icon. - goto="Screen" on any node makes it open that screen when clicked in the app or preview, to walk a flow. + goto=back, an identifier, opens the screen the user came from while a journey is tried. +- Journeys are the ways through the app the user tries as if it were working, one item each: + 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. - 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." @@ -255,11 +261,11 @@ func schema(props map[string]any, required ...string) map[string]any { var ( projectArg = map[string]any{"type": "string", "description": "project name"} - kindArg = map[string]any{"type": "string", "enum": []string{string(dsl.ScreenDecl), string(dsl.FragmentDecl), string(dsl.NoteDecl)}, "description": "screen, fragment (a reusable component) or note"} - nameArg = map[string]any{"type": "string", "description": "the screen's, fragment's or note's name"} + kindArg = map[string]any{"type": "string", "enum": []string{string(dsl.ScreenDecl), string(dsl.FragmentDecl), string(dsl.NoteDecl), string(dsl.JourneyDecl)}, "description": "screen, fragment (a reusable component), note or journey"} + nameArg = map[string]any{"type": "string", "description": "the screen's, fragment's, note's or journey's name"} groupArg = map[string]any{"type": "string", "description": "the group (a sidebar folder: a flow of screens, a family of fragments); omit to keep the item's, empty for none"} designSystemArg = map[string]any{"type": "string", "description": "a design system list_design_systems names; the default when omitted"} - sourceArg = map[string]any{"type": "string", "description": "exactly one declaration: a screen \"Name\" { … }, a fragment Name { … } or a note \"Name\" on=\"Screen\" status=todo text=\"…\""} + sourceArg = map[string]any{"type": "string", "description": "exactly one declaration: a screen \"Name\" { … }, a fragment Name { … }, a note \"Name\" on=\"Screen\" status=todo text=\"…\" or a journey \"Name\" from=\"Screen\" via=\"Screen\" to=\"Screen\""} tools = []map[string]any{ {"name": "list_components", "description": "Syntax reference and every component of a design system with its properties: the project's, the one named, or the default.", "inputSchema": schema(map[string]any{"project": projectArg, "design_system": designSystemArg})}, @@ -302,9 +308,9 @@ var ( "inputSchema": schema(map[string]any{"project": projectArg, "name": map[string]any{"type": "string"}}, "project", "name")}, {"name": "read_project", "description": "Read a whole project as one .gockup text: its fragments, then its screens, in order.", "inputSchema": schema(map[string]any{"project": projectArg}, "project")}, - {"name": "read_item", "description": "Read one screen, fragment or note of a project; a screen comes with the notes pinned to it.", + {"name": "read_item", "description": "Read one screen, fragment, note or journey of a project; a screen comes with the notes pinned to it.", "inputSchema": schema(map[string]any{"project": projectArg, "kind": kindArg, "name": nameArg}, "project", "kind", "name")}, - {"name": "write_item", "description": "Create a screen, fragment or note, or replace the one of the same kind and name. " + + {"name": "write_item", "description": "Create a screen, fragment, note or journey, or replace the one of the same kind and name. " + "The whole project is validated with it first and nothing is written if it has problems.", "inputSchema": schema(map[string]any{"project": projectArg, "source": sourceArg, "group": groupArg}, "project", "source")}, {"name": "group_item", "description": "Put a screen or fragment in a group, the folders of the sidebar (screens and fragments have their own); an empty group takes it out.", @@ -317,12 +323,12 @@ var ( "new": map[string]any{"type": "string", "description": "replacement text"}, "all": map[string]any{"type": "boolean", "description": "replace every occurrence"}, }, "project", "kind", "name", "old", "new")}, - {"name": "rename_item", "description": "Rename a screen or fragment; the gotos, calls and notes pointing at it follow, one change the user can undo.", + {"name": "rename_item", "description": "Rename a screen, fragment or journey; the gotos, calls, notes and journeys pointing at it follow, one change the user can undo.", "inputSchema": schema(map[string]any{ "project": projectArg, "kind": kindArg, "name": nameArg, "new": map[string]any{"type": "string", "description": "the new name"}, }, "project", "kind", "name", "new")}, - {"name": "delete_item", "description": "Delete a screen, fragment or note; a screen goes with the notes pinned to it. Refused if the rest of the project would stop being valid (a goto or a call still uses it).", + {"name": "delete_item", "description": "Delete a screen, fragment, note or journey; a screen goes with the notes pinned to it. Refused if the rest of the project would stop being valid (a goto, a call or a journey still uses it).", "inputSchema": schema(map[string]any{"project": projectArg, "kind": kindArg, "name": nameArg}, "project", "kind", "name")}, {"name": "move_item", "description": "Move a screen or fragment to position among its kind (0 is first; clamped to the ends).", "inputSchema": schema(map[string]any{ @@ -660,8 +666,10 @@ func (s *mcpServer) renameItem(project string, kind dsl.DeclKind, name, to strin next, err = dsl.RenameScreen(decls, name, to) case dsl.FragmentDecl: next, err = dsl.RenameFragment(decls, name, to) + case dsl.JourneyDecl: + next, err = dsl.RenameJourney(decls, name, to) default: - return toolResult{}, fmt.Errorf("rename_item renames a screen or a fragment, not a %s", kind) + return toolResult{}, fmt.Errorf("rename_item renames a screen, a fragment or a journey, not a %s", kind) } if err != nil { return toolResult{}, err diff --git a/notes_test.go b/notes_test.go index dbf18a5..045b793 100644 --- a/notes_test.go +++ b/notes_test.go @@ -28,12 +28,16 @@ type noteStudio struct { } func newNoteStudio(t *testing.T, decls ...dsl.Decl) *noteStudio { + return newStudioDrawing(t, NewRegistry(), decls...) +} + +func newStudioDrawing(t *testing.T, reg *Registry, decls ...dsl.Decl) *noteStudio { db := testDB(t) all := append([]dsl.Decl{{Kind: dsl.ScreenDecl, Name: "A", Text: `screen "A" width=360 height=640 { Spacer }`}}, decls...) if err := db.Replace("P", all, nil); err != nil { t.Fatal(err) } - s := ¬eStudio{t: t, a: newStudio(single(NewRegistry()), db, func() {})} + s := ¬eStudio{t: t, a: newStudio(single(reg), db, func() {})} s.a.act("open:P") s.frame() s.frame() @@ -41,6 +45,9 @@ func newNoteStudio(t *testing.T, decls ...dsl.Decl) *noteStudio { } func (s *noteStudio) frame() { + // as the window: a snapshot's layout waits for it + s.a.mu.Lock() + defer s.a.mu.Unlock() ops := new(op.Ops) s.a.uiSess.Layout(layout.Context{Ops: ops, Source: s.router.Source(), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(image.Pt(1200, 800))}, s.a.view) s.router.Frame(ops) diff --git a/present.go b/present.go index 6003a9b..60fb14e 100644 --- a/present.go +++ b/present.go @@ -86,8 +86,7 @@ func (a *studio) presentScreen() string { return b.String() } -// layoutPresented lays the presented screen out live, in the middle of the -// window at its own size, smaller when it does not fit; the arrow keys go +// layoutPresented lays the presented screen out alone; the arrow keys go // through the page. func (a *studio) layoutPresented(gtx layout.Context) layout.Dimensions { for { @@ -103,19 +102,25 @@ func (a *studio) layoutPresented(gtx layout.Context) layout.Dimensions { } } } - room := gtx.Constraints.Max sc := a.file.Screen(a.presenting) if sc == nil { - return layout.Dimensions{Size: room} + return layout.Dimensions{Size: gtx.Constraints.Max} } + return layoutAlone(gtx, a.sess, sc, 0) +} + +// layoutAlone lays sc out live in the middle of the window right of left, in +// pixels, at its own size, smaller when it does not fit. +func layoutAlone(gtx layout.Context, sess *Session, sc *dsl.Screen, left int) layout.Dimensions { + room := gtx.Constraints.Max size := image.Pt(gtx.Dp(unit.Dp(sc.Width)), gtx.Dp(unit.Dp(sc.Height))) - free := room.Sub(image.Pt(0, 2*gtx.Dp(presentRoom))) + 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 := layout.FPt(room).Sub(layout.FPt(size).Mul(k)).Mul(0.5) + at := f32.Pt(float32(left), 0).Add(layout.FPt(room.Sub(image.Pt(left, 0))).Sub(layout.FPt(size).Mul(k)).Mul(0.5)) 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 fgtx.Constraints = layout.Exact(size) - a.sess.Layout(fgtx, sc) + sess.Layout(fgtx, sc) return layout.Dimensions{Size: room} } diff --git a/shortcuts.go b/shortcuts.go index 478fa87..cbf88f6 100644 --- a/shortcuts.go +++ b/shortcuts.go @@ -33,7 +33,7 @@ var shortcuts = []struct { {"Undo", []string{"Ctrl Z"}}, {"Redo", []string{"Ctrl Shift Z"}}, {"Duplicate", []string{"Ctrl D"}}, {"Export PNG", []string{"Ctrl Shift E"}}, {"Delete note", []string{"Del"}}, {"Rename", []string{"Double click"}}, }}, - {"GO", []shortcut{{"Present", []string{"P"}}, {"Present: next, previous", []string{"→", "←"}}, {"Search", []string{"Ctrl K"}}, {"Shortcuts", []string{"Ctrl /"}}, {"Close, deselect", []string{"Esc"}}}}, + {"GO", []shortcut{{"Journeys", []string{"J"}}, {"Present", []string{"P"}}, {"Present: next, previous", []string{"→", "←"}}, {"Search", []string{"Ctrl K"}}, {"Shortcuts", []string{"Ctrl /"}}, {"Close, deselect", []string{"Esc"}}}}, } // shortcutsDialog writes the shortcuts list, its groups in two columns. @@ -95,6 +95,8 @@ func (a *studio) escape() { switch { case a.dialog != "": a.act("dialog-close") + case a.trial.on(): + a.act("try-exit") case a.presenting != "": a.act("present-exit") case a.board.cancelNote(): @@ -110,6 +112,10 @@ func (a *studio) escape() { a.invalidate() case a.settings: a.act("settings-close") + case a.lit != "": + a.act("light:" + a.lit) + case a.journeysOpen: + a.act("journeys") } } diff --git a/store/store.go b/store/store.go index bb49fe0..d706a48 100644 --- a/store/store.go +++ b/store/store.go @@ -101,6 +101,16 @@ var migrations = []string{ // the items as the user last saw them, JSON of prints by label; NULL // before anything was kept `ALTER TABLE projects ADD COLUMN seen TEXT`, + `CREATE TABLE journeys ( + id INTEGER PRIMARY KEY, + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + name TEXT NOT NULL, + position INTEGER NOT NULL, + source TEXT NOT NULL, + grp TEXT NOT NULL DEFAULT '', + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, + UNIQUE (project_id, name) + )`, } // historyLimit is how many changes of a project Undo can take back. @@ -116,7 +126,7 @@ const ( // tables maps a declaration kind to the table holding it; it is also the // whitelist that keeps a kind from a client out of the SQL text. -var tables = map[dsl.DeclKind]string{dsl.FragmentDecl: "components", dsl.ScreenDecl: "screens", dsl.NoteDecl: "notes"} +var tables = map[dsl.DeclKind]string{dsl.FragmentDecl: "components", dsl.ScreenDecl: "screens", dsl.NoteDecl: "notes", dsl.JourneyDecl: "journeys"} // ErrNotFound is returned for a project or item that does not exist. var ErrNotFound = errors.New("not found") @@ -307,7 +317,8 @@ func (d *DB) DeleteProject(name string) error { return affected(res, err, "project "+name) } -// Decls returns the project's components, its screens, then its notes, each in order. +// Decls returns the project's components, its screens, its notes, then its +// journeys, each in order. func (d *DB) Decls(project string) ([]dsl.Decl, error) { id, err := projectID(d.db, project) if err != nil { @@ -318,7 +329,7 @@ func (d *DB) Decls(project string) ([]dsl.Decl, error) { func decls(q querier, id int64) ([]dsl.Decl, error) { var decls []dsl.Decl - for _, kind := range []dsl.DeclKind{dsl.FragmentDecl, dsl.ScreenDecl, dsl.NoteDecl} { + for _, kind := range []dsl.DeclKind{dsl.FragmentDecl, dsl.ScreenDecl, dsl.NoteDecl, dsl.JourneyDecl} { rows, err := q.Query("SELECT name, source, grp FROM "+tables[kind]+" WHERE project_id = ? ORDER BY position", id) if err != nil { return nil, err @@ -1056,7 +1067,7 @@ func projectID(q querier, name string) (int64, error) { func table(kind dsl.DeclKind) (string, error) { t, ok := tables[kind] if !ok { - return "", fmt.Errorf("kind must be %q, %q or %q, got %q", dsl.ScreenDecl, dsl.FragmentDecl, dsl.NoteDecl, kind) + return "", fmt.Errorf("kind must be %q, %q, %q or %q, got %q", dsl.ScreenDecl, dsl.FragmentDecl, dsl.NoteDecl, dsl.JourneyDecl, kind) } return t, nil } diff --git a/store/store_test.go b/store/store_test.go index 097d367..29627b1 100644 --- a/store/store_test.go +++ b/store/store_test.go @@ -633,6 +633,29 @@ func TestNotesAreStoredAndUndone(t *testing.T) { } } +func TestJourneysAreStoredAndUndone(t *testing.T) { + db := open(t) + j := dsl.Decl{Kind: dsl.JourneyDecl, Name: "J", Text: `journey "J" from="A"`} + if err := db.Replace("P", []dsl.Decl{screen("A")}, nil); err != nil { + t.Fatal(err) + } + if err := db.Put("P", "", j); err != nil { + t.Fatal(err) + } + if err := db.Delete("P", dsl.JourneyDecl, "J"); err != nil { + t.Fatal(err) + } + if got := names(t, db, "P"); got != "screen:A" { + t.Errorf("after deleting it: %s", got) + } + if err := db.Undo("P", time.Time{}); err != nil { + t.Fatal(err) + } + if got := names(t, db, "P"); got != "screen:A journey:J" { + t.Errorf("after undoing: %s", got) + } +} + func TestSettings(t *testing.T) { db := open(t) if v, err := db.Setting("theme"); v != "" || err != nil { diff --git a/theme.go b/theme.go index 60c1421..8b93c4f 100644 --- a/theme.go +++ b/theme.go @@ -66,6 +66,7 @@ var ( &appCanvasBg, &textColor, &tipBg, &tipKey, &dotColor, &dotLit, &frameTitleColor, &accent, &changedColor, &highlightColor, ¬eBg, ¬eBorder, ¬eTextColor, ¬eMuted, ¬eAccent, ¬eDelete, &todoColor, &doingColor, &decidedColor, ¬eSelect, &lapColor, &flowColor, + &flagBg, &flagBorder, &flagLitBg, } darks = func() []color.NRGBA { out := make([]color.NRGBA, len(themed)) diff --git a/tip_test.go b/tip_test.go new file mode 100644 index 0000000..d5e1b86 --- /dev/null +++ b/tip_test.go @@ -0,0 +1,73 @@ +package gockup + +import ( + "image" + "testing" + + "gioui.org/f32" + "gioui.org/io/pointer" + "gioui.org/layout" + "gioui.org/op" + "gioui.org/unit" +) + +// The top bar is against the window's edge: a tip over its buttons is cut. +func TestTopBarTipsOpenBelowIt(t *testing.T) { + s := newJourneyStudio(t) + s.act("sel:screen:Login") + hovered := func() *tipState { + for _, e := range s.a.uiSess.state[s.a.view.Name] { + if h, ok := e.v.(*tipState); ok && h.hover { + return h + } + } + return nil + } + painted := func() (above, below int) { + // laid out with the test's router: a render has no pointer over anything + ops := new(op.Ops) + size := image.Pt(1200, 800) + s.a.uiSess.Layout(layout.Context{Ops: ops, Source: s.router.Source(), Metric: unit.Metric{PxPerDp: 1, PxPerSp: 1}, Constraints: layout.Exact(size)}, s.a.view) + renderMu.Lock() + defer renderMu.Unlock() + w, err := offscreenOf(size) + if err != nil { + t.Fatal(err) + } + if err := w.Frame(ops); err != nil { + t.Fatal(err) + } + img := image.NewRGBA(image.Rectangle{Max: w.Size()}) + if err := w.Screenshot(img); err != nil { + t.Fatal(err) + } + for y := range 100 { + for x := 800; x < 1200; x++ { + if r, g, b, _ := img.At(x, y).RGBA(); r>>8 == uint32(tipBg.R) && g>>8 == uint32(tipBg.G) && b>>8 == uint32(tipBg.B) { + if y < 8 { + above++ + } else if y >= topSpan { + below++ + } + } + } + } + return above, below + } + seen := map[*tipState]bool{} + for x := float32(900); x < 1200; x += 8 { + s.send(pointer.Event{Kind: pointer.Move, Source: pointer.Mouse, Position: f32.Pt(x, 30)}) + s.frame() + h := hovered() + if h == nil || seen[h] { + continue + } + seen[h] = true + if above, below := painted(); above > 0 || below == 0 { + t.Errorf("tip of the button at %v: %d pixels above the bar, %d below", x, above, below) + } + } + if len(seen) != 2 { + t.Errorf("%d tips in the top bar, want the journeys' and Present's", len(seen)) + } +} diff --git a/trial.go b/trial.go new file mode 100644 index 0000000..8ad661b --- /dev/null +++ b/trial.go @@ -0,0 +1,301 @@ +package gockup + +import ( + "fmt" + "image" + "slices" + "strconv" + "strings" + "unicode/utf8" + + "gioui.org/layout" + "gioui.org/unit" + + "github.com/lichdotdev/gockup/dsl" +) + +const ( + // trialStepsShown is how many steps the path lists, the last ones. + trialStepsShown = 8 + // trialNamesShown is how many places a finding names. + trialNamesShown = 3 + // trialLabel is the length of a clicked thing's text in the path, in runes. + trialLabel = 28 +) + +// trial is a journey being tried: the app alone in the window, answering as +// it would, and the path walked. +type trial struct { + journey string // "" when none is + from string + via string + to string + // sess is the trial's own: what is typed in it starts empty and lasts + // from a screen to the next. + sess *Session + steps []trialStep + idle []idleClick +} + +type trialStep struct { + screen string + // did is what was clicked on the screen to leave it, "" on the last. + did string + // from are the screens goto=back goes back through, the last first left. + from []string +} + +// idleClick is something clicked that did nothing. +type idleClick struct{ what, screen string } + +func (t *trial) on() bool { return t.journey != "" } + +func (t *trial) screen() string { return t.steps[len(t.steps)-1].screen } + +// try starts the journey named name. +func (a *studio) try(name string) { + if a.file == nil { + return + } + j := a.file.Journey(name) + if j == nil || a.file.Screen(j.From) == nil { + return + } + a.dialog, a.menu, a.renaming, a.picked = "", "", "", nil + a.trial = trial{journey: j.Name, from: j.From, via: j.Via, to: j.To} + a.restartTrial() +} + +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) + // called while a frame is laid out, with a.mu already held + t.sess.Goto = func(screen string) { + a.innermost() + at := t.steps[len(t.steps)-1] + a.walk(screen, append(slices.Clone(at.from), at.screen)) + } + t.sess.back = func() { + a.innermost() + from := t.steps[len(t.steps)-1].from + if n := len(from); n > 0 { + a.walk(from[n-1], from[:n-1]) + } + } + t.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() + } + } +} + +// 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.trialBack() + } +} + +// walk takes the trial to screen by the click that just came. +func (a *studio) walk(screen string, from []string) { + t := &a.trial + t.steps[len(t.steps)-1].did = nodeText(t.sess.clicked) + t.steps = append(t.steps, trialStep{screen: screen, from: from}) + a.regen() + a.invalidate() +} + +// trialBack takes the last step back, as if it was not walked. +func (a *studio) trialBack() { + t := &a.trial + if n := len(t.steps); n > 1 { + t.steps = t.steps[:n-1] + t.steps[n-2].did = "" + } +} + +func (a *studio) trialExit() { + if !a.trial.on() { + return + } + a.selKind, a.selName = dsl.ScreenDecl, a.trial.screen() + a.board.focus, a.trial = a.selName, trial{} +} + +// keepTrying goes on with the trial over a project just loaded, or ends it +// when a screen it walked is gone. +func (a *studio) keepTrying() { + t := &a.trial + if !t.on() { + return + } + gone := func(s trialStep) bool { return a.file.Screen(s.screen) == nil } + switch { + case a.file == nil || slices.ContainsFunc(t.steps, gone): + *t = trial{} + case t.sess.reg != a.reg: + a.restartTrial() + default: + t.sess.SetAssets(a.assets) + } +} + +// nodeText is what a node says, for the path to tell what was clicked: the +// first text in it, or its component's name. +func nodeText(n *dsl.Node) string { + var find func(n *dsl.Node) string + find = func(n *dsl.Node) string { + for _, name := range []string{"text", "label", "title", "name"} { + if v, ok := n.Prop(name); ok && v.Kind == dsl.String && strings.TrimSpace(v.Str) != "" { + return strings.Join(strings.Fields(v.Str), " ") + } + } + for _, c := range n.Children { + if s := find(c); s != "" { + return s + } + } + return "" + } + s := find(n) + if s == "" { + return n.Type + } + if utf8.RuneCountInString(s) > trialLabel { + s = strings.TrimSpace(string([]rune(s)[:trialLabel])) + "…" + } + return s +} + +// 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 + 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 +} + +// 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)} + pages := map[string]bool{} + for _, d := range a.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 { + if d.Kind == dsl.ScreenDecl && pages[d.Group] && reached.step(d.Name) < 0 { + out = append(out, d.Name) + } + } + return out +} + +// someOf lists the first names, and how many more there are. +func someOf(names []string) string { + if n := len(names) - trialNamesShown; n > 0 { + return strings.Join(names[:trialNamesShown], ", ") + fmt.Sprintf(" and %d more", n) + } + return strings.Join(names, ", ") +} + +// trialScreen is the window while a journey is tried: the app alone, the bar +// under it, and the path in the sidebar's place unless it is hidden. +func (a *studio) trialScreen() string { + t := &a.trial + left := 0 + if !a.pathHidden { + left = a.sidebarSpan() + } + var b strings.Builder + b.WriteString("screen \"trial\" { Overlay align=nw {\nBox color=\"#0e0b0a\" fill=true { Spacer }\n") + fmt.Fprintf(&b, "Tried left=%d\n", left) + back, path, pathBg := mutedColor, pickedText, pickedFill + if len(t.steps) > 1 { + back = "#dccfc7" + } + if a.pathHidden { + path, pathBg = "#9c8d84", "#00000000" + b.WriteString("Inset left=16 top=16 { Pill top=6 bottom=6 left=8 right=14 { TrialExit } }\n") + } else { + a.trialPath(&b) + } + fmt.Fprintf(&b, "Inset left=%d bottom=16 { Flex axis=vertical { Spacer weight=1\nFlex axis=horizontal { Spacer weight=1\nTrialBar name=%q back=%q path=%q pathBg=%q\nSpacer weight=1 } } }\n", + left, t.screen(), back, path, pathBg) + b.WriteString("} }\n") + return b.String() +} + +// trialPath writes the steps walked and, at the journey's end, how it went. +func (a *studio) trialPath(b *strings.Builder) { + t := &a.trial + arrived := a.arrived() + text := "Started at " + t.from + if arrived { + text = "Got to " + t.screen() + " in " + plural(len(t.steps), "step") + } + fmt.Fprintf(b, "Sidebar width=%d {\nTrialHead title=%q text=%q\n", a.sideWidth, t.journey, text) + first := max(0, len(t.steps)-trialStepsShown) + if first > 0 { + fmt.Fprintf(b, "Inset left=8 top=4 bottom=4 { Text text=%q size=12 color=\"#9c8d84\" }\n", plural(first, "step")+" before") + } + for i := first; i < len(t.steps); i++ { + s := t.steps[i] + n := strconv.Itoa(i + 1) + switch { + case i < len(t.steps)-1: + fmt.Fprintf(b, "TrialStep n=%q name=%q did=%q\n", n, s.screen, "Clicked "+s.did) + case arrived: + fmt.Fprintf(b, "TrialHere n=%q name=%q did=\"The end\"\n", n, s.screen) + default: + fmt.Fprintf(b, "TrialHere n=%q name=%q did=\"You are here\"\n", n, s.screen) + } + } + if arrived { + a.trialFindings(b) + } + b.WriteString("}\n") +} + +func (a *studio) trialFindings(b *strings.Builder) { + b.WriteString("Inset top=12 bottom=10 { HLine }\nInset left=8 { Flex axis=vertical spacing=12 align=stretch {\nText text=\"WHAT IT SHOWED\" size=11 bold=true color=\"#80726a\"\n") + idle := make([]string, len(a.trial.idle)) + for i, c := range a.trial.idle { + idle[i] = c.what + " on " + c.screen + } + unopened := a.unopened() + if len(idle) > 0 { + fmt.Fprintf(b, "TrialFinding text=%q where=%q color=%q\n", plural(len(idle), "click")+" did nothing", someOf(idle), warnColor) + } + if len(unopened) > 0 { + fmt.Fprintf(b, "TrialFinding text=%q where=%q color=\"#4db5ff\"\n", plural(len(unopened), "screen")+" no click opens", someOf(unopened)) + } + if len(idle)+len(unopened) == 0 { + fmt.Fprintf(b, "TrialFinding text=\"Every click answered\" where=\"and every screen of its pages can be reached\" color=%q\n", okColor) + } + b.WriteString("} }\n") +} + +func (a *studio) layoutTried(c *Ctx) layout.Dimensions { + gtx := c.Gtx + sc := a.file.Screen(a.trial.screen()) + if sc == nil { + return layout.Dimensions{Size: image.Pt(gtx.Constraints.Max.X, gtx.Constraints.Max.Y)} + } + return layoutAlone(gtx, a.trial.sess, sc, gtx.Dp(unit.Dp(c.Number("left")))) +} diff --git a/trial_test.go b/trial_test.go new file mode 100644 index 0000000..02287c9 --- /dev/null +++ b/trial_test.go @@ -0,0 +1,211 @@ +package gockup + +import ( + "image" + "slices" + "strings" + "testing" + + "gioui.org/f32" + "gioui.org/layout" + "gioui.org/widget" + + "github.com/lichdotdev/gockup/dsl" +) + +func journeyDecls() []dsl.Decl { + screen := func(name, body string) dsl.Decl { + return dsl.Decl{Kind: dsl.ScreenDecl, Name: name, Text: `screen "` + name + `" width=360 height=640 { ` + body + ` }`} + } + return []dsl.Decl{ + screen("Login", `Flex axis=vertical { + Sized width=360 height=100 goto="Register" { Text text="Create an account" } + Sized width=360 height=100 { Text text="Forgot it" } + Toggle + }`), + screen("Register", `Flex axis=vertical { + Sized width=360 height=100 goto="Welcome" { Text text="Create" } + Sized width=360 height=100 goto=back { Text text="Cancel" } + }`), + screen("Welcome", `Text text="Hello"`), + screen("Locked", `Text text="Too many tries"`), + {Kind: dsl.JourneyDecl, Name: "Create account", Text: `journey "Create account" from="Login" to="Welcome"`}, + } +} + +// newJourneyStudio is the app on the journey's project, its Text a box of its +// own size and its Toggle a switch. +func newJourneyStudio(t *testing.T) *noteStudio { + reg := NewRegistry() + box := func(layout.Context) layout.Dimensions { return layout.Dimensions{Size: image.Pt(360, 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{Layout: func(c *Ctx) layout.Dimensions { + return State[widget.Bool](c, nil).Layout(c.Gtx, box) + }}) + return newStudioDrawing(t, reg, journeyDecls()...) +} + +// newTrial tries the journey, its screen drawn at 1:1 right of the path. +func newTrial(t *testing.T) *noteStudio { + s := newJourneyStudio(t) + s.act("try:Create account") + return s +} + +// act does an action and draws what it opened, for the clicks after it. +func (s *noteStudio) act(action string) { + s.a.act(action) + s.frame() + s.frame() +} + +// clickApp clicks at a point of the screen being tried. +func (s *noteStudio) clickApp(x, y float32) { + left := float32(s.a.sidebarSpan()) + if s.a.pathHidden { + left = 0 + } + s.click(f32.Pt(left+(1200-left-360)/2+x, (800-640)/2+y)) + s.frame() +} + +func (s *noteStudio) walked() string { + var out []string + for _, st := range s.a.trial.steps { + out = append(out, st.screen+"/"+st.did) + } + return strings.Join(out, " ") +} + +func TestTryingAJourney(t *testing.T) { + s := newTrial(t) + if got := s.walked(); got != "Login/" { + t.Fatalf("start: %q", got) + } + s.clickApp(20, 20) + s.clickApp(20, 120) // goto=back + if got, want := s.walked(), "Login/Create an account Register/Cancel Login/"; got != want { + t.Fatalf("there and back: %q, want %q", got, want) + } + s.act("try-back") + if got, want := s.walked(), "Login/Create an account Register/"; got != want { + t.Fatalf("a step back: %q, want %q", got, want) + } + if s.a.arrived() { + t.Error("arrived before the journey's end") + } + s.clickApp(20, 20) + if !s.a.arrived() || !strings.Contains(s.a.trialScreen(), "Got to Welcome in 3 steps") { + t.Errorf("end: %q", s.walked()) + } + if got := s.a.unopened(); !slices.Equal(got, []string{"A", "Locked"}) { + t.Errorf("screens no click opens = %v", got) + } + s.act("try-restart") + if got := s.walked(); got != "Login/" { + t.Errorf("restart: %q", got) + } + s.clickApp(20, 20) + s.a.escape() + if s.a.trial.on() || s.a.selName != "Register" { + t.Errorf("Esc: trying %v, selected %q; want the board, Register selected", s.a.trial.on(), s.a.selName) + } +} + +func TestTryingAJourneyViaAScreenDoesNotEndWithoutIt(t *testing.T) { + s := newJourneyStudio(t) + if err := s.a.db.Put("P", "", dsl.Decl{Kind: dsl.JourneyDecl, Name: "Create account", Text: `journey "Create account" from="Login" via="Locked" to="Welcome"`}); err != nil { + t.Fatal(err) + } + s.a.refresh() + s.act("try:Create account") + s.clickApp(20, 20) + s.clickApp(20, 20) + if s.a.trial.screen() != "Welcome" || s.a.arrived() { + t.Errorf("on %q, arrived %v; want Welcome, not arrived", s.a.trial.screen(), s.a.arrived()) + } +} + +func TestTryingTellsTheClicksThatDidNothing(t *testing.T) { + s := newTrial(t) + s.clickApp(20, 130) + s.clickApp(20, 130) + s.clickApp(20, 250) // the toggle answers + s.clickApp(20, 500) // nothing there + if want := []idleClick{{"Forgot it", "Login"}}; !slices.Equal(s.a.trial.idle, want) { + t.Errorf("idle = %v, want %v", s.a.trial.idle, want) + } + s.clickApp(20, 20) + if len(s.a.trial.idle) != 1 { + t.Errorf("a goto counted as idle: %v", s.a.trial.idle) + } +} + +func TestTryingTakesOneStepForNestedGotos(t *testing.T) { + s := newJourneyStudio(t) + if err := s.a.db.Put("P", "", dsl.Decl{Kind: dsl.ScreenDecl, Name: "Login", Text: `screen "Login" width=360 height=640 { Box goto="Locked" { Text text="In" goto="Register" } }`}); err != nil { + t.Fatal(err) + } + s.act("try:Create account") + s.clickApp(20, 20) + if got, want := s.walked(), "Login/In Register/"; got != want { + t.Errorf("walked %q, want %q", got, want) + } +} + +func TestTryingKeepsWhatWasDoneOnAScreen(t *testing.T) { + s := newTrial(t) + on := func() bool { + for _, e := range s.a.trial.sess.state["Login"] { + if b, ok := e.v.(*widget.Bool); ok { + return b.Value + } + } + return false + } + s.clickApp(20, 250) + s.clickApp(20, 20) + s.clickApp(20, 120) + if !on() { + t.Error("the toggle was lost on the way back") + } + s.act("try-restart") + s.frame() + if on() { + t.Error("the toggle survived the restart") + } +} + +func TestTryingEndsWithItsScreens(t *testing.T) { + s := newTrial(t) + decls := journeyDecls() + if err := s.a.db.Put("P", "", dsl.Decl{Kind: dsl.ScreenDecl, Name: "Login", Text: strings.Replace(decls[0].Text, "Forgot it", "Lost it", 1)}); err != nil { + t.Fatal(err) + } + s.a.refresh() + if !s.a.trial.on() { + t.Fatal("an edit ended the trial") + } + if err := s.a.db.Replace("P", decls[2:4], nil); err != nil { + t.Fatal(err) + } + s.a.refresh() + s.frame() + if s.a.trial.on() { + t.Error("still trying a screen that is gone") + } +} + +func TestJourneyValidation(t *testing.T) { + _, probs, err := NewRegistry().LoadSource(`screen "A" { Spacer goto=back } +journey "J" from="Gone" to="Nowhere"`, "") + if err != nil { + t.Fatal(err) + } + if len(probs) != 2 || !strings.Contains(probs[0].Msg, `from must name a screen of this project, got "Gone"`) || !strings.Contains(probs[1].Msg, `to must name`) { + t.Errorf("problems = %v", probs) + } +}