sloane.sh/lib/sloane_sh/layouts/helpers.ex

68 lines
1.7 KiB
Elixir
Raw Normal View History

2024-02-24 13:40:20 -05:00
defmodule SloaneSH.Layouts.Helpers do
2024-02-24 21:11:19 -05:00
require Logger
2024-02-24 13:40:20 -05:00
alias SloaneSH.Context
2024-02-24 21:11:19 -05:00
alias SloaneSH.OutputDirs
2024-02-24 13:40:20 -05:00
def cx(classes) do
classes
|> Enum.map(fn
{_, _} = t -> t
c -> {c, true}
end)
|> Enum.filter(fn {_, v} -> !!v end)
|> Enum.map_join(" ", fn {class, _} -> class end)
end
def sorted_post_attrs(%Context{} = ctx) do
2024-03-09 09:38:18 -05:00
{drafts, others} =
ctx.posts
|> Enum.map(& &1.attrs)
|> Enum.split_with(&is_nil(&1[:date]))
others = Enum.sort_by(others, & &1[:date], {:desc, Date})
2024-02-24 13:53:53 -05:00
2024-03-09 09:38:18 -05:00
drafts ++ others
2024-02-24 13:53:53 -05:00
end
2024-02-24 21:11:19 -05:00
2024-03-09 09:38:18 -05:00
def fmt_date(nil), do: "Draft"
def fmt_date(date), do: Timex.format!(date, "{Mfull} {D}, {YYYY}")
2024-02-24 21:11:19 -05:00
def picture(ctx, src, alt \\ "", class \\ "") do
2024-02-24 21:48:47 -05:00
image =
Enum.find(ctx.images, fn i ->
output = OutputDirs.image(ctx.config, i.src)
src == OutputDirs.to_permalink(ctx.config, output)
end)
2024-02-24 21:11:19 -05:00
if is_nil(image) do
Logger.warning("Could not find #{inspect(src)} to make picture element")
~s|<img src="#{src}" alt="#{alt}" class="#{class}">|
else
2024-02-24 21:48:47 -05:00
[{_, src} | srcsets] =
[
{"image/jpg", ".jpg"},
{"image/webp", ".webp"},
{"image/png", ".png"}
]
2024-02-24 21:11:19 -05:00
|> Enum.map(fn {type, ext} ->
{type, OutputDirs.replace_ext(src, ext)}
end)
2024-02-24 21:48:47 -05:00
EEx.eval_string(
~S"""
<picture class="<%= class %>">
<%= for {type, srcset} <- srcsets do %>
<source srcset="<%= srcset %>" type="<%= type %>" />
<% end %>
<img src="<%= src %>" alt="<%= alt %>" />
</picture>
""",
src: src,
srcsets: srcsets,
alt: alt,
class: class
)
2024-02-24 21:11:19 -05:00
end
end
2024-02-24 13:40:20 -05:00
end