From ac2e3fe2df3419b71276f86fa9c45fd39d668f23 Mon Sep 17 00:00:00 2001 From: CJ van den Berg Date: Wed, 26 Mar 2025 21:48:31 +0100 Subject: [PATCH] feat: prettify json representation of themes --- src/theme.zig | 36 +++++++++++++++++++++++++++++++++++- 1 file changed, 35 insertions(+), 1 deletion(-) diff --git a/src/theme.zig b/src/theme.zig index 290a8d9..8dc143c 100644 --- a/src/theme.zig +++ b/src/theme.zig @@ -41,6 +41,40 @@ tokens: Tokens, pub const FontStyle = enum { normal, bold, italic, underline, undercurl, strikethrough }; pub const Style = struct { fg: ?Color = null, bg: ?Color = null, fs: ?FontStyle = null }; -pub const Color = struct { color: u24, alpha: u8 = 0xFF }; +pub const Color = struct { + color: u24, + alpha: u8 = 0xFF, + + pub fn jsonStringify(self: @This(), writer: anytype) !void { + try writer.beginObject(); + try writer.objectField("color"); + try writer.print("\"#{X:0>6}\"", .{self.color}); + try writer.objectField("alpha"); + try writer.print("{d}", .{self.alpha}); + try writer.endObject(); + } + + pub fn jsonParse(_: std.mem.Allocator, source: anytype, _: std.json.ParseOptions) !@This() { + var color: Color = .{ .color = 0 }; + if (try source.next() != .object_begin) return error.UnexpectedToken; + var key = try source.next(); + while (key != .object_end) : (key = try source.next()) { + if (key != .string) return error.UnexpectedToken; + if (std.mem.eql(u8, key.string, "color")) { + const value = try source.next(); + if (value != .string) return error.UnexpectedToken; + if (value.string.len != 7 or value.string[0] != '#') return error.InvalidNumber; + color.color = try std.fmt.parseInt(u24, value.string[1..], 16); + } else if (std.mem.eql(u8, key.string, "alpha")) { + const value = try source.next(); + if (value != .number) return error.UnexpectedToken; + color.alpha = try std.fmt.parseInt(u8, value.number, 10); + } + } + return color; + } +}; pub const Token = struct { id: usize, style: Style }; pub const Tokens = []const Token; + +const std = @import("std");