aboutsummaryrefslogtreecommitdiff
path: root/src/title.zig
blob: 352460f30846b72a2114e886833cc345e52a0690 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const std = @import("std");
const Allocator = std.mem.Allocator;
const Lexed = @import("lexer/Lexed.zig");
const Lexer = @import("lexer/Lexer.zig");
const Element = @import("dom/Element.zig");
const paragraph = @import("paragraph.zig");
const testing = @import("testing.zig");
const doTest = testing.do;
const doTestError = testing.doError;

pub const Error = error{InvalidTitleContent} || paragraph.Error || Lexer.Error;

pub fn parse(alloc: Allocator, l: *Lexer) Error!Element {
    var v = (try l.next(alloc)).?;
    defer v.deinit();
    var el = try Element.init(alloc, .content, switch (v.content.items.len) {
        1 => "h1",
        2 => "h2",
        3 => "h3",
        4 => "h4",
        5 => "h5",
        6 => "h6",
        else => unreachable,
    });
    errdefer el.deinit();
    try el.appendContent(paragraph.parseLine(alloc, l) catch |err| switch (err) {
        paragraph.Error.IllegalPlacement => return Error.InvalidTitleContent,
        else => return err,
    });
    var next = (try l.next(alloc)) orelse return el;
    defer next.deinit();
    if (!next.kind.isDelimiter()) return Error.InvalidTitleContent;
    return el;
}

test "parse title" {
    var arena = std.heap.DebugAllocator(.{}).init;
    defer if (arena.deinit() == .leak) std.debug.print("leaking!\n", .{});
    const alloc = arena.allocator();

    try doTest(parse, alloc, "# hey", "<h1>hey</h1>");
    try doTest(parse, alloc, "## hey", "<h2>hey</h2>");
    try doTest(parse, alloc, "### hey", "<h3>hey</h3>");

    try doTest(parse, alloc, "# hello *world*", "<h1>hello <b>world</b></h1>");

    try doTestError(parse, alloc, "# aa :::", Error.InvalidTitleContent);
}