diff --git a/build.zig b/build.zig index 449c21c..891f024 100644 --- a/build.zig +++ b/build.zig @@ -39,6 +39,7 @@ pub fn build(b: *std.Build) void { "mouse", "accessibility", "wasm_app", + "text_overflow", "async_tasks", "sub_program", "layers", diff --git a/examples/text_overflow.zig b/examples/text_overflow.zig new file mode 100644 index 0000000..e15dd11 --- /dev/null +++ b/examples/text_overflow.zig @@ -0,0 +1,114 @@ +//! ZigZag Text Overflow Example +//! Demonstrates overflow policies: hidden, ellipsis, word_wrap, char_wrap. + +const std = @import("std"); +const zz = @import("zigzag"); + +const Model = struct { + pub const Msg = union(enum) { + key: zz.KeyEvent, + }; + + pub fn init(self: *Model, _: *zz.Context) zz.Cmd(Msg) { + self.* = .{}; + return .none; + } + + pub fn update(_: *Model, msg: Msg, _: *zz.Context) zz.Cmd(Msg) { + switch (msg) { + .key => |k| switch (k.key) { + .char => |c| if (c == 'q') return .quit, + .escape => return .quit, + else => {}, + }, + } + return .none; + } + + pub fn view(_: *const Model, ctx: *const zz.Context) []const u8 { + const alloc = ctx.allocator; + const long_text = "The quick brown fox jumps over the lazy dog. This is a long sentence that demonstrates how text overflow policies work in the ZigZag TUI framework."; + const box_width: u16 = 35; + + // Title + var title_style = zz.Style{}; + title_style = title_style.bold(true); + title_style = title_style.fg(zz.Color.cyan()); + title_style = title_style.inline_style(true); + const title = title_style.render(alloc, "Text Overflow Policies") catch "Text Overflow Policies"; + + // visible (no overflow handling) + var vis_style = zz.Style{}; + vis_style = vis_style.width(box_width); + vis_style = vis_style.borderAll(zz.Border.rounded); + vis_style = vis_style.borderForeground(zz.Color.gray(8)); + vis_style = vis_style.overflow(.visible); + const vis = vis_style.render(alloc, long_text) catch ""; + + // hidden (clip) + var clip_style = zz.Style{}; + clip_style = clip_style.width(box_width); + clip_style = clip_style.borderAll(zz.Border.rounded); + clip_style = clip_style.borderForeground(zz.Color.yellow()); + clip_style = clip_style.overflow(.hidden); + const clip = clip_style.render(alloc, long_text) catch ""; + + // ellipsis + var ell_style = zz.Style{}; + ell_style = ell_style.width(box_width); + ell_style = ell_style.borderAll(zz.Border.rounded); + ell_style = ell_style.borderForeground(zz.Color.green()); + ell_style = ell_style.overflow(.ellipsis); + const ell = ell_style.render(alloc, long_text) catch ""; + + // word_wrap + var ww_style = zz.Style{}; + ww_style = ww_style.width(box_width); + ww_style = ww_style.borderAll(zz.Border.rounded); + ww_style = ww_style.borderForeground(zz.Color.blue()); + ww_style = ww_style.overflow(.word_wrap); + const ww = ww_style.render(alloc, long_text) catch ""; + + // char_wrap + var cw_style = zz.Style{}; + cw_style = cw_style.width(box_width); + cw_style = cw_style.borderAll(zz.Border.rounded); + cw_style = cw_style.borderForeground(zz.Color.magenta()); + cw_style = cw_style.overflow(.char_wrap); + const cw = cw_style.render(alloc, long_text) catch ""; + + // Labels + var label_style = zz.Style{}; + label_style = label_style.fg(zz.Color.gray(12)); + label_style = label_style.inline_style(true); + + const content = std.fmt.allocPrint(alloc, + "{s}\n\n{s} visible (default):\n{s}\n\n{s} hidden (clip):\n{s}\n\n{s} ellipsis:\n{s}\n\n{s} word_wrap:\n{s}\n\n{s} char_wrap:\n{s}\n\nPress q to quit", + .{ + title, + label_style.render(alloc, "\xe2\x96\xb8") catch ">", + vis, + label_style.render(alloc, "\xe2\x96\xb8") catch ">", + clip, + label_style.render(alloc, "\xe2\x96\xb8") catch ">", + ell, + label_style.render(alloc, "\xe2\x96\xb8") catch ">", + ww, + label_style.render(alloc, "\xe2\x96\xb8") catch ">", + cw, + }, + ) catch "Error"; + + return content; + } +}; + +pub fn main() !void { + var gpa = std.heap.GeneralPurposeAllocator(.{}){}; + defer _ = gpa.deinit(); + + var program = try zz.Program(Model).init(gpa.allocator()); + defer program.deinit(); + + try program.run(); +} diff --git a/src/root.zig b/src/root.zig index a2d6709..e551dc4 100644 --- a/src/root.zig +++ b/src/root.zig @@ -286,6 +286,9 @@ pub const AdaptiveColor = color.AdaptiveColor; pub const CompleteColor = color.CompleteColor; pub const CompleteAdaptiveColor = color.CompleteAdaptiveColor; +// Overflow +pub const Overflow = style.Overflow; + // Style utilities pub const StyleRange = style.StyleRange; pub const renderWithRanges = style.renderWithRanges; diff --git a/src/style/overflow.zig b/src/style/overflow.zig new file mode 100644 index 0000000..1f29995 --- /dev/null +++ b/src/style/overflow.zig @@ -0,0 +1,262 @@ +//! Text overflow handling for the ZigZag TUI framework. +//! Provides configurable overflow policies: clip, ellipsis, word-wrap, char-wrap. + +const std = @import("std"); +const measure = @import("../layout/measure.zig"); + +/// Overflow policy for text that exceeds width constraints. +pub const Overflow = enum { + /// No overflow handling (default). + visible, + /// Clip text without indicator. + hidden, + /// Truncate with ellipsis character. + ellipsis, + /// Wrap at word boundaries. + word_wrap, + /// Wrap at character boundaries. + char_wrap, +}; + +/// Apply an overflow policy to text with a given max width. +/// Handles each line independently. ANSI-aware. +pub fn applyOverflow( + allocator: std.mem.Allocator, + text: []const u8, + max_width: u16, + policy: Overflow, +) ![]const u8 { + if (policy == .visible or max_width == 0) return text; + + var result = std.array_list.Managed(u8).init(allocator); + + var lines = std.mem.splitScalar(u8, text, '\n'); + var first_line = true; + while (lines.next()) |line| { + if (!first_line) try result.append('\n'); + first_line = false; + + switch (policy) { + .hidden => try applyClip(&result, line, max_width), + .ellipsis => try applyEllipsis(&result, line, max_width), + .word_wrap => try applyWordWrap(&result, line, max_width), + .char_wrap => try applyCharWrap(&result, line, max_width), + .visible => unreachable, + } + } + + return try result.toOwnedSlice(); +} + +fn applyClip(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + var visible_width: usize = 0; + var i: usize = 0; + while (i < line.len) { + // Skip ANSI escape sequences + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + const char_width = charDisplayWidth(line, i); + if (visible_width + char_width > max_width) break; + + const byte_len = charByteLen(line[i]); + try result.appendSlice(line[i .. i + byte_len]); + visible_width += char_width; + i += byte_len; + } +} + +fn applyEllipsis(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + const line_width = measure.width(line); + if (line_width <= max_width) { + try result.appendSlice(line); + return; + } + + if (max_width <= 1) { + if (max_width == 1) try result.appendSlice("\xe2\x80\xa6"); // … + return; + } + + // Truncate to max_width - 1 and add ellipsis + var visible_width: usize = 0; + var i: usize = 0; + const target_width = max_width - 1; + while (i < line.len) { + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + const char_width = charDisplayWidth(line, i); + if (visible_width + char_width > target_width) break; + + const byte_len = charByteLen(line[i]); + try result.appendSlice(line[i .. i + byte_len]); + visible_width += char_width; + i += byte_len; + } + + try result.appendSlice("\xe2\x80\xa6"); // … +} + +fn applyWordWrap(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + if (measure.width(line) <= max_width) { + try result.appendSlice(line); + return; + } + + var visible_width: usize = 0; + var i: usize = 0; + var last_space: usize = 0; + var last_space_result_pos: usize = result.items.len; + + while (i < line.len) { + // Skip ANSI sequences + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + if (line[i] == ' ') { + last_space = i; + last_space_result_pos = result.items.len; + } + + const char_width = charDisplayWidth(line, i); + if (visible_width + char_width > max_width) { + // Wrap at last space if possible + if (last_space_result_pos > result.items.len - visible_width + 1) { + // Replace space with newline in result + result.items[last_space_result_pos] = '\n'; + visible_width = measure.width(line[last_space + 1 .. i]); + } else { + // No space found, wrap at current position + try result.append('\n'); + visible_width = 0; + } + } + + const byte_len = charByteLen(line[i]); + try result.appendSlice(line[i .. i + byte_len]); + visible_width += char_width; + i += byte_len; + } +} + +fn applyCharWrap(result: *std.array_list.Managed(u8), line: []const u8, max_width: u16) !void { + if (measure.width(line) <= max_width) { + try result.appendSlice(line); + return; + } + + var visible_width: usize = 0; + var i: usize = 0; + var first_on_line = true; + + while (i < line.len) { + // Skip ANSI sequences + if (line[i] == 0x1b and i + 1 < line.len and line[i + 1] == '[') { + const seq_start = i; + i += 2; + while (i < line.len and line[i] != 'm' and line[i] != 'H' and line[i] != 'J' and line[i] != 'K' and line[i] != 'A' and line[i] != 'B' and line[i] != 'C' and line[i] != 'D') : (i += 1) {} + if (i < line.len) i += 1; + try result.appendSlice(line[seq_start..i]); + continue; + } + + const char_width = charDisplayWidth(line, i); + if (visible_width + char_width > max_width and !first_on_line) { + try result.append('\n'); + visible_width = 0; + first_on_line = true; + } + + const byte_len = charByteLen(line[i]); + try result.appendSlice(line[i .. i + byte_len]); + visible_width += char_width; + first_on_line = false; + i += byte_len; + } +} + +fn charDisplayWidth(text: []const u8, pos: usize) usize { + const byte = text[pos]; + if (byte < 0x80) return 1; + // Simple heuristic: CJK characters are 2-wide, others 1-wide + // Full-width ranges: U+1100-U+115F, U+2E80-U+A4CF, U+AC00-U+D7A3, etc. + const byte_len = charByteLen(byte); + if (byte_len >= 3 and pos + byte_len <= text.len) { + const cp = std.unicode.utf8Decode(text[pos..][0..byte_len]) catch return 1; + if (isWideCodepoint(cp)) return 2; + } + return 1; +} + +fn isWideCodepoint(cp: u21) bool { + return (cp >= 0x1100 and cp <= 0x115F) or + (cp >= 0x2E80 and cp <= 0x303E) or + (cp >= 0x3041 and cp <= 0x33BF) or + (cp >= 0x3400 and cp <= 0x4DBF) or + (cp >= 0x4E00 and cp <= 0xA4CF) or + (cp >= 0xAC00 and cp <= 0xD7A3) or + (cp >= 0xF900 and cp <= 0xFAFF) or + (cp >= 0xFE30 and cp <= 0xFE6F) or + (cp >= 0xFF01 and cp <= 0xFF60) or + (cp >= 0xFFE0 and cp <= 0xFFE6) or + (cp >= 0x20000 and cp <= 0x2FFFD) or + (cp >= 0x30000 and cp <= 0x3FFFD); +} + +fn charByteLen(first_byte: u8) usize { + if (first_byte < 0x80) return 1; + if (first_byte & 0xE0 == 0xC0) return 2; + if (first_byte & 0xF0 == 0xE0) return 3; + if (first_byte & 0xF8 == 0xF0) return 4; + return 1; +} + +// --------------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------------- + +test "clip truncates at max width" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hello, World!", 5, .hidden); + defer allocator.free(result); + try std.testing.expectEqualStrings("Hello", result); +} + +test "ellipsis adds character" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hello, World!", 6, .ellipsis); + defer allocator.free(result); + try std.testing.expectEqualStrings("Hello\xe2\x80\xa6", result); +} + +test "visible returns original" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hello", 3, .visible); + try std.testing.expectEqualStrings("Hello", result); +} + +test "short text unchanged with ellipsis" { + const allocator = std.testing.allocator; + const result = try applyOverflow(allocator, "Hi", 10, .ellipsis); + defer allocator.free(result); + try std.testing.expectEqualStrings("Hi", result); +} diff --git a/src/style/style.zig b/src/style/style.zig index b2a208f..a8e0078 100644 --- a/src/style/style.zig +++ b/src/style/style.zig @@ -6,6 +6,8 @@ const color_mod = @import("color.zig"); const border_mod = @import("border.zig"); const ansi = @import("../terminal/ansi.zig"); const measure = @import("../layout/measure.zig"); +const overflow_mod = @import("overflow.zig"); +pub const Overflow = overflow_mod.Overflow; pub const Color = color_mod.Color; pub const Border = border_mod.Border; @@ -126,6 +128,9 @@ pub const Style = struct { // Transform function transform_fn: ?*const fn (std.mem.Allocator, []const u8) []const u8 = null, + // Text overflow + overflow_mode: Overflow = .visible, + // Whitespace formatting controls underline_spaces: bool = false, strikethrough_spaces: bool = false, @@ -483,6 +488,13 @@ pub const Style = struct { return s; } + // Overflow setter + pub fn overflow(self: Self, mode: Overflow) Self { + var s = self; + s.overflow_mode = mode; + return s; + } + // Alignment setters pub fn alignH(self: Self, a: Align) Self { var s = self; @@ -585,6 +597,14 @@ pub const Style = struct { processed_text = tf(allocator, processed_text); } + // Apply overflow policy before dimension calculation + if (self.overflow_mode != .visible) { + const ow = self.width_val orelse (self.max_width_val orelse 0); + if (ow > 0) { + processed_text = overflow_mod.applyOverflow(allocator, processed_text, ow, self.overflow_mode) catch processed_text; + } + } + // Calculate content dimensions const content_width = measure.width(processed_text); const content_height = measure.height(processed_text);