Skip to main content

src/spruce@group.erl

-module(spruce@group).
-compile([no_auto_import, nowarn_unused_vars, nowarn_unused_function, nowarn_nomatch, inline]).
-define(FILEPATH, "src/spruce/group.gleam").
-export([render_title/2, group/3, indent/2]).

-if(?OTP_RELEASE >= 27).
-define(MODULEDOC(Str), -moduledoc(Str)).
-define(DOC(Str), -doc(Str)).
-else.
-define(MODULEDOC(Str), -compile([])).
-define(DOC(Str), -compile([])).
-endif.

?MODULEDOC(" Depth-in-context grouped output helpers.\n").

-file("src/spruce/group.gleam", 30).
-spec title_line(spruce:spruce(), binary()) -> binary().
title_line(Sp, Title) ->
    case spruce:supports_color(Sp) of
        false ->
            <<<<(<<"▸"/utf8>>)/binary, " "/utf8>>/binary, Title/binary>>;

        true ->
            <<<<(spruce@style:render(
                        Sp,
                        spruce@palette:hash(Sp, Title),
                        <<"▸"/utf8>>
                    ))/binary,
                    " "/utf8>>/binary,
                (spruce@style:render(
                    Sp,
                    begin
                        _pipe = spruce@style:new(),
                        spruce@style:bold(_pipe)
                    end,
                    Title
                ))/binary>>
    end.

-file("src/spruce/group.gleam", 26).
?DOC(
    " Render a group title line (indent prefix + styled marker + title), the same\n"
    " line that `group` prints. Exposed so buffered output (`spruce/output`) can\n"
    " compose group titles without duplicating the styling.\n"
).
-spec render_title(spruce:spruce(), binary()) -> binary().
render_title(Sp, Title) ->
    <<(spruce@internal@layout:indent_prefix(Sp))/binary,
        (title_line(Sp, Title))/binary>>.

-file("src/spruce/group.gleam", 18).
?DOC(
    " Print a group title, then run `body` with a context indented one level deeper.\n"
    "\n"
    " This is the eager, streaming form of grouping: the title prints immediately\n"
    " and `body` runs right away, so its output appears as work happens and it may\n"
    " perform IO and return any value. For deferred, pipe-composable grouping that\n"
    " buffers output instead, see `spruce/output.group`.\n"
).
-spec group(spruce:spruce(), binary(), fun((spruce:spruce()) -> IOB)) -> IOB.
group(Sp, Title, Body) ->
    gleam_stdlib:println(render_title(Sp, Title)),
    Body(spruce:indented(Sp)).

-file("src/spruce/group.gleam", 41).
?DOC(" Prefix every line in `text` with two spaces for each indent level.\n").
-spec indent(binary(), integer()) -> binary().
indent(Text, Level) ->
    Prefix = gleam@string:repeat(<<"  "/utf8>>, Level),
    _pipe = Text,
    _pipe@1 = gleam@string:split(_pipe, <<"\n"/utf8>>),
    _pipe@2 = gleam@list:map(
        _pipe@1,
        fun(Line) -> <<Prefix/binary, Line/binary>> end
    ),
    gleam@string:join(_pipe@2, <<"\n"/utf8>>).