defmodule Mix.Tasks.Heroicons.Generate do
@moduledoc """
Generate Heroicons components.
1. Clone heroicons project.
$ git clone https://github.com/tailwindlabs/heroicons.git
2. Run the task.
$ mix heroicons.generate
"""
use Mix.Task
@shortdoc "Convert source SVG files into HEEX components. Run `git clone https://github.com/tailwindlabs/heroicons.git` first."
def run(_) do
Enum.each(["outline", "solid"], &loop_directory/1)
Mix.Task.run("format")
end
defp loop_directory(folder) do
src_path = "./heroicons/optimized/#{folder}/"
namespace = "Heroicons.#{String.capitalize(folder)}"
file_content = """
defmodule Icons.#{namespace} do
@moduledoc \"\"\"
Icon name can be the function or passed in as an atom.
### Examples
\"\"\"
use Phoenix.Component
def render(assigns) do
apply(__MODULE__, assigns.icon, [assigns])
end
"""
functions_content =
src_path
|> File.ls!()
|> Enum.filter(&(Path.extname(&1) == ".svg"))
|> Enum.map_join("\n\n", &create_component(src_path, &1))
file_content =
file_content <>
functions_content <>
"""
end
"""
dest_path = "./lib/icons/heroicons/#{folder}.ex"
unless File.exists?(dest_path) do
File.mkdir_p("./lib/icons/heroicons")
end
File.write!(dest_path, file_content)
end
defp create_component(src_path, filename) do
svg_content =
File.read!(Path.join(src_path, filename))
|> String.trim()
|> String.replace(~r/