//! Scrollable vertical window over a list of lines. Set `width`/`height`, //! load content with `setContent` (splits on `\n`, normalizes `\r\n`) or //! `setContentLinesBorrow`, then route updates through `update` for keyboard //! nav. //! //! Supports vertical scroll with ANSI-aware horizontal truncation, optional //! soft-wrap, and search highlights. Not ported from bubbles: horizontal //! scroll, a line-number gutter, the per-line style callback, mouse wheel, //! and the lipgloss `Style`/frame (so borders/padding can't be added). const std = @import("std"); const tea = @import("blacktea"); const matte = @import("matte"); const util = @import("util.zig"); const Allocator = std.mem.Allocator; const Writer = std.Io.Writer; const ArrayList = std.ArrayList; const Viewport = @This(); pub const KeyMap = struct { const key = @import("key.zig"); page_down: key.Binding = .{ .keys = &.{ .page_down, .f, .space }, .help = .{ .key = "f/pgdn", .desc = "page down" }, }, page_up: key.Binding = .{ .keys = &.{ .page_up, .b }, .help = .{ .key = "b/pgup", .desc = "page up" }, }, half_page_up: key.Binding = .{ .keys = &.{ .u, .ctrl(.u) }, .help = .{ .key = "u", .desc = "½ page up" }, }, half_page_down: key.Binding = .{ .keys = &.{ .d, .ctrl(.d) }, .help = .{ .key = "d", .desc = "½ page down" }, }, up: key.Binding = .up, down: key.Binding = .down, left: key.Binding = .left, right: key.Binding = .right, }; const GutterContext = struct { /// Line index in the content (0-based). index: usize, /// Total content lines. total: usize, /// True when this row is a soft-wrap continuation of the prior row. /// Always false in v1 viewport (no soft-wrap yet). soft: bool = false, }; /// Callback that returns the prefix string rendered to the left of each /// visible line. The string's cell width must be the same on every call; /// the viewport reserves that width up-front. const GutterFn = *const fn (ctx: GutterContext) []const u8; /// Callback that returns an optional style applied to a given content line. const LineStyleFn = *const fn (index: usize) matte.Style; const Highlight = struct { line: usize, col_start: u16, col_end: u16, }; width: u16 = 0, height: u16 = 0, key_map: KeyMap = .{}, /// When true, the rendered output always pads to `height` rows even if the /// content is shorter. fill_height: bool = false, /// When true, lines wider than the content width wrap onto continuation /// rows instead of horizontally scrolling. Disables `setXOffset` and /// makes `y_offset` count visual rows. soft_wrap: bool = false, /// Optional gutter rendered to the left of every line. gutter_fn: ?GutterFn = null, /// Optional per-line style applied to the line content (after the gutter). line_style_fn: ?LineStyleFn = null, /// Backing buffer for owned content. `lines` slices into this. content: ArrayList(u8) = .empty, /// One slice per line, in display order. May reference `content` (owned) /// or external memory (if loaded via `setContentLinesBorrow`). lines: ArrayList([]const u8) = .empty, y_offset: u16 = 0, /// Horizontal scroll offset in cells. x_offset: u16 = 0, /// Columns scrolled per ScrollLeft/Right call. horizontal_step: u16 = 6, /// Cached width of the widest line; recomputed on setContent. longest_line_width: u16 = 0, /// Whether mouse-wheel events trigger scrolling. mouse_wheel_enabled: bool = true, /// Lines scrolled per wheel notch. mouse_wheel_delta: u16 = 3, /// Borrowed highlight ranges. Single-line spans only in v1; multi-line /// matches need to be split into per-line entries by the caller. highlights: []const Highlight = &.{}, current_highlight: usize = 0, highlight_style: matte.Style = .none, selected_highlight_style: matte.Style = .none, model: tea.Model = .{ .vtable = &.{ .init = vtableInit, .update = vtableUpdate, .view = vtableView, }, }, fn vtableInit(_: *tea.Model) ?tea.Cmd { return null; } fn vtableUpdate(m: *tea.Model, msg: tea.Msg) ?tea.Cmd { const self: *Viewport = @fieldParentPtr("model", m); return self.update(msg); } fn vtableView(m: *tea.Model, w: *Writer) Writer.Error!tea.View { const self: *Viewport = @fieldParentPtr("model", m); try self.view(w); return .{}; } pub fn deinit(self: *Viewport, allocator: Allocator) void { self.content.deinit(allocator); self.lines.deinit(allocator); } pub fn setWidth(self: *Viewport, cells: u16) void { self.width = cells; self.clampOffset(); } pub fn setHeight(self: *Viewport, rows: u16) void { self.height = rows; self.clampOffset(); } /// Replace the content. Splits `text` on `\n` and normalizes `\r\n` like /// bubbles' `SetContent` (a trailing `\n` yields a trailing empty line; a /// lone empty line becomes no content). Owns a copy of the text. pub fn setContent(self: *Viewport, allocator: Allocator, text: []const u8) !void { self.content.clearRetainingCapacity(); self.lines.clearRetainingCapacity(); try self.content.appendSlice(allocator, text); try self.splitIntoLines(allocator, self.content.items); self.finishContentLoad(); } /// Replace the content with a borrowed list of lines. Lines must outlive /// the viewport; `setContent`-allocated content is freed. Like bubbles' /// `SetContentLines`, lines containing `\r\n` are split into multiple lines. pub fn setContentLinesBorrow(self: *Viewport, allocator: Allocator, src_lines: []const []const u8) !void { self.content.clearRetainingCapacity(); self.lines.clearRetainingCapacity(); for (src_lines) |line| try self.splitIntoLines(allocator, line); self.finishContentLoad(); } /// Split `s` on `\n`, folding the `\r` of any `\r\n` pair. Trailing empty /// lines are preserved (mirrors `strings.Split` after `ReplaceAll("\r\n", /// "\n")`). fn splitIntoLines(self: *Viewport, allocator: Allocator, s: []const u8) !void { var line_start: usize = 0; var i: usize = 0; while (i < s.len) : (i += 1) { if (s[i] != '\n') continue; var end = i; if (end > line_start and s[end - 1] == '\r') end -= 1; try self.lines.append(allocator, s[line_start..end]); line_start = i + 1; } try self.lines.append(allocator, s[line_start..]); } fn finishContentLoad(self: *Viewport) void { // bubbles treats a single zero-width line as "no content". if (self.lines.items.len == 1 and matte.measure.cellWidth(self.lines.items[0]) == 0) self.lines.clearRetainingCapacity(); self.refreshLongest(); self.clearHighlights(); self.clampOffset(); } fn refreshLongest(self: *Viewport) void { var max_w: u16 = 0; for (self.lines.items) |line| { const w = matte.measure.cellWidth(line); if (w > max_w) max_w = w; } self.longest_line_width = max_w; } pub fn lineCount(self: *const Viewport) u16 { return @intCast(@min(self.lines.items.len, std.math.maxInt(u16))); } /// Total visible rows the content occupies (= lineCount when soft_wrap is /// off; sums per-line wrap counts otherwise). pub fn totalVisualRows(self: *const Viewport) usize { if (!self.soft_wrap) return self.lines.items.len; const content_w = self.contentWidth(); if (content_w == 0) return self.lines.items.len; var total: usize = 0; for (self.lines.items) |line| { const w = matte.measure.cellWidth(line); total += visualRowsForWidth(w, content_w); } return total; } fn visualRowsForWidth(line_width: u16, max_w: u16) usize { if (max_w == 0 or line_width == 0) return 1; return (line_width + max_w - 1) / max_w; } pub fn yOffset(self: *const Viewport) u16 { return self.y_offset; } pub fn setYOffset(self: *Viewport, offset: u16) void { self.y_offset = @min(offset, self.maxYOffset()); } pub fn maxYOffset(self: *const Viewport) u16 { const total = self.totalVisualRows(); const total_u16: u16 = @intCast(@min(total, std.math.maxInt(u16))); if (total_u16 <= self.height) return 0; return total_u16 - self.height; } pub fn atTop(self: *const Viewport) bool { return self.y_offset == 0; } pub fn atBottom(self: *const Viewport) bool { return self.y_offset >= self.maxYOffset(); } /// Whether the viewport is scrolled beyond the last line (can happen after a /// height change). Mirrors bubbles' `PastBottom`. pub fn pastBottom(self: *const Viewport) bool { return self.y_offset > self.maxYOffset(); } /// Number of lines currently visible in the viewport, capped by `height`. /// Mirrors bubbles' `VisibleLineCount`. pub fn visibleLineCount(self: *const Viewport) usize { const visible = self.totalVisualRows() -| @as(usize, self.y_offset); return @min(visible, self.height); } /// Returns the content as one `\n`-joined string, exactly as bubbles' /// `GetContent`. The caller owns the result. pub fn getContent(self: *const Viewport, allocator: Allocator) ![]u8 { var buf: ArrayList(u8) = .empty; errdefer buf.deinit(allocator); for (self.lines.items, 0..) |line, i| { if (i > 0) try buf.append(allocator, '\n'); try buf.appendSlice(allocator, line); } return buf.toOwnedSlice(allocator); } pub fn scrollPercent(self: *const Viewport) f32 { // Count visual rows (soft-wrap aware), matching bubbles' calculateLine(0). const total = self.totalVisualRows(); if (total == 0 or self.height >= total) return 1.0; const y: f32 = @floatFromInt(self.y_offset); const h: f32 = @floatFromInt(self.height); const t: f32 = @floatFromInt(total); const v = y / (t - h); return std.math.clamp(v, 0.0, 1.0); } pub fn scrollDown(self: *Viewport, n: u16) void { if (self.atBottom() or n == 0) return; self.setYOffset(self.y_offset +| n); } pub fn scrollUp(self: *Viewport, n: u16) void { if (self.atTop() or n == 0) return; self.y_offset = if (self.y_offset > n) self.y_offset - n else 0; } pub fn pageDown(self: *Viewport) void { self.scrollDown(self.height); } pub fn pageUp(self: *Viewport) void { self.scrollUp(self.height); } pub fn halfPageDown(self: *Viewport) void { self.scrollDown(self.height / 2); } pub fn halfPageUp(self: *Viewport) void { self.scrollUp(self.height / 2); } pub fn gotoTop(self: *Viewport) void { self.y_offset = 0; } pub fn gotoBottom(self: *Viewport) void { self.y_offset = self.maxYOffset(); } pub fn setHighlights(self: *Viewport, list: []const Highlight) void { self.highlights = list; self.current_highlight = 0; self.ensureHighlightVisible(); } pub fn clearHighlights(self: *Viewport) void { self.highlights = &.{}; self.current_highlight = 0; } pub fn highlightNext(self: *Viewport) void { if (self.highlights.len == 0) return; self.current_highlight = (self.current_highlight + 1) % self.highlights.len; self.ensureHighlightVisible(); } pub fn highlightPrevious(self: *Viewport) void { if (self.highlights.len == 0) return; self.current_highlight = (self.current_highlight + self.highlights.len - 1) % self.highlights.len; self.ensureHighlightVisible(); } fn ensureHighlightVisible(self: *Viewport) void { if (self.current_highlight >= self.highlights.len) return; const h = self.highlights[self.current_highlight]; const line: u16 = @intCast(@min(h.line, std.math.maxInt(u16))); if (line < self.y_offset or line >= self.y_offset +| self.height) { self.setYOffset(line); } if (!self.soft_wrap) { // Bring the column into view. const content_w = self.contentWidth(); if (h.col_end > self.x_offset +| content_w) { const target: u16 = if (h.col_start > self.horizontal_step) h.col_start - self.horizontal_step else 0; self.setXOffset(target); } else if (h.col_start < self.x_offset) { self.setXOffset(h.col_start); } } } pub fn xOffset(self: *const Viewport) u16 { return self.x_offset; } pub fn setXOffset(self: *Viewport, x: u16) void { if (self.soft_wrap) return; self.x_offset = @min(x, self.maxXOffset()); } pub fn maxXOffset(self: *const Viewport) u16 { const content_w = self.contentWidth(); if (self.longest_line_width <= content_w) return 0; return self.longest_line_width - content_w; } pub fn scrollLeft(self: *Viewport, n: u16) void { self.x_offset = if (self.x_offset > n) self.x_offset - n else 0; } pub fn scrollRight(self: *Viewport, n: u16) void { self.setXOffset(self.x_offset +| n); } pub fn horizontalScrollPercent(self: *const Viewport) f32 { const max_x = self.maxXOffset(); if (max_x == 0) return 1.0; return @as(f32, @floatFromInt(self.x_offset)) / @as(f32, @floatFromInt(max_x)); } fn contentWidth(self: *const Viewport) u16 { const gutter_w = self.gutterWidth(); return if (self.width > gutter_w) self.width - gutter_w else 0; } pub fn update(self: *Viewport, msg: tea.Msg) ?tea.Cmd { switch (msg) { .key_press => |k| { if (self.key_map.page_down.matches(k)) self.pageDown(); if (self.key_map.page_up.matches(k)) self.pageUp(); if (self.key_map.half_page_down.matches(k)) self.halfPageDown(); if (self.key_map.half_page_up.matches(k)) self.halfPageUp(); if (self.key_map.down.matches(k)) self.scrollDown(1); if (self.key_map.up.matches(k)) self.scrollUp(1); if (self.key_map.left.matches(k)) self.scrollLeft(self.horizontal_step); if (self.key_map.right.matches(k)) self.scrollRight(self.horizontal_step); }, .mouse_wheel => |m| { if (!self.mouse_wheel_enabled) return null; switch (m.button) { .wheel_up => if (m.mods.shift) self.scrollLeft(self.horizontal_step) else self.scrollUp(self.mouse_wheel_delta), .wheel_down => if (m.mods.shift) self.scrollRight(self.horizontal_step) else self.scrollDown(self.mouse_wheel_delta), .wheel_left => self.scrollLeft(self.horizontal_step), .wheel_right => self.scrollRight(self.horizontal_step), else => {}, } }, else => {}, } return null; } pub fn view(self: *const Viewport, w: *Writer) Writer.Error!void { if (self.height == 0 or self.width == 0) return; if (self.soft_wrap) try self.viewSoftWrap(w) else try self.viewHardCut(w); } fn viewHardCut(self: *const Viewport, w: *Writer) Writer.Error!void { const total = self.lineCount(); const start: u16 = self.y_offset; const end: u16 = @min(start +| self.height, total); const content_w = self.contentWidth(); var rendered: u16 = 0; var i = start; while (i < end) : (i += 1) { if (rendered > 0) try w.writeByte('\n'); if (self.gutter_fn) |gfn| try w.writeAll(gfn(.{ .index = i, .total = self.lines.items.len, })); if (self.line_style_fn) |sfn| if (sfn(i).maybeStyle()) |s| try openInlineStyle(w, s); var ranges_buf: [16]StyledRange = undefined; const ranges = self.gatherRanges(&ranges_buf, i); try writeCut(w, self.lines.items[i], self.x_offset, self.x_offset +| content_w, ranges); if (self.line_style_fn) |sfn| if (sfn(i).maybeStyle()) |s| try closeInlineStyle(w, s); rendered += 1; } if (!self.fill_height) return; while (rendered < self.height) : (rendered += 1) { if (rendered > 0) try w.writeByte('\n'); if (self.gutter_fn) |gfn| try w.writeAll(gfn(.{ .index = self.lines.items.len, .total = self.lines.items.len, })); } } fn viewSoftWrap(self: *const Viewport, w: *Writer) Writer.Error!void { const content_w = self.contentWidth(); if (content_w == 0) return; const total = self.lines.items.len; // Walk logical lines, expanding each into chunks of `content_w` cells. // Skip until we've scrolled past `y_offset` visual rows; then emit up // to `height` rows. var visual_skipped: usize = 0; var rendered: u16 = 0; var line_idx: usize = 0; while (line_idx < total and rendered < self.height) : (line_idx += 1) { const line = self.lines.items[line_idx]; const line_w = matte.measure.cellWidth(line); const rows = visualRowsForWidth(line_w, content_w); var chunk: usize = 0; while (chunk < rows and rendered < self.height) : (chunk += 1) { if (visual_skipped < self.y_offset) { visual_skipped += 1; continue; } if (rendered > 0) try w.writeByte('\n'); if (self.gutter_fn) |gfn| try w.writeAll(gfn(.{ .index = line_idx, .total = total, .soft = chunk > 0, })); if (self.line_style_fn) |sfn| if (sfn(line_idx).maybeStyle()) |s| try openInlineStyle(w, s); const col_start: u16 = @intCast(chunk * @as(usize, content_w)); var ranges_buf: [16]StyledRange = undefined; const ranges = self.gatherRanges(&ranges_buf, line_idx); try writeCut(w, line, col_start, col_start +| content_w, ranges); if (self.line_style_fn) |sfn| if (sfn(line_idx).maybeStyle()) |s| try closeInlineStyle(w, s); rendered += 1; } } if (!self.fill_height) return; while (rendered < self.height) : (rendered += 1) { if (rendered > 0) try w.writeByte('\n'); if (self.gutter_fn) |gfn| try w.writeAll(gfn(.{ .index = total, .total = total, })); } } fn gutterWidth(self: *const Viewport) u16 { const gfn = self.gutter_fn orelse return 0; return matte.measure.cellWidth(gfn(.{ .index = 0, .total = 0 })); } fn gatherRanges(self: *const Viewport, buf: []StyledRange, line_idx: usize) []const StyledRange { if (self.highlights.len == 0) return &.{}; var n: usize = 0; for (self.highlights, 0..) |h, idx| { if (h.line != line_idx) continue; if (n >= buf.len) break; const style = if (idx == self.current_highlight) self.selected_highlight_style.maybeStyle() orelse self.highlight_style else self.highlight_style; if (style.isNone()) continue; buf[n] = .{ .col_start = h.col_start, .col_end = h.col_end, .style = style }; n += 1; } return buf[0..n]; } fn openInlineStyle(w: *Writer, s: matte.Style) Writer.Error!void { if (s.internal.bold) try w.writeAll("\x1b[1m"); if (s.internal.faint) try w.writeAll("\x1b[2m"); if (s.internal.italic) try w.writeAll("\x1b[3m"); switch (s.internal.underline.style) { .none => {}, .single => try w.writeAll("\x1b[4m"), .double => try w.writeAll("\x1b[4:2m"), .curly => try w.writeAll("\x1b[4:3m"), .dotted => try w.writeAll("\x1b[4:4m"), .dashed => try w.writeAll("\x1b[4:5m"), } if (s.internal.foreground) |c| try c.writeSgr(w, .fg); if (s.internal.background) |c| try c.writeSgr(w, .bg); } fn closeInlineStyle(w: *Writer, s: matte.Style) Writer.Error!void { if (s.internal.bold or s.internal.italic or s.internal.underline.style != .none or s.internal.faint or s.internal.foreground != null or s.internal.background != null) try w.writeAll("\x1b[0m"); } fn clampOffset(self: *Viewport) void { self.y_offset = @min(self.y_offset, self.maxYOffset()); } const StyledRange = struct { col_start: u16, col_end: u16, style: matte.Style, }; /// Emits cells [col_start, col_end) of `line`, ANSI-aware. CSI escapes /// always pass through (so SGR opened before col_start still affects the /// visible portion). When `ranges` is non-empty, cells inside any range /// are wrapped in that range's style. Trailing `\x1b[0m` if any escape /// or range opened. fn writeCut( w: *Writer, line: []const u8, col_start: u16, col_end: u16, ranges: []const StyledRange, ) Writer.Error!void { if (col_end <= col_start) return; var visible: u16 = 0; var i: usize = 0; var saw_escape = false; var current_range: ?usize = null; while (i < line.len) { if (line[i] == 0x1b) { saw_escape = true; const start = i; i += 1; if (i < line.len and line[i] == '[') { i += 1; while (i < line.len and (line[i] < 0x40 or line[i] > 0x7e)) : (i += 1) {} if (i < line.len) i += 1; } else if (i < line.len) i += 1; try w.writeAll(line[start..i]); continue; } const cell_len: usize = if (line[i] < 0x80) 1 else std.unicode.utf8ByteSequenceLength(line[i]) catch 1; const safe_len = @min(cell_len, line.len - i); if (visible >= col_end) break; if (visible >= col_start) { const r = findRange(ranges, visible); if (r != current_range) { if (current_range != null) try w.writeAll("\x1b[0m"); if (r) |idx| try openInlineStyle(w, ranges[idx].style); current_range = r; } try w.writeAll(line[i .. i + safe_len]); } visible += 1; i += safe_len; } if (current_range != null) try w.writeAll("\x1b[0m"); if (saw_escape) try w.writeAll("\x1b[0m"); } fn findRange(ranges: []const StyledRange, col: u16) ?usize { for (ranges, 0..) |r, idx| { if (col >= r.col_start and col < r.col_end) return idx; } return null; } // ---- tests ---- const testing = std.testing; test "setContent splits and counts lines" { var v: Viewport = .{}; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "a\nb\nc"); try testing.expectEqual(@as(u16, 3), v.lineCount()); } test "setContent keeps trailing empty line like strings.Split" { var v: Viewport = .{}; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "a\n"); try testing.expectEqual(@as(u16, 2), v.lineCount()); try testing.expectEqualStrings("", v.lines.items[1]); var v2: Viewport = .{}; defer v2.deinit(testing.allocator); try v2.setContent(testing.allocator, ""); try testing.expectEqual(@as(u16, 0), v2.lineCount()); } test "setContent normalizes CRLF" { var v: Viewport = .{}; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "a\r\nb"); try testing.expectEqual(@as(u16, 2), v.lineCount()); try testing.expectEqualStrings("a", v.lines.items[0]); try testing.expectEqualStrings("b", v.lines.items[1]); } test "getContent joins lines" { var v: Viewport = .{}; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "a\nb"); const joined = try v.getContent(testing.allocator); defer testing.allocator.free(joined); try testing.expectEqualStrings("a\nb", joined); } test "pastBottom and visibleLineCount" { var v: Viewport = .{ .height = 2 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "1\n2\n3\n4\n5"); try testing.expect(!v.pastBottom()); try testing.expectEqual(@as(usize, 2), v.visibleLineCount()); v.height = 1; try testing.expect(!v.pastBottom()); try testing.expectEqual(@as(usize, 1), v.visibleLineCount()); v.setYOffset(10); v.height = 2; try testing.expect(v.pastBottom()); } test "scrollPercent counts visual rows under soft wrap" { var v: Viewport = .{ .height = 1, .soft_wrap = true, .width = 3 }; defer v.deinit(testing.allocator); // "abcdef" wraps to 2 visual rows. try v.setContent(testing.allocator, "abcdef"); try testing.expectEqual(@as(f32, 0.0), v.scrollPercent()); v.setYOffset(v.maxYOffset()); try testing.expectEqual(@as(f32, 1.0), v.scrollPercent()); } test "scroll bounds" { var v: Viewport = .{ .height = 2 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "1\n2\n3\n4\n5"); try testing.expect(v.atTop()); v.scrollDown(1); try testing.expectEqual(@as(u16, 1), v.y_offset); v.scrollDown(100); try testing.expect(v.atBottom()); try testing.expectEqual(v.maxYOffset(), v.y_offset); v.scrollUp(100); try testing.expect(v.atTop()); } test "page navigation" { var v: Viewport = .{ .height = 3 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "1\n2\n3\n4\n5\n6\n7\n8\n9"); v.pageDown(); try testing.expectEqual(@as(u16, 3), v.y_offset); v.halfPageUp(); try testing.expectEqual(@as(u16, 2), v.y_offset); } test "view renders visible window" { var v: Viewport = .{ .width = 8, .height = 2 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "a\nbb\nccc\ndddd\neeeee"); v.setYOffset(1); var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("bb\nccc", w.buffered()); } test "horizontal scroll shifts visible columns" { var v: Viewport = .{ .width = 3, .height = 1 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "abcdefgh"); v.setXOffset(2); var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("cde", w.buffered()); } test "scrollRight clamps to maxXOffset" { var v: Viewport = .{ .width = 4, .height = 1 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "1234567890"); v.scrollRight(100); try testing.expectEqual(v.maxXOffset(), v.x_offset); } test "view truncates wide lines to width" { var v: Viewport = .{ .width = 3, .height = 1 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "abcdef"); var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("abc", w.buffered()); } test "view preserves SGR through truncation" { var v: Viewport = .{ .width = 3, .height = 1 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "\x1b[31mabcdef\x1b[0m"); var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("\x1b[31mabc\x1b[0m", w.buffered()); } test "fill_height pads short content" { var v: Viewport = .{ .width = 4, .height = 4, .fill_height = true }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "x"); var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("x\n\n\n", w.buffered()); } test "gutter_fn prepends per line and shrinks content width" { const G = struct { fn gut(_: GutterContext) []const u8 { return "| "; } }; var v: Viewport = .{ .width = 6, .height = 2, .gutter_fn = G.gut }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "abcdef\nghi"); var buf: [128]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); // content_w = 6 - 2 = 4 → "abcd" / "ghi" with truncation/padding. try testing.expectEqualStrings("| abcd\n| ghi", w.buffered()); } test "line_style_fn wraps styled lines" { const S = struct { fn st(_: usize) matte.Style { return .new(.{ .bold = true }); } }; var v: Viewport = .{ .width = 3, .height = 1, .line_style_fn = S.st }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "abc"); var buf: [128]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("\x1b[1mabc\x1b[0m", w.buffered()); } test "highlights wrap matched cells" { var v: Viewport = .{ .width = 10, .height = 1, .highlight_style = .new(.{ .bold = true }), }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "abcdefghij"); const hi = [_]Highlight{.{ .line = 0, .col_start = 2, .col_end = 5 }}; v.setHighlights(&hi); var buf: [128]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("ab\x1b[1mcde\x1b[0mfghij", w.buffered()); } test "soft-wrap expands long line into rows" { var v: Viewport = .{ .width = 3, .height = 3, .soft_wrap = true }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "abcdefgh"); var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("abc\ndef\ngh", w.buffered()); } test "soft-wrap y_offset counts visual rows" { var v: Viewport = .{ .width = 3, .height = 2, .soft_wrap = true }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "abcdefgh"); v.setYOffset(1); // skip "abc" var buf: [64]u8 = undefined; var w: Writer = .fixed(&buf); try v.view(&w); try testing.expectEqualStrings("def\ngh", w.buffered()); } test "scrollPercent" { var v: Viewport = .{ .height = 2 }; defer v.deinit(testing.allocator); try v.setContent(testing.allocator, "1\n2\n3\n4"); try testing.expectEqual(@as(f32, 0.0), v.scrollPercent()); v.gotoBottom(); try testing.expectEqual(@as(f32, 1.0), v.scrollPercent()); }