Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
camelpunch committed Oct 28, 2024
1 parent c4d47ec commit e689365
Showing 1 changed file with 25 additions and 19 deletions.
44 changes: 25 additions & 19 deletions lib/mudbrick/text_block.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,30 +37,36 @@ defmodule Mudbrick.TextBlock do
end

def write(tb, text, opts \\ []) do
line_texts = String.split(text, "\n")

Map.update!(tb, :lines, fn
[] ->
for text <- String.split(text, "\n"), reduce: [] do
acc ->
[Line.wrap(text, opts) | acc]
end
add_texts([], line_texts, opts)

[%Line{} = previous_line | existing_lines] ->
[first_new_line_text | new_line_texts] = String.split(text, "\n")
existing_lines ->
case line_texts do
["" | new_line_texts] ->
existing_lines
|> add_texts(new_line_texts, opts)

new_previous_line =
if first_new_line_text == "" do
previous_line
else
Map.update!(previous_line, :parts, fn
parts ->
[Part.wrap(first_new_line_text, opts) | parts]
end)
end

for text <- new_line_texts, reduce: [new_previous_line | existing_lines] do
acc ->
[Line.wrap(text, opts) | acc]
[first_new_line_text | new_line_texts] ->
existing_lines
|> update_previous_line(first_new_line_text, opts)
|> add_texts(new_line_texts, opts)
end
end)
end

defp update_previous_line([previous_line | existing_lines], first_new_line_text, opts) do
[
Map.update!(previous_line, :parts, &[Part.wrap(first_new_line_text, opts) | &1])
| existing_lines
]
end

defp add_texts(existing_lines, new_line_texts, opts) do
for text <- new_line_texts, reduce: existing_lines do
acc -> [Line.wrap(text, opts) | acc]
end
end
end

0 comments on commit e689365

Please sign in to comment.