Skip to content

Commit

Permalink
feat: text alignment (#16)
Browse files Browse the repository at this point in the history
* enhancement(formatting): provide text alignment for table cells

- Add `alignment` parameter to `cell` function to control text alignment to be left, right, or center.

* enhancement(formatting): provide cell-level text alignment for tables

Add `alignment` field to `format_opts` type to configure alignment passed to formatter code.

* enhancement(formatting): provide cell-level text alignment for tables

For `:center` alignment, add back possible lost space due to integer division.
  • Loading branch information
cowile authored Aug 31, 2024
1 parent 9e098ea commit 8fb3568
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
30 changes: 25 additions & 5 deletions lib/formatter.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,8 +37,13 @@ defmodule Scribe.Formatter.Line do

cell_value =
case opts[:colorize] do
false -> value |> cell(width)
_ -> value |> cell(width) |> colorize(style.color(value))
false ->
value |> cell(width, opts[:alignment])

_ ->
value
|> cell(width, opts[:alignment])
|> colorize(style.color(value))
end

acc <> cell_value <> b.right_edge
Expand All @@ -47,10 +52,25 @@ defmodule Scribe.Formatter.Line do
left_edge <> line <> "\n"
end

def cell(x, width) do
def cell(x, width, alignment \\ :left) do
len = min(String.length(" #{inspect(x)} "), width)
padding = String.duplicate(" ", width - len)
truncate(" #{inspect(x)}#{padding}", width - 2) <> " "

case alignment do
:center ->
padding = String.duplicate(" ", div(width - len, 2))
remaining = String.duplicate(" ", rem(width - len, 2))

truncate(" #{padding}#{inspect(x)}#{padding}#{remaining}", width - 2) <>
" "

:right ->
padding = String.duplicate(" ", width - len)
truncate(" #{padding}#{inspect(x)}", width - 2) <> " "

_ ->
padding = String.duplicate(" ", width - len)
truncate(" #{inspect(x)}#{padding}", width - 2) <> " "
end
end

def cell_value(x, padding, max_width) when padding >= 0 do
Expand Down
2 changes: 2 additions & 0 deletions lib/scribe.ex
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,15 @@ defmodule Scribe do
@typedoc ~S"""
Options for configuring table output.
- `:alignment` - Define text alignment in cells. Defaults to `:left`.
- `:colorize` - When `false`, disables colored output. Defaults to `true`
- `:data` - Defines table headers
- `:device` - Where to print (defaults to STDOUT)
- `:style` - Style callback module. Defaults to `Scribe.Style.Default`
- `:width` - Defines table width. Defaults to `:infinite`
"""
@type format_opts :: [
alignment: atom,
colorize: boolean,
data: [...],
style: module,
Expand Down

0 comments on commit 8fb3568

Please sign in to comment.