Skip to content

Instantly share code, notes, and snippets.

@colindensem
Created November 12, 2024 11:06
Show Gist options
  • Save colindensem/6b8b0d10ac48b0a10d8180ba83c53613 to your computer and use it in GitHub Desktop.
Save colindensem/6b8b0d10ac48b0a10d8180ba83c53613 to your computer and use it in GitHub Desktop.
Create svg functions in elixir from directory of svg icons
defmodule GenerateSVGModule do
@moduledoc """
Script to generate an Elixir module containing functions for each SVG icon.
Reads a directory of custom svg icons and turns them into code.
Done so that various aspects can be altered at use, eg stroke, fill
Creates a new module called `SvgIcons`
"""
@icon_path "priv/static/icons"
@output_file "lib/web_web/components/srt_ui/svg_icons.ex"
def generate do
functions_code =
@icon_path
|> File.ls!()
|> Enum.sort()
|> Enum.map(&generate_function_code/1)
|> Enum.join("\n\n")
module_code = """
defmodule AppWeb.SVGIcons do
@moduledoc \"\"\"
This module contains functions for rendering SVG icons.
\"\"\"
#{functions_code}
end
"""
File.write!(@output_file, module_code)
IO.puts("Module generated successfully at #{@output_file}")
end
defp generate_function_code(file_name) do
icon_name = file_name |> Path.rootname() |> String.replace("-", "_") |> String.to_atom()
svg_content = File.read!(Path.join([@icon_path, file_name])) |> String.trim()
"""
@doc \"\"\"
Renders the `#{icon_name}` icon.
You may pass arbitary HTML attributes to the applied svg tag, e.g. `class`
## Examples
```heex
Icons.#{icon_name} />
Icons.#{icon_name} class="w-4 h-4" />
```
\"\"\"
attr :rest, :global,
include: ~w(fill stroke stroke-width),
doc: "the arbitary HTML attributes for the SVG container"
def #{icon_name}() do
~S|#{svg_content}|
end
"""
end
end

Copyright 2024

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment