diff options
| author | Anhgelus Morhtuuzh <william@herges.fr> | 2026-04-26 21:38:06 +0200 |
|---|---|---|
| committer | Anhgelus Morhtuuzh <william@herges.fr> | 2026-04-26 21:38:06 +0200 |
| commit | dca42e27fe9c7d28c72bb6cb8e5cc4ec481572e8 (patch) | |
| tree | 5492f9c4b46b48e58d8002fd36deebd13c059291 /src/eval/Image.zig | |
| parent | b0902c05ffc84d282e10a0179e041948d49fabf8 (diff) | |
feat(): support image
Diffstat (limited to 'src/eval/Image.zig')
| -rw-r--r-- | src/eval/Image.zig | 68 |
1 files changed, 68 insertions, 0 deletions
diff --git a/src/eval/Image.zig b/src/eval/Image.zig new file mode 100644 index 0000000..771c8ee --- /dev/null +++ b/src/eval/Image.zig @@ -0,0 +1,68 @@ +const std = @import("std"); +const Allocator = std.mem.Allocator; +const HTML = @import("html/Element.zig"); +const Element = @import("Element.zig"); + +const Self = @This(); + +src: []const u8, +alt: ?[]const u8 = null, +source: ?Element = null, + +pub fn init(alloc: Allocator, src: []const u8) !*Self { + const v = try alloc.create(Self); + v.* = .{ + .src = src, + }; + return v; +} + +pub fn element(self: *Self) Element { + return .{ .ptr = self, .vtable = .{ .deinit = destroy, .html = html } }; +} + +pub fn deinit(self: *Self, alloc: Allocator) void { + destroy(self, alloc); +} + +fn destroy(context: *anyopaque, alloc: Allocator) void { + const self: *Self = @ptrCast(@alignCast(context)); + if (self.source) |it| it.deinit(alloc); + alloc.destroy(self); +} + +fn html(context: *anyopaque, alloc: Allocator) HTML.Error!HTML { + const self: *Self = @ptrCast(@alignCast(context)); + + var img = try HTML.init(alloc, .void, "img"); + errdefer img.deinit(); + try img.setAttribute("src", self.src); + if (self.alt) |it| try img.setAttribute("alt", it); + var el = try HTML.init(alloc, .content, "figure"); + errdefer el.deinit(); + try el.appendContent(img); + + const source = self.source orelse return el; + var caption = try HTML.init(alloc, .content, "figcaption"); + errdefer caption.deinit(); + try caption.content.append(alloc, try source.html(alloc)); + try el.appendContent(caption); + return el; +} + +test "html" { + const alloc = std.testing.allocator; + const expect = std.testing.expect; + const eql = std.mem.eql; + + var img = try init(alloc, "foo"); + defer img.deinit(alloc); + const h = try img.element().renderHTML(alloc); + defer alloc.free(h); + try expect(eql(u8, h, "<figure><img src=\"foo\"></figure>")); + + img.alt = "bar"; + const h2 = try img.element().renderHTML(alloc); + defer alloc.free(h2); + try expect(eql(u8, h2, "<figure><img src=\"foo\" alt=\"bar\"></figure>")); +} |
