diff --git a/CHANGELOG.md b/CHANGELOG.md index b95da4bbd..6523e146f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Stop resolving and emitting the whole tree when the platform reports only a new window frame, maximized state, lifecycle or title bar, as on every step of a window drag; what reads them through `Env` still updates (#178 by @houko). - Convert macOS `nsgotest` captures and screenshots to sRGB, so their pixels no longer depend on whether the Mac's display is Display P3 (#311 by @houko). - Stop a `tsx.View` that renders an `Export` from also running what the package's entry module mounts, with its effects, handlers, timers and animation frames (#923 by @houko). +- Search a `ui/chat` transcript from Mod+F in a find bar that unfolds folded turns and reasoning, marks the matches in `ui.TextView` and reasoning, reveals each match clear of the bar and the composer and gives the focus back as it closes, with `core.FocusedRef` to read the focused view (#47 by @houko). - Add `TabStyle` and `IndicatorStyle` to `ui.Tabs` to restyle its tabs, the selected tab and the indicator (#958 by @houko). - Reload a TSX `` in place with the new script when `injectedJavaScriptBeforeContentLoaded` changes, as `core.WebView.InjectedJavaScriptBeforeContentFunc` does, rather than replacing the web view (#895 by @houko). - Keep partial borders above Apple backdrop, material and glass layers while leaving app children above the border (#935 by @houko). diff --git a/core/element.go b/core/element.go index 3eb6fed11..8fbd5285b 100644 --- a/core/element.go +++ b/core/element.go @@ -656,6 +656,18 @@ func (r *Ref) HoldsFocus() bool { return false } +// FocusedRef returns a reference to the element with the keyboard focus in cx's tree, as the platform last reported it, or nil when none has it; it is not tracked. The reference works while that element stays mounted, so what takes the focus without a trigger, such as a find bar a key opens, can give it back as it closes. +func FocusedRef(cx *Scope) *Ref { + if cx == nil { + return nil + } + t := cx.tree() + if t == nil || t.focus == nil { + return nil + } + return &Ref{t: t, n: t.focus} +} + // Before reports whether r's view comes before other's in tree order, // the order Tab goes through them; views not mounted come last. func (r *Ref) Before(other *Ref) bool { diff --git a/docs/architecture/text-search.md b/docs/architecture/text-search.md index 7fb0639ca..79e8eb262 100644 --- a/docs/architecture/text-search.md +++ b/docs/architecture/text-search.md @@ -1,6 +1,6 @@ # Text-level search -This is the shared design for issue [#47](https://github.com/nsgo-dev/nsgo/issues/47). `base/textview` and core's box reveal implement it; its [chat integration](#chat-integration) is still a goal. Chat transcript search will consume this capability; the matching rules and highlights belong to `base/textview`, so another document viewer can use them without importing `ui/chat`. Where it follows one of its [decisions](#decisions), confirmed by the user on 2026-11-15, the decision's number marks it. +This is the shared design for issue [#47](https://github.com/nsgo-dev/nsgo/issues/47). `base/textview`, core's box reveal and `ui/chat` implement it. The matching rules and highlights belong to `base/textview`, so another document viewer can use them without importing `ui/chat`. Where it follows one of its [decisions](#decisions), confirmed by the user on 2026-11-15, the decision's number marks it. ## What a view searches @@ -66,9 +66,9 @@ A `TextView` joins the search in its `Search` field, else the one `ProvideSearch ## Chat integration -`ui/chat` then supplies a find bar with a field, count, previous/next and close actions. `Conversation` and `FloatingConversation` provide one search state to the text views for their turns, open it from Mod+F (Ctrl+F elsewhere) and focus the field; Escape in the bar closes it. Closing gives the focus back to where it was when the bar opened, unless it already left the bar, as a popover gives it back to its trigger ([components](components.md)); core cannot read the focused view today, so the implementation adds a way to record it. Each sets the reveal margin to the find bar's height, and `FloatingConversation` adds its composer's and `TopInset`, so a match lands clear of them. Revealing a match stops a following transcript from following (`ConversationState`'s `pause`), so a streaming reply does not pull it back to the end. The bar's words, through `ui/chat/locales` in ICU MessageFormat ([languages](languages.md)), are “Find”, “Previous”, “Next”, “Close”, “No results” and “{selected, number} of {count, number}”. It does not implement matching, span splitting or cross-view counting. +`ui/chat` supplies a find bar with a field, count, previous/next and close actions. `Conversation` and `FloatingConversation` provide one search state to the text views for their turns, open it from Mod+F (Ctrl+F elsewhere) and focus the field; Escape closes it. Closing gives the focus back to where it was when the bar opened, unless it already left the bar, as a popover gives it back to its trigger ([components](components.md)); `core.FocusedRef` records that element for the overlay. Each sets the reveal margin to the find bar's height, and `FloatingConversation` adds its `TopInset` and its composer's height at the bottom, so a match lands clear of both. Revealing a match stops a following transcript from following (`ConversationState`'s `pause`), so a streaming reply does not pull it back to the end. The bar's words, through `ui/chat/locales` in ICU MessageFormat ([languages](languages.md)), are “Find”, “Previous”, “Next”, “Close”, “No results” and “{selected, number} of {count, number}”. It does not implement matching, span splitting or cross-view counting. -A completed turn folds its steps and a completed reasoning block its detail, building nothing hidden, so their text views do not exist to register. While the search is open with a query, a turn and a reasoning block that share the transcript's `ConversationState` unfold without recording a choice of the user's, and fold again by their own rules when it closes (decision 5); the transcript does not virtualize, so this mounts no more than a transcript the user unfolded. A reasoning block's default body is a plain `core.Text`, so it becomes a one-paragraph `TextView` to be searched. Only text views register: what a step or a prompt shows with other components is not searched. +A completed turn folds its steps and a completed reasoning block its detail, building nothing hidden, so their text views do not exist to register. While the search is open with a query, a turn and a reasoning block that share the transcript's `ConversationState` unfold without recording a choice of the user's, and fold again by their own rules when it closes (decision 5); the transcript does not virtualize, so this mounts no more than a transcript the user unfolded. A reasoning block's default body is a one-paragraph `TextView` of its text, which it does not read as Markdown, so it is searched. Only text views register: what a step or a prompt shows with other components is not searched. ## Verification diff --git a/docs/public/en/accessibility.md b/docs/public/en/accessibility.md index b64792e59..3f2de5281 100644 --- a/docs/public/en/accessibility.md +++ b/docs/public/en/accessibility.md @@ -88,7 +88,7 @@ Tooltips describe their trigger before it receives focus. `View.Tooltip`, `base. A `base.DataTable` exposes its named grid as the keyboard and accessibility focus stop; the pointer hit layer is hidden from assistive technology. -On desktops, the web and an Apple TV, views that take presses are Tab stops beside text fields; `NoFocus` keeps one out and `Focusable` makes a view without presses a stop. `Style.FocusVisible` draws the focus ring only when the keyboard moved the focus (`focus-visible:`), `Style.Focus` any focus and `Style.FocusWithin` the focus inside a view, `OnFocus` and `OnBlur` hear it, `OnBlur` also as the focused view leaves the tree, and `Ref.Focus()` and `Ref.SetAccessibilityFocus()` move it. Return and Space press the focused view, and arrow keys move through tab lists, radio groups and menus. A view's `Tooltip` shows at once when the keyboard moves the focus to it, until the focus leaves or Escape is pressed. A popup's `OnOpen` runs once its content is there, so a `Focus` there moves the focus in, as a non-modal dialog's should; a popover's content follows its trigger in the Tab order, and the focus goes back to the trigger as the popup closes. +On desktops, the web and an Apple TV, views that take presses are Tab stops beside text fields; `NoFocus` keeps one out and `Focusable` makes a view without presses a stop. `Style.FocusVisible` draws the focus ring only when the keyboard moved the focus (`focus-visible:`), `Style.Focus` any focus and `Style.FocusWithin` the focus inside a view, `OnFocus` and `OnBlur` hear it, `OnBlur` also as the focused view leaves the tree, and `Ref.Focus()` and `Ref.SetAccessibilityFocus()` move it; `core.FocusedRef(cx)` is a ref to the view that has it, for what opens without a trigger, such as a find bar from a key, to give it back as it closes. Return and Space press the focused view, and arrow keys move through tab lists, radio groups and menus. A view's `Tooltip` shows at once when the keyboard moves the focus to it, until the focus leaves or Escape is pressed. A popup's `OnOpen` runs once its content is there, so a `Focus` there moves the focus in, as a non-modal dialog's should; a popover's content follows its trigger in the Tab order, and the focus goes back to the trigger as the popup closes. `cx.Env().ScreenReader()` says whether one runs, `cx.Env().ReduceMotion()` whether the user asked for less motion, `cx.Env().IncreaseContrast()` whether the user asked for more contrast (Increase Contrast on macOS, iOS and watchOS, a Windows contrast theme, GNOME's High Contrast, GTK 4.20's contrast setting or a high-contrast GTK theme, Android 14's contrast setting above standard, `prefers-contrast: more` or `forced-colors: active` on the web), `cx.Env().FontScale()` the text size, and `cx.Env().RTL()` the layout direction. Texts follow the text size unless `NoFontScaling` is set, and a layout that is right to left mirrors its physical edges when it uses the logical ones. diff --git a/docs/public/en/ui/text.md b/docs/public/en/ui/text.md index 2673ea82b..76f4e343b 100644 --- a/docs/public/en/ui/text.md +++ b/docs/public/en/ui/text.md @@ -54,6 +54,8 @@ textview.TextView{Markdown: "## Notes\n\nA **native** document.", Styles: ui.Tex OnLinkPress: func(e textview.LinkPressEvent) { open(e.URL) }} ``` +`textview.NewSearch` searches the text a `TextView` shows and highlights its matches. Give several views the same search with `textview.ProvideSearch`, then call `Open`, `SetQuery`, `Next` and `Previous`; `Count` and `Selected` report the result. Search parts are styled with `textview.PartSearch` and `textview.PartSearchSelected`. + ## Selection and accessibility `SelectableOn` lets the user select and copy a text. A `core.View` with `Selectable` makes its texts select together in document order. A `Role` such as `RoleHeader` tells assistive technology what the text is, and `Label` replaces it when the words are not the label. diff --git a/docs/public/zh/accessibility.md b/docs/public/zh/accessibility.md index d6d8556e5..848984f59 100644 --- a/docs/public/zh/accessibility.md +++ b/docs/public/zh/accessibility.md @@ -88,7 +88,7 @@ core.Text{ContentFunc: func() string { return fmt.Sprintf("购物车里有 %d `base.DataTable` 将带标签的网格作为键盘和辅助功能的焦点停靠点;指针命中层对辅助技术隐藏。 -在桌面、Web 和 Apple TV 上,可按压的视图和文本框一起成为 Tab 停靠点;`NoFocus` 让一个视图退出,`Focusable` 让没有按压的视图成为停靠点。`Style.FocusVisible` 只在键盘移动焦点时绘制焦点环(`focus-visible:`),`Style.Focus` 对应任何焦点,`Style.FocusWithin` 对应视图内的焦点,`OnFocus` 和 `OnBlur` 听到焦点变化(获得焦点的视图离开树时也会收到 `OnBlur`),`Ref.Focus()` 和 `Ref.SetAccessibilityFocus()` 移动焦点。Return 和空格按下获得焦点的视图,方向键在标签列表、单选组和菜单中移动。键盘把焦点移到视图上时,它的 `Tooltip` 立即显示,直到焦点离开或按下 Escape。弹出层的 `OnOpen` 在内容就绪后运行,在其中调用 `Focus` 就能把焦点移进去,非模态对话框应当这样做;popover 的内容在 Tab 顺序中紧跟触发器,弹出层关闭时焦点回到触发器。 +在桌面、Web 和 Apple TV 上,可按压的视图和文本框一起成为 Tab 停靠点;`NoFocus` 让一个视图退出,`Focusable` 让没有按压的视图成为停靠点。`Style.FocusVisible` 只在键盘移动焦点时绘制焦点环(`focus-visible:`),`Style.Focus` 对应任何焦点,`Style.FocusWithin` 对应视图内的焦点,`OnFocus` 和 `OnBlur` 听到焦点变化(获得焦点的视图离开树时也会收到 `OnBlur`),`Ref.Focus()` 和 `Ref.SetAccessibilityFocus()` 移动焦点;`core.FocusedRef(cx)` 返回指向当前焦点视图的 ref,供没有触发器、由按键打开的界面(例如查找栏)在关闭时把焦点交还。Return 和空格按下获得焦点的视图,方向键在标签列表、单选组和菜单中移动。键盘把焦点移到视图上时,它的 `Tooltip` 立即显示,直到焦点离开或按下 Escape。弹出层的 `OnOpen` 在内容就绪后运行,在其中调用 `Focus` 就能把焦点移进去,非模态对话框应当这样做;popover 的内容在 Tab 顺序中紧跟触发器,弹出层关闭时焦点回到触发器。 `cx.Env().ScreenReader()` 说明是否有屏幕阅读器运行,`cx.Env().ReduceMotion()` 说明用户是否要求减少动态效果,`cx.Env().IncreaseContrast()` 说明用户是否要求增强对比度(macOS、iOS 和 watchOS 的“增强对比度”、Windows 的对比度主题、GNOME 的高对比度、GTK 4.20 的对比度设置或高对比度 GTK 主题、Android 14 高于标准的对比度设置,Web 上的 `prefers-contrast: more` 或 `forced-colors: active`),`cx.Env().FontScale()` 是文本大小,`cx.Env().RTL()` 是布局方向。除非设置 `NoFontScaling`,文本会跟随文本大小;从右到左的布局使用逻辑边时会镜像物理边。 diff --git a/docs/public/zh/ui/text.md b/docs/public/zh/ui/text.md index ea302e0ee..f61039e77 100644 --- a/docs/public/zh/ui/text.md +++ b/docs/public/zh/ui/text.md @@ -54,6 +54,8 @@ textview.TextView{Markdown: "## 笔记\n\n一份 **原生** 文档。", Styles: OnLinkPress: func(e textview.LinkPressEvent) { open(e.URL) }} ``` +`textview.NewSearch` 搜索 `TextView` 显示的文字并高亮匹配项。将同一个 search 通过 `textview.ProvideSearch` 提供给多个视图,然后调用 `Open`、`SetQuery`、`Next` 和 `Previous`;`Count` 和 `Selected` 返回结果。用 `textview.PartSearch` 和 `textview.PartSearchSelected` 设置搜索部分的样式。 + ## 选择与无障碍 `SelectableOn` 让用户选择和复制文本。带 `Selectable` 的 `core.View` 让其中的文本按文档顺序一起选择。`RoleHeader` 之类的 `Role` 告诉辅助技术这段文字是什么,`Label` 在原文不适合朗读时替换它。 diff --git a/docs/roadmap.md b/docs/roadmap.md index b5f28b3dc..f018f1956 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -220,14 +220,6 @@ What `base/terminal` still lacks of a terminal app's features, Ghostty's the ref | Drawn box characters, blinking and contrast | `cursor-style-blink`, `minimum-contrast`, `window-padding-color` | Box drawing, blocks and Powerline's separators are drawn so lines join, the cursor blinks, and minimum contrast and padding colors apply | | Search, images and shell integration | Find, the Kitty graphics protocol, `shell-integration` | A search highlights matches, programs show images, and OSC 133 prompts take Option+click to move the cursor | -## Text views - -What `base/textview` and `ui/chat` still lack, from NSGo's own issues ([text view](architecture/textview.md)). - -| Item | Reference | Done when | -| --- | --- | --- | -| Transcript search | NSGo's [#47](https://github.com/nsgo-dev/nsgo/issues/47), [text-level search](architecture/text-search.md#chat-integration) | `ui/chat` adds a transcript find bar on `textview.Search`, opened with Mod+F, unfolding folded turns and reasoning while it is open and giving the focus back as it closes | - ## Widgets What package `widget` lacks of WidgetKit and ActivityKit, and of widgets and Live Activities elsewhere ([tool](architecture/tool.md#widgets)). diff --git a/ui/chat/chat.go b/ui/chat/chat.go index 1d49da93a..e6d7cab27 100644 --- a/ui/chat/chat.go +++ b/ui/chat/chat.go @@ -101,6 +101,10 @@ func (t Turn) Render(cx *core.Scope) core.Node { choice := core.NewSignal(cx, uint8(0)) folded := false open := core.NewMemo(cx, func() bool { + // A search unfolds the turn without a choice of the user's, which its rules take up again once it closes. + if t.Conversation != nil && t.Conversation.searching() { + return true + } held := hold() if c := choice.Get(); c != 0 { return c == 1 diff --git a/ui/chat/chat_test.go b/ui/chat/chat_test.go index 71d4c89ce..e48dec0d1 100644 --- a/ui/chat/chat_test.go +++ b/ui/chat/chat_test.go @@ -7,6 +7,7 @@ import ( "time" "github.com/nsgo-dev/nsgo/base" + "github.com/nsgo-dev/nsgo/base/textview" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/icons/lucide" "github.com/nsgo-dev/nsgo/internal/driver" @@ -77,6 +78,90 @@ func startChat(t *testing.T, e core.Environment) (*nsgotest.App, *chatStage) { return app, s } +// TestConversationSearch searches folded steps and reasoning across turns from Mod+F, reveals each selected match clear of the find bar and the floating composer, and closes with Escape, the focus back in the composer and the turns folded again. +func TestConversationSearch(t *testing.T) { + var state *ConversationState + app := start(t, desktopEnv, func(cx *core.Scope) core.Node { + state = NewConversationState(cx) + draft := core.NewSignal(cx, "") + turn := func(n int) core.Node { + id := strconv.Itoa(n) + word := "hay" + if n%4 == 0 { + word = "needle" + } + return Turn{Status: func() Status { return Completed }, HasFinal: func() bool { return true }, Conversation: state, + Summary: func() string { return "Worked " + id }, Prompt: func(*core.Scope) core.Node { return core.Text{Content: "Prompt " + id} }, + Reasoning: func(*core.Scope) core.Node { + return Reasoning{Text: func() string { return "reason " + id + " " + word }, Status: func() Status { return Completed }, Conversation: state} + }, + Steps: func() []Step { + return []Step{{ID: "step", Message: func(*core.Scope) core.Node { + return textview.TextView{Markdown: "step " + id + " " + word} + }}} + }, + Final: func(*core.Scope) core.Node { + return core.View{Style: core.Style{Height: core.Pt(240)}, Children: []core.Node{core.Text{Content: "Answer " + id}}} + }} + } + var turns []core.Node + for n := range 12 { + turns = append(turns, turn(n+1)) + } + return core.View{Style: core.Style{Height: core.Pt(700)}, Children: []core.Node{FloatingConversation{State: state, JumpLabel: "Latest", TopInset: 20, Children: turns, + Composer: []core.Node{Composer{Draft: draft.Get, OnDraftChange: draft.Set, Label: "Message", SendLabel: "Send", StopLabel: "Stop", Glass: true, State: state}}}}} + }) + if app.Exists("text:reason 4 needle") { + t.Fatal("a completed turn's reasoning should start folded") + } + app.Focus("id:composer") + app.Key("mod+f") + if !app.Find("id:chat-find-input").Focused { + t.Fatal("Mod+F did not focus the find field") + } + if app.Exists("text:reason 4 needle") { + t.Fatal("the find bar unfolded the transcript before a query") + } + app.Type("id:chat-find-input", "needle") + if !app.Exists("text:1 of 6") { + t.Fatalf("the count is not 1 of 6\n%s", app.Dump()) + } + if !app.Exists("text:reason 4 needle") || !app.Exists("text:step 12 needle") { + t.Fatal("the search did not unfold the transcript's reasoning and steps") + } + clear := func(n int) { + t.Helper() + match, ok := state.Search().SelectedBounds() + bar, composer := app.Find("id:chat-find-input").Parent.Bounds(), app.Find("id:chat-composer").Bounds() + if !ok || match.Origin.Y < bar.Origin.Y+bar.Size.Height || match.Origin.Y+match.Size.Height > composer.Origin.Y { + t.Fatalf("match %d at %v is not clear of the bar %v and the composer %v", n, match, bar, composer) + } + } + clear(1) + for n := 2; n <= 6; n++ { + app.Press("id:chat-find-next") + if !app.Exists("text:" + strconv.Itoa(n) + " of 6") { + t.Fatalf("after next the count is not %d of 6", n) + } + clear(n) + } + app.Press("id:chat-find-previous") + if !app.Exists("text:5 of 6") { + t.Fatal("previous did not go back to 5 of 6") + } + app.Focus("id:chat-find-input") + app.Key("escape") + if app.Exists("id:chat-find-input") { + t.Fatal("Escape left the find bar open") + } + if !app.Find("id:composer").Focused { + t.Fatal("closing the find bar did not give the focus back to the composer") + } + if app.Exists("text:reason 4 needle") { + t.Fatal("the reasoning stayed unfolded after the search closed") + } +} + // TestTurnFolds checks a live group, then the fold a completed turn // takes with its final response, and that a choice outlives updates. func TestTurnFolds(t *testing.T) { diff --git a/ui/chat/conversation.go b/ui/chat/conversation.go index a9a88e3fb..faeac95c0 100644 --- a/ui/chat/conversation.go +++ b/ui/chat/conversation.go @@ -2,6 +2,7 @@ package chat import ( "github.com/nsgo-dev/nsgo/base" + "github.com/nsgo-dev/nsgo/base/textview" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/icons/lucide" "github.com/nsgo-dev/nsgo/ui" @@ -26,13 +27,16 @@ type ConversationState struct { following *core.Signal[bool] composer, card, footer *core.Signal[core.Points] composers *core.Signal[int] - lastY core.Points + search *textview.Search + // bar is the find bar's box; focusBack is where the focus was as it opened. + bar, focusBack *core.Ref + lastY core.Points } // NewConversationState makes a state at the latest turn. func NewConversationState(cx *core.Scope) *ConversationState { return &ConversationState{scroll: &core.Ref{}, following: core.NewSignal(cx, true), composer: core.NewSignal(cx, core.Points(140)), - card: core.NewSignal(cx, chatRestingCard), footer: core.NewSignal(cx, core.Points(0)), composers: core.NewSignal(cx, 0)} + card: core.NewSignal(cx, chatRestingCard), footer: core.NewSignal(cx, core.Points(0)), composers: core.NewSignal(cx, 0), search: textview.NewSearch(cx), bar: &core.Ref{}} } // AtLatest reports whether the transcript follows its end. @@ -51,6 +55,33 @@ func (s *ConversationState) Scroll() *core.Ref { return s.scroll } // for what the app overlays on an empty conversation. func (s *ConversationState) ComposerHeight() core.Points { return s.composer.Get() } +// Search returns the transcript's search, which Conversation and FloatingConversation provide to every TextView in their children and open with Mod+F in a find bar. +func (s *ConversationState) Search() *textview.Search { return s.search } + +// SearchOpen reports whether the transcript's find bar is open. +func (s *ConversationState) SearchOpen() bool { return s.search.IsOpen() } + +// searching reports whether the find bar is open with a query, which unfolds the turns and reasoning sharing the state so that their text is searched. +func (s *ConversationState) searching() bool { return s.search.IsOpen() && s.search.Query() != "" } + +// openSearch opens the find bar, noting where the focus is to give it back as the bar closes. +func (s *ConversationState) openSearch(cx *core.Scope) { + if !s.search.IsOpen() { + s.focusBack = core.FocusedRef(cx) + s.search.Open() + } +} + +// closeSearch closes the find bar, giving the focus back to where it was as the bar opened unless it already left the bar. +func (s *ConversationState) closeSearch() { + back := s.focusBack + s.focusBack = nil + if back != nil && s.bar.HoldsFocus() { + back.Focus() + } + s.search.Close() +} + // pause stops following until the user returns to the end, so a disclosure // opening under the pointer keeps its header in place. func (s *ConversationState) pause() { @@ -95,6 +126,7 @@ type Conversation struct { // Render implements core.Node. func (v Conversation) Render(cx *core.Scope) core.Node { s := v.State + setupSearch(cx, s) return core.View{TestID: v.TestID, Style: ui.FillRest, Children: []core.Node{ core.Scroll{Ref: s.scroll, OnScroll: s.scrolled, Style: ui.FillRest, Children: []core.Node{ chatTranscript(s, v.ContentWidth, core.Edges{Top: 22, Right: 20, Bottom: 22, Left: 20}, v.Children, nil), @@ -102,6 +134,7 @@ func (v Conversation) Render(cx *core.Scope) core.Node { core.Show{When: func() bool { return !s.AtLatest() }, Then: func(cx *core.Scope) core.Node { return chatJumpButton(cx, s, v.JumpLabel, func() core.Points { return ui.ButtonHeight/2 - 6 }, false) }}, + findBar(s, 0, nil), }} } @@ -191,6 +224,7 @@ type FloatingConversation struct { // Render implements core.Node. func (v FloatingConversation) Render(cx *core.Scope) core.Node { s := v.State + setupSearch(cx, s) inset := max(0, v.TopInset) transparent := core.Style{Background: core.Transparent} // Only the scroll view clips: the composer's glass and shadow reach past @@ -218,6 +252,7 @@ func (v FloatingConversation) Render(cx *core.Scope) core.Node { core.Show{When: func() bool { return !s.AtLatest() }, Then: func(cx *core.Scope) core.Node { return chatJumpButton(cx, s, v.JumpLabel, func() core.Points { return s.composer.Get() + 12 }, true) }}, + findBar(s, inset, s.composer.Get), core.View{PointerEvents: core.PointerEventsBoxNone, OnLayout: func(b core.Bounds) { s.composer.Set(b.Size.Height) }, TestID: "chat-composer", Style: core.Style{Position: core.Absolute, Left: core.Pt(0), Right: core.Pt(0), Bottom: core.Pt(0), AlignItems: core.AlignCenter}, StyleFunc: func() core.Style { @@ -227,6 +262,20 @@ func (v FloatingConversation) Render(cx *core.Scope) core.Node { }} } +// setupSearch provides the transcript's search to its text views, opens it with Mod+F and stops following the end as a match is revealed, so a streaming reply does not pull the transcript away from it. +func setupSearch(cx *core.Scope, s *ConversationState) { + textview.ProvideSearch(cx, s.search) + cx.OnKeyWith("mod+f", core.KeyOptions{When: core.KeyAlways}, func() { s.openSearch(cx) }) + last := 0 + cx.Effect(func() { + selected := s.search.Selected() + if selected != 0 && selected != last { + s.pause() + } + last = selected + }) +} + // FloatingMargin keeps a floating composer off the bottom edge: its footer, // footer points tall, may stand in the safe area, which holds nothing but // the home indicator, while the software keyboard hides it. diff --git a/ui/chat/find.go b/ui/chat/find.go new file mode 100644 index 000000000..090b63350 --- /dev/null +++ b/ui/chat/find.go @@ -0,0 +1,44 @@ +package chat + +import ( + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/icons/lucide" + "github.com/nsgo-dev/nsgo/ui" + "github.com/nsgo-dev/nsgo/ui/chat/locales" +) + +// findBar is a transcript's find bar, shown while its search is open: a field, the count, previous, next and close. inset is the room above it; bottom, when set, is the height of what covers the transcript's end, a floating composer, which a revealed match keeps clear of as it does of the bar. +func findBar(s *ConversationState, inset core.Points, bottom func() core.Points) core.Node { + return core.Show{When: s.search.IsOpen, Then: func(cx *core.Scope) core.Node { + search := s.search + colors := tonesOf(cx) + height := core.NewSignal(cx, core.Points(0)) + cx.Effect(func() { + margin := core.Edges{Top: height.Get() + inset + 16} + if bottom != nil { + margin.Bottom = bottom() + 16 + } + search.SetRevealMargin(margin) + }) + // Always, or the field, which has the focus, would keep Escape. + cx.OnKeyWith("escape", core.KeyOptions{When: core.KeyAlways}, s.closeSearch) + count := func() string { + n := search.Count() + if n == 0 { + return locales.NoResults(cx) + } + return locales.Matches(cx, search.Selected(), n) + } + return core.View{TestID: "chat-find", PointerEvents: core.PointerEventsBoxNone, Style: core.Style{Position: core.Absolute, Top: core.Pt(inset + 8), Left: core.Pt(8), Right: core.Pt(8), AlignItems: core.AlignCenter}, Children: []core.Node{ + core.View{Ref: s.bar, PointerEvents: core.PointerEventsAuto, Style: core.Style{Direction: core.Row, MinWidth: core.Pt(0), MaxWidth: core.Pt(520), Padding: core.Symmetric(4, 6), Gap: 4, AlignItems: core.AlignCenter, CornerRadius: 9}, StyleFunc: func() core.Style { + return core.Style{Background: colors.Surface(), BorderWidth: 1, BorderColor: colors.Border(), Shadows: []core.BoxShadow{ui.Shadow(0, 3, 12, 0, ui.Black(0.16))}} + }, OnLayout: func(frame core.Bounds) { height.Set(frame.Size.Height) }, Children: []core.Node{ + ui.Input{Value: search.Query, OnChange: search.SetQuery, Label: locales.Find(cx), Placeholder: locales.Find(cx), AutoFocus: true, TestID: "chat-find-input", Style: core.Style{FlexGrow: 1, MinWidth: core.Pt(80), Height: core.Pt(28)}}, + core.Text{ContentFunc: count, Style: core.Style{MinWidth: core.Pt(78), TextAlign: core.TextAlignCenter, FontSize: 12}, StyleFunc: ui.Colored(colors.Muted)}, + ui.IconButton{Icon: lucide.ChevronUp, LabelFunc: func() string { return locales.Previous(cx) }, OnPress: search.Previous, TestID: "chat-find-previous"}, + ui.IconButton{Icon: lucide.ChevronDown, LabelFunc: func() string { return locales.Next(cx) }, OnPress: search.Next, TestID: "chat-find-next"}, + ui.IconButton{Icon: lucide.X, LabelFunc: func() string { return locales.Close(cx) }, OnPress: s.closeSearch, TestID: "chat-find-close"}, + }}, + }} + }} +} diff --git a/ui/chat/locales/catalog_gen.go b/ui/chat/locales/catalog_gen.go index c26cc7a17..2bc6f606c 100644 --- a/ui/chat/locales/catalog_gen.go +++ b/ui/chat/locales/catalog_gen.go @@ -40,6 +40,7 @@ func For(cx *core.Scope) Messages { var Parameters = map[string][]string{ "Thinking": {"seconds"}, "ThoughtFor": {"seconds"}, + "Matches": {"selected", "count"}, } // Translation is a language's messages another package supplies: @@ -50,6 +51,7 @@ type Translation struct { Texts map[string]string Thinking func(seconds int) string ThoughtFor func(seconds int) string + Matches func(selected int, count int) string } var supplied = map[string]Translation{} @@ -62,6 +64,11 @@ const ( textEdit textThinkingUntimed textThoughts + textFind + textPrevious + textNext + textClose + textNoResults numTexts ) @@ -74,6 +81,11 @@ var keyOfText = [numTexts]string{ "edit", "thinkingUntimed", "thoughts", + "find", + "previous", + "next", + "close", + "noResults", } // textsEn are the messages without arguments in en. @@ -83,7 +95,12 @@ var textsEn = i18n.NewTexts(""+ "Retry"+ "Edit"+ "Thinking…"+ - "Thoughts", + "Thoughts"+ + "Find"+ + "Previous"+ + "Next"+ + "Close"+ + "No results", []uint16{ 4, 6, @@ -91,6 +108,11 @@ var textsEn = i18n.NewTexts(""+ 4, 11, 8, + 4, + 8, + 4, + 5, + 10, }) // textsZhHans are the messages without arguments in zh-Hans. @@ -100,7 +122,12 @@ var textsZhHans = i18n.NewTexts(""+ "重试"+ "编辑"+ "思考中…"+ - "思考过程", + "思考过程"+ + "查找"+ + "上一个"+ + "下一个"+ + "关闭"+ + "无结果", []uint16{ 6, 9, @@ -108,6 +135,11 @@ var textsZhHans = i18n.NewTexts(""+ 6, 12, 12, + 6, + 9, + 9, + 6, + 9, }) // texts returns the messages without arguments in lang, nil for a @@ -170,6 +202,9 @@ func Supply(lang string, t Translation) { if t.ThoughtFor != nil { s.ThoughtFor = t.ThoughtFor } + if t.Matches != nil { + s.Matches = t.Matches + } supplied[lang] = s Catalog.Add(lang) } @@ -284,3 +319,72 @@ func Thoughts(cx *core.Scope) string { return For(cx).Thoughts() } // Thoughts is the package's Thoughts in the language of msgs. func (msgs Messages) Thoughts() string { return msgs.text(textThoughts) } + +// Find says "Find" +// in the language the app shows under cx. +// +// The label and placeholder of the conversation find field. +func Find(cx *core.Scope) string { return For(cx).Find() } + +// Find is the package's Find in the language of msgs. +func (msgs Messages) Find() string { return msgs.text(textFind) } + +// Previous says "Previous" +// in the language the app shows under cx. +// +// The accessible label of the previous-match button. +func Previous(cx *core.Scope) string { return For(cx).Previous() } + +// Previous is the package's Previous in the language of msgs. +func (msgs Messages) Previous() string { return msgs.text(textPrevious) } + +// Next says "Next" +// in the language the app shows under cx. +// +// The accessible label of the next-match button. +func Next(cx *core.Scope) string { return For(cx).Next() } + +// Next is the package's Next in the language of msgs. +func (msgs Messages) Next() string { return msgs.text(textNext) } + +// Close says "Close" +// in the language the app shows under cx. +// +// The accessible label of the button closing the conversation find bar. +func Close(cx *core.Scope) string { return For(cx).Close() } + +// Close is the package's Close in the language of msgs. +func (msgs Messages) Close() string { return msgs.text(textClose) } + +// NoResults says "No results" +// in the language the app shows under cx. +// +// What the conversation find bar says when the query has no matches. +func NoResults(cx *core.Scope) string { return For(cx).NoResults() } + +// NoResults is the package's NoResults in the language of msgs. +func (msgs Messages) NoResults() string { return msgs.text(textNoResults) } + +// Matches says "{selected, number} of {count, number}" +// in the language the app shows under cx. +// +// The selected match and total count in the conversation find bar. +func Matches(cx *core.Scope, selected int, count int) string { return For(cx).Matches(selected, count) } + +// Matches is the package's Matches in the language of msgs. +func (msgs Messages) Matches(selected int, count int) string { + if i18n.IsPseudo(msgs.lang) { + return i18n.Pseudo(msgs.lang, Messages{lang: Source, mark: true}.Matches(selected, count)) + } + for lang := msgs.lang; ; lang = i18n.Parent(lang) { + if f := supplied[lang].Matches; f != nil { + return f(selected, count) + } + switch lang { + case "", "en": + return msgs.arg(i18n.FormatNumber("en", float64(selected))) + " of " + msgs.arg(i18n.FormatNumber("en", float64(count))) + case "zh-Hans": + return i18n.FormatNumber("zh-Hans", float64(selected)) + " / " + i18n.FormatNumber("zh-Hans", float64(count)) + } + } +} diff --git a/ui/chat/locales/en.yaml b/ui/chat/locales/en.yaml index 52175a548..9f2ad9b7c 100644 --- a/ui/chat/locales/en.yaml +++ b/ui/chat/locales/en.yaml @@ -22,3 +22,21 @@ thinkingUntimed: thoughts: message: "Thoughts" description: What a reasoning block reads once it ends, when the app does not say what it cost. +find: + message: "Find" + description: The label and placeholder of the conversation find field. +previous: + message: "Previous" + description: The accessible label of the previous-match button. +next: + message: "Next" + description: The accessible label of the next-match button. +close: + message: "Close" + description: The accessible label of the button closing the conversation find bar. +noResults: + message: "No results" + description: What the conversation find bar says when the query has no matches. +matches: + message: "{selected, number} of {count, number}" + description: The selected match and total count in the conversation find bar. diff --git a/ui/chat/locales/zh-Hans.yaml b/ui/chat/locales/zh-Hans.yaml index 01dfa1411..a59621339 100644 --- a/ui/chat/locales/zh-Hans.yaml +++ b/ui/chat/locales/zh-Hans.yaml @@ -6,3 +6,9 @@ thinking: "思考中… {seconds, number} 秒" thoughtFor: "思考了 {seconds, number} 秒" thinkingUntimed: "思考中…" thoughts: "思考过程" +find: "查找" +previous: "上一个" +next: "下一个" +close: "关闭" +noResults: "无结果" +matches: "{selected, number} / {count, number}" diff --git a/ui/chat/reasoning.go b/ui/chat/reasoning.go index e4d3fca4c..f4d49167c 100644 --- a/ui/chat/reasoning.go +++ b/ui/chat/reasoning.go @@ -1,9 +1,11 @@ package chat import ( + "strings" "time" "github.com/nsgo-dev/nsgo/base" + "github.com/nsgo-dev/nsgo/base/textview" "github.com/nsgo-dev/nsgo/core" "github.com/nsgo-dev/nsgo/ui" "github.com/nsgo-dev/nsgo/ui/chat/locales" @@ -97,6 +99,10 @@ func (r Reasoning) Render(cx *core.Scope) core.Node { choice := core.NewSignal(cx, uint8(0)) folded := false open := core.NewMemo(cx, func() bool { + // A search unfolds the reasoning without a choice of the user's, which its rules take up again once it closes. + if r.Conversation != nil && r.Conversation.searching() { + return true + } held := is(r.HoldOpen) || r.Conversation != nil && !r.Conversation.AtLatest() if c := choice.Get(); c != 0 { return c == 1 @@ -120,8 +126,13 @@ func (r Reasoning) Render(cx *core.Scope) core.Node { } body := r.Content if body == nil { - body = func(*core.Scope) core.Node { - return core.Text{ContentFunc: r.Text, Selectable: core.SelectableOn, Style: core.Style{LineHeight: 20}} + body = func(cx *core.Scope) core.Node { + // A paragraph of the text as it is, not read as Markdown, in a text view so that a search finds it and marks its matches as ui's text views do. + styles := ui.Themed(cx, func() textview.Styles { + s := ui.TextViewStyles(cx) + return textview.Styles{textview.PartRoot: {LineHeight: 20}, textview.PartSearch: s[textview.PartSearch], textview.PartSearchSelected: s[textview.PartSearchSelected]} + }) + return textview.TextView{DocumentFunc: func() textview.Document { return plainDocument(r.Text()) }, Selectable: true, StyleOf: func(p textview.Part) core.Style { return styles()[p] }} } } row := core.View{Style: core.Style{Direction: core.Row, AlignItems: core.AlignCenter, Gap: 6, Height: core.Pt(24)}, Children: []core.Node{ @@ -151,3 +162,17 @@ func (r Reasoning) Render(cx *core.Scope) core.Node { Children: []core.Node{row, detail}} }} } + +// plainDocument is text as one paragraph, its line breaks kept. +func plainDocument(text string) textview.Document { + var content []textview.Inline + for i, line := range strings.Split(text, "\n") { + if i > 0 { + content = append(content, textview.Break{}) + } + if line != "" { + content = append(content, textview.Text{Text: line}) + } + } + return textview.Document{Blocks: []textview.Block{textview.Paragraph{Content: content}}} +} diff --git a/ui/textview.go b/ui/textview.go index 50cc44559..91076660a 100644 --- a/ui/textview.go +++ b/ui/textview.go @@ -93,11 +93,14 @@ func TextViewStyles(cx *core.Scope) textview.Styles { textview.PartStrikethrough: {TextDecoration: core.TextDecorationLineThrough}, textview.PartUnderline: {TextDecoration: core.TextDecorationUnderline}, textview.PartMark: {Background: c.Selection}, - textview.PartSuperscript: {FontSize: TypeCaption.FontSize}, - textview.PartSubscript: {FontSize: TypeCaption.FontSize}, - textview.PartSmall: {FontSize: TypeCaption.FontSize}, - textview.PartLink: {Color: c.Accent, TextDecoration: core.TextDecorationUnderline, TextDecorationColor: c.Accent.Faded(0.4)}, - textview.PartImage: {CornerRadius: RadiusControl}, + // A search's matches, the selected one stronger, as a browser's find marks them. + textview.PartSearch: {Background: c.Warn.Faded(0.3)}, + textview.PartSearchSelected: {Background: c.Warn.Faded(0.7)}, + textview.PartSuperscript: {FontSize: TypeCaption.FontSize}, + textview.PartSubscript: {FontSize: TypeCaption.FontSize}, + textview.PartSmall: {FontSize: TypeCaption.FontSize}, + textview.PartLink: {Color: c.Accent, TextDecoration: core.TextDecorationUnderline, TextDecorationColor: c.Accent.Faded(0.4)}, + textview.PartImage: {CornerRadius: RadiusControl}, textview.PartTable: {BorderWidth: 1, BorderColor: c.Border, CornerRadius: RadiusControl, Overflow: core.Hidden}, textview.PartTableRow: {Borders: core.Edges{Top: 1}, BorderColors: core.EdgeColors{Top: c.Line}},