swarmicons

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 1, 2026 License: MIT Imports: 17 Imported by: 0

README

Go Swarm Icons logo

Go Swarm Icons

Documentation Go Reference CI Go Version

A Go library for working with SVG icons. It pulls icons from local directories, Iconify JSON collections, or the Iconify HTTP API, and gives you a fluent API for attribute merging, transforms, accessibility, and sanitization.

Read the documentation

Why

If you're building a Go web app, static site generator, or CLI tool that needs icons, your current options boil down to shelling out to Node.js, copy-pasting raw SVG strings, or managing icon files by hand. None of that gives you a proper API for tapping into the 200,000+ icons in the Iconify ecosystem.

This library lets you call Get("prefix:name") to resolve an icon from any source (embedded collections, JSON files on disk, or the Iconify HTTP API) and get back an immutable *Icon you can transform, style, and render to HTML. No JavaScript runtime, no build step, no template hacks.

Features

  • Multiple icon sources. Load from SVG files on disk, Iconify JSON collections, or the Iconify HTTP API. Chain providers with first-match-wins fallback.
  • Embedded Lucide set. ~1,500 Lucide icons compiled into the binary via go:embed. Zero I/O, zero network.
  • 200+ icon sets. Download any Iconify set (Font Awesome, Tabler, Material Design, Heroicons, etc.) via the CLI tool or fetch on demand from the API.
  • Fluent API. Immutable *Icon values with chainable Size(), Rotate(), Flip(), Opacity(), Fill(), Title(), and more. Each call returns a new icon.
  • Five-layer attribute merging. Icon's own attrs → global defaults → prefix attrs → suffix attrs → caller attrs. class concatenates; everything else is last-wins.
  • Accessibility. Automatic ARIA injection: aria-hidden="true" for decorative icons, role="img" when a label is present.
  • SVG sanitization. Strips <script>, <foreignObject>, event handlers, javascript: URIs, and external references.
  • Goldmark extension. :icon[prefix:name] inline syntax for Markdown.
  • Sprite sheets. Collect symbols during rendering and emit a single hidden <svg> with only the icons actually used on the page.
  • CLI tool. Browse, download, search, and export icon sets from the terminal. No Node.js required.
  • Thread-safe. All providers and the manager are safe for concurrent use.

Install

# Core library (zero external dependencies)
go get github.com/frostybee/go-swarm-icons@latest

# Embedded Lucide icon set (optional)
go get github.com/frostybee/go-swarm-icons/lucide@latest

# Goldmark Markdown extension (optional)
go get github.com/frostybee/go-swarm-icons/goldmark@latest

# CLI tool for downloading and managing icon sets
go install github.com/frostybee/go-swarm-icons/cmd/swarm-icons@latest

Requires Go 1.25+.

Quick start

The fastest way to get icons rendering is with the embedded Lucide set:

import (
    "fmt"
    "log"

    swarmicons "github.com/frostybee/go-swarm-icons"
    "github.com/frostybee/go-swarm-icons/lucide"
)

func main() {
    manager := swarmicons.Default("lucide", lucide.Provider())

    icon, err := manager.Get("home")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(icon.ToHTML())
    // <svg aria-hidden="true" viewBox="0 0 24 24" ...>...</svg>

    // Transform icons with the fluent API
    fmt.Println(icon.Size(32).Rotate(45).Opacity(0.7).ToHTML())
}

Every icon below was rendered by the library (generator in showcase/):

Providers

A provider is any source of SVG icons. Register providers under a prefix (e.g. "lucide", "tabler", "custom") and the manager routes Get("prefix:name") to the right one. When an icon name has no colon, the configured default prefix is used.

DirectoryProvider

Loads .svg files from a directory. With WithRecursive(true), subdirectory names become part of the icon name (outline/home.svg"outline/home"). Symlinks are resolved and path traversal is blocked.

provider, err := swarmicons.NewDirectoryProvider("./icons",
    swarmicons.WithRecursive(true),
)

JsonCollectionProvider

Loads icons from an Iconify JSON collection file. Parsed lazily on first access. Alias chains are resolved up to 10 levels deep.

// From a file on disk
provider, err := swarmicons.NewJsonCollectionProvider("./tabler.json")

// From embedded bytes (via go:embed)
provider := swarmicons.NewJsonCollectionFromBytes(data)

IconifyProvider

Fetches icons on demand from the Iconify HTTP API. Three API hosts are tried in sequence as fallback. Results are cached in memory.

provider := swarmicons.NewIconifyProvider("mdi",
    swarmicons.WithTimeout(5 * time.Second),
)

Note: Has() triggers a network request if the icon isn't cached. All() returns an empty slice since the API has no listing endpoint.

ChainProvider

Combines providers with first-match-wins semantics.

chain := swarmicons.NewChainProvider(directoryProvider, jsonProvider)

Configuration

For anything beyond a single provider, use the config builder:

manager, err := swarmicons.NewConfig().
    AddProvider("lucide", lucide.Provider()).
    AddDirectory("custom", "./icons").
    AddJsonCollection("tabler", "./resources/json/tabler.json").
    AddIconifySet("mdi").
    DefaultPrefix("lucide").
    DefaultAttributes(map[string]string{
        "stroke":       "currentColor",
        "stroke-width": "2",
        "fill":         "none",
    }).
    PrefixAttributes("tabler", map[string]string{
        "stroke-width": "1.5",
    }).
    Alias("house", "lucide:home").
    FallbackIcon("lucide:help-circle").
    IgnoreNotFound().
    Build()
Method Purpose
AddProvider Register any custom provider under a prefix
AddDirectory Create a DirectoryProvider (always recursive)
AddJsonCollection Load a JSON collection file
AddIconifySet Register an Iconify HTTP API provider
AddHybridSet Chain a directory provider with an Iconify fallback
DiscoverJsonSets(dir) Auto-discover *.json files, using filenames as prefixes
DefaultPrefix Prefix for bare icon names (no colon)
DefaultAttributes Global defaults (layer 2)
PrefixAttributes Per-prefix defaults (layer 3)
PrefixSuffix Match icon name suffixes, e.g. -solid or -outline (layer 4)
Alias Map one name to another
FallbackIcon / FallbackIconForPrefix Returned when an icon is not found
IgnoreNotFound Return an empty icon instead of an error

The Default() constructor creates a manager with a single provider and basic ARIA injection but no attribute merging layers. Use NewConfig().Build() when you need the full five-layer merge.

Icon API

Every method returns a new *Icon. The original is never modified.

icon, _ := manager.Get("lucide:home")

icon.Size(32)             // set width and height
icon.Width("1.5em")       // set width, derive height from aspect ratio
icon.Height("2rem")       // set height, derive width from aspect ratio
icon.Rotate(45)           // CSS rotate transform
icon.Flip("h")            // CSS scale transform: "h", "v", or "both"
icon.Opacity(0.7)         // opacity attribute
icon.Fill("red")          // fill attribute
icon.Stroke("blue")       // stroke attribute
icon.StrokeWidth("1.5")   // stroke-width attribute
icon.Title("Home")        // prepend a <title> element
icon.Class("icon", "lg")  // append CSS classes (never replaces)
icon.Attr(map[string]string{"data-tip": "home"}) // merge arbitrary attributes

icon.ToHTML()             // render as <svg ...>...</svg>
icon.Content()            // SVG inner content without the <svg> wrapper
icon.Attributes()         // deep copy of the attribute map
icon.ViewBox()            // parsed viewBox components
icon.IsEmpty()            // true if no inner content

Coloring icons

Most icon sets use currentColor on inner elements, which inherits from the CSS color property. Set color via the style attribute:

icon.Attr(map[string]string{"style": "color: red"}).ToHTML()

.Fill("red") and .Stroke("red") set attributes on the outer <svg> element. If the icon's inner elements override them (common in Iconify sets), use the style approach instead.

CSS transforms

Rotate() and Flip() compose into a single CSS transform declaration. Chaining icon.Rotate(45).Flip("h") produces transform: rotate(45deg) scaleX(-1), not two conflicting declarations.

Width() and Height() preserve CSS units: Width("1.5em") on a 24x24 icon produces width="1.5em" height="1.5em". Pass "auto" to use the viewBox dimensions, or "unset" to remove both attributes.

Attribute merging

Attributes merge across five layers. class is always concatenated; all other attributes use last-wins.

Priority Layer Source
1 (lowest) Icon's own viewBox, width, height from the SVG
2 Global defaults DefaultAttributes()
3 Prefix PrefixAttributes("tabler", ...)
4 Suffix PrefixSuffix("heroicons", "solid", ...)
5 (highest) Caller Attributes passed to Get() or fluent methods

ARIA attributes are injected after merging: aria-hidden="true" and focusable="false" for decorative icons, role="img" when aria-label or aria-labelledby is present.

Goldmark extension

Adds :icon[prefix:name] inline syntax to Goldmark-processed Markdown.

import (
    swarmgoldmark "github.com/frostybee/go-swarm-icons/goldmark"
    "github.com/yuin/goldmark"
)

ext := &swarmgoldmark.Extension{
    Manager:         manager,
    SilentOnMissing: true,
}
md := goldmark.New(goldmark.WithExtensions(ext))

Syntax:

:icon[lucide:home]
:icon[lucide:star size="32" style="color:gold"]
:icon[lucide:settings size="24" rotate="90"]
Click :icon[lucide:home size="16"] to return.

Supported attributes: size, rotate, flip, opacity, title (applied via fluent methods), plus any other attribute passed through to the SVG element. When SilentOnMissing is true, missing icons render as an HTML comment instead of returning an error.

Sprite sheets

The SpriteCollector deduplicates icons during rendering and produces a single hidden SVG sprite sheet containing only the symbols referenced on the page.

collector := swarmicons.NewSpriteCollector()

// During rendering, register each icon
collector.Register("i-lucide-home", iconBody, "0 0 24 24")

// After rendering, generate the sprite sheet
sprite := collector.SpriteSheet(pageHTML)
// Returns <svg aria-hidden="true" ...><symbol id="i-lucide-home" ...>...</symbol></svg>

Internal IDs within each symbol are automatically namespaced to prevent collisions when multiple icons share a sprite sheet.

CLI tool

The swarm-icons CLI manages icon sets without requiring Node.js. It downloads directly from the npm registry and extracts the JSON files.

# Browse all 200+ available Iconify icon sets
swarm-icons json browse
swarm-icons json browse --search material

# Download icon sets
swarm-icons json download tabler heroicons mdi
swarm-icons json download --all    # 23 popular sets
swarm-icons json download --list   # show download status

# Check for updates
swarm-icons json update --dry-run
swarm-icons json update

# Search and list icons
swarm-icons icon list --prefix lucide --iconify
swarm-icons icon search lucide arrow

# Export icons as standalone SVG files
swarm-icons icon export lucide home star settings --dest ./icons
swarm-icons icon export lucide --all --dest ./icons

# Cache management
swarm-icons cache warm --prefix tabler --icons home,star,heart
swarm-icons cache clear

# Generate a starter Go configuration
swarm-icons init

# Generate a JSON manifest from a directory of SVGs
swarm-icons manifest generate --path ./icons

Downloaded sets are saved to ./resources/json/ by default. A swarm-icons.json manifest tracks which sets are installed and their versions, enabling json update to detect newer releases. Running json download with no arguments re-downloads whatever is listed in the manifest.

Load downloaded sets in code:

// Single set
manager, _ := swarmicons.NewConfig().
    AddJsonCollection("tabler", "./resources/json/tabler.json").
    Build()

// Auto-discover all JSON files in a directory
manager, _ := swarmicons.NewConfig().
    DiscoverJsonSets("./resources/json/").
    Build()

The --all flag downloads: bi, bx, carbon, fa6-brands, fa6-regular, fa6-solid, flowbite, fluent, heroicons, icon-park-outline, iconoir, ion, line-md, lucide, mdi, mingcute, octicon, ph, ri, simple-icons, solar, tabler, uil.

Security

All SVG content passes through a sanitization pipeline that strips:

  • XML comments, <title>, <desc>
  • <script> and <foreignObject> elements
  • on* event handler attributes
  • javascript: URIs
  • External <use> and <image> href values

Additional protections: DirectoryProvider resolves symlinks and blocks path traversal. Attribute names are validated against ^[a-zA-Z_:][\w:.\-]*$ and values are HTML-escaped. Iconify API requests are restricted to a fixed allowlist of three hosts. HTTP response bodies are capped (1 MB for API, 100 MB for npm downloads).

Project structure

go-swarm-icons/
├── *.go                  # Core library (zero dependencies)
├── lucide/               # Embedded Lucide icon set (separate module)
├── goldmark/             # Goldmark Markdown extension (separate module)
├── npm/                  # npm registry downloader (used by CLI)
├── cmd/swarm-icons/      # CLI tool (separate module)
├── demo/                 # Demo HTTP server (separate module)
├── showcase/             # README showcase generator (separate module)
├── docs/                 # Documentation website source
├── brand/                # Logo and favicon masters
└── resources/json/       # Downloaded Iconify JSON collections

Each submodule (lucide, goldmark, cmd/swarm-icons, demo) has its own go.mod and can be imported independently.

Documentation

Full documentation lives at frostybee.github.io/go-swarm-icons:

The site is built with Sarde from the docs/ directory.

Contributing

Contributions are welcome. To get started:

git clone https://github.com/frostybee/go-swarm-icons.git
cd go-swarm-icons

# Run tests across all modules
go test -race ./...
cd lucide && go test -race ./... && cd ..
cd goldmark && go test -race ./... && cd ..
cd cmd/swarm-icons && go test -race ./... && cd ..

# Lint
go vet ./...

The CI runs tests on Ubuntu, Windows, and macOS with Go 1.25, plus staticcheck for linting.

Before submitting a PR:

  • Run go vet ./... and go test -race ./... on all modules.
  • Keep the core library dependency-free (stdlib only).
  • Add tests for new functionality.

License

MIT

Embedded and downloaded icon sets are licensed by their respective authors; see THIRD-PARTY-NOTICE for details, including the Lucide license.

Documentation

Overview

Package swarmicons is a provider-based SVG icon management library.

Load icons from local SVG directories, Iconify JSON collections, or the Iconify HTTP API. Resolve them by prefix:name addressing, apply attribute merging across five precedence layers, and render accessible SVG output.

Quick start with the embedded Lucide icon set:

import (
    swarmicons "github.com/frostybee/go-swarm-icons"
    "github.com/frostybee/go-swarm-icons/lucide"
)

manager := swarmicons.Default("lucide", lucide.Provider())
icon, err := manager.Get("home")
fmt.Println(icon.ToHTML())

For multiple providers, use the Config builder:

manager, err := swarmicons.NewConfig().
    AddProvider("lucide", lucide.Provider()).
    AddDirectory("custom", "./icons").
    AddIconifySet("tabler").
    DefaultPrefix("lucide").
    Build()

Every Icon is immutable. Fluent methods return a new Icon with the requested change applied:

icon.Size(32).Rotate(45).Opacity(0.7).ToHTML()

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrIconNotFound indicates the requested icon name was not found in any provider.
	ErrIconNotFound = errors.New("icon not found")
	// ErrProviderNotFound indicates no provider is registered for the given prefix.
	ErrProviderNotFound = errors.New("no provider registered for prefix")
	// ErrInvalidIconName indicates a malformed icon name (empty or invalid format).
	ErrInvalidIconName = errors.New("invalid icon name")
	// ErrInvalidSVG indicates the SVG content could not be parsed.
	ErrInvalidSVG = errors.New("invalid SVG content")
	// ErrProviderError indicates a provider-level failure such as file I/O or network error.
	ErrProviderError = errors.New("provider error")
)

Sentinel errors returned by the icon manager and providers.

Functions

This section is empty.

Types

type ChainProvider

type ChainProvider struct {
	// contains filtered or unexported fields
}

ChainProvider queries an ordered list of providers and returns the first match.

func NewChainProvider

func NewChainProvider(providers ...Provider) *ChainProvider

NewChainProvider creates a ChainProvider from the given providers, queried in order.

func (*ChainProvider) All

func (c *ChainProvider) All() []string

All returns deduplicated icon names across all providers in the chain.

func (*ChainProvider) Get

func (c *ChainProvider) Get(name string) (*Icon, bool)

Get returns the first icon found for the given name across the provider chain.

func (*ChainProvider) Has

func (c *ChainProvider) Has(name string) bool

Has reports whether any provider in the chain has an icon with the given name.

type Config

type Config struct {
	// contains filtered or unexported fields
}

Config is a fluent builder for constructing an IconManager. Chain the configuration methods and call Build to produce a fully configured IconManager.

func NewConfig

func NewConfig() *Config

NewConfig creates an empty Config ready for method chaining.

func (*Config) AddDirectory

func (c *Config) AddDirectory(prefix, dir string) *Config

AddDirectory registers a DirectoryProvider that loads SVG files from dir under the given prefix.

func (*Config) AddHybridSet

func (c *Config) AddHybridSet(prefix, dir string) *Config

AddHybridSet registers a ChainProvider combining a DirectoryProvider for dir and an IconifyProvider, both under the given prefix. The directory is checked first.

func (*Config) AddIconifySet

func (c *Config) AddIconifySet(prefix string) *Config

AddIconifySet registers an IconifyProvider that fetches icons from the Iconify HTTP API under the given prefix.

func (*Config) AddJsonCollection

func (c *Config) AddJsonCollection(prefix, path string) *Config

AddJsonCollection registers a JsonCollectionProvider loaded from an Iconify JSON file at path under the given prefix.

func (*Config) AddProvider

func (c *Config) AddProvider(prefix string, provider Provider) *Config

AddProvider registers a pre-built provider under the given prefix.

func (*Config) Alias

func (c *Config) Alias(alias, target string) *Config

Alias maps alias to target so that Get(alias) resolves the same icon as Get(target).

func (*Config) Build

func (c *Config) Build() (*IconManager, error)

Build constructs and returns an IconManager from the accumulated configuration. It initializes all registered providers and returns an error if any provider fails to load.

func (*Config) DefaultAttributes

func (c *Config) DefaultAttributes(attrs map[string]string) *Config

DefaultAttributes sets attributes applied globally to every icon at layer 2 (after the icon's own attributes).

func (*Config) DefaultPrefix

func (c *Config) DefaultPrefix(prefix string) *Config

DefaultPrefix sets the prefix used when an icon name has no colon separator.

func (*Config) DiscoverJsonSets

func (c *Config) DiscoverJsonSets(dir string) *Config

DiscoverJsonSets scans dir for *.json files and registers each as a JsonCollectionProvider, using the filename without extension as the prefix.

func (*Config) FallbackIcon

func (c *Config) FallbackIcon(name string) *Config

FallbackIcon sets the global fallback icon name returned when a requested icon is not found.

func (*Config) FallbackIconForPrefix

func (c *Config) FallbackIconForPrefix(prefix, name string) *Config

FallbackIconForPrefix sets a fallback icon name used only when an icon from the given prefix is not found.

func (*Config) IgnoreNotFound

func (c *Config) IgnoreNotFound() *Config

IgnoreNotFound configures the built manager to return an empty Icon instead of an error when a requested icon or its provider cannot be found.

func (*Config) PrefixAttributes

func (c *Config) PrefixAttributes(prefix string, attrs map[string]string) *Config

PrefixAttributes sets attributes applied to all icons from the given prefix at layer 3.

func (*Config) PrefixSuffix

func (c *Config) PrefixSuffix(prefix, suffix string, attrs map[string]string) *Config

PrefixSuffix sets attributes applied at layer 4 to icons under prefix whose name ends with "-suffix". Pass an empty suffix as a catch-all for all icons under the prefix.

type DirectoryOption

type DirectoryOption func(*DirectoryProvider)

DirectoryOption is a functional option for configuring a DirectoryProvider.

func WithExtension

func WithExtension(ext string) DirectoryOption

WithExtension sets the file extension to match when scanning the directory. The default extension is "svg".

func WithRecursive

func WithRecursive(recursive bool) DirectoryOption

WithRecursive sets whether subdirectories are scanned recursively. When enabled, subdirectory names form part of the icon name (e.g., "outline/home").

type DirectoryProvider

type DirectoryProvider struct {
	// contains filtered or unexported fields
}

DirectoryProvider loads SVG icons from a directory on disk. Icons are read lazily on first access and cached in memory.

func NewDirectoryProvider

func NewDirectoryProvider(dir string, opts ...DirectoryOption) (*DirectoryProvider, error)

NewDirectoryProvider creates a DirectoryProvider rooted at the given directory path.

func (*DirectoryProvider) All

func (p *DirectoryProvider) All() []string

All returns the names of all icons found in the provider's directory.

func (*DirectoryProvider) Get

func (p *DirectoryProvider) Get(name string) (*Icon, bool)

Get returns the icon with the given name, loading it from disk on first access.

func (*DirectoryProvider) Has

func (p *DirectoryProvider) Has(name string) bool

Has reports whether an icon with the given name exists in the directory.

func (*DirectoryProvider) Preload

func (p *DirectoryProvider) Preload()

Preload reads all icons from the directory into the in-memory cache.

type Icon

type Icon struct {
	// contains filtered or unexported fields
}

Icon represents a parsed SVG icon with inner content and SVG attributes. Every fluent method returns a new Icon; the original is never modified.

func FromFile

func FromFile(path string) (*Icon, error)

FromFile reads the SVG file at path and returns a parsed Icon.

func FromString

func FromString(svg string) (*Icon, error)

FromString parses an SVG string and returns the resulting Icon.

func New

func New(content string, attrs map[string]string) *Icon

New creates an Icon from raw SVG inner content and an attribute map. The attribute map is deep-copied; the caller's map is not retained.

func (*Icon) Attr

func (ic *Icon) Attr(attrs map[string]string) *Icon

Attr returns a new Icon with the given attributes merged into the existing set. Empty-string values are ignored. Use Class to append CSS classes without overwriting.

func (*Icon) Attributes

func (ic *Icon) Attributes() map[string]string

Attributes returns a deep copy of the icon's SVG attribute map.

func (*Icon) Class

func (ic *Icon) Class(classes ...string) *Icon

Class returns a new Icon with the given CSS classes appended to any existing class attribute.

func (*Icon) Content

func (ic *Icon) Content() string

Content returns the SVG inner content without the outer <svg> element.

func (*Icon) Fill

func (ic *Icon) Fill(fill string) *Icon

Fill returns a new Icon with the fill attribute set to the given value. For icon sets that use currentColor strokes, set color via style="color: X" instead.

func (*Icon) Flip

func (ic *Icon) Flip(direction string) *Icon

Flip returns a new Icon with a CSS scale transform appended to the style attribute. direction accepts "h" (horizontal), "v" (vertical), or "both". Chaining with Rotate produces a single combined transform declaration.

func (*Icon) Height

func (ic *Icon) Height(h string) *Icon

Height returns a new Icon with height set to h and width derived from the viewBox aspect ratio. Supports CSS units ("24", "1.5em", "2rem").

Special values: "auto" resolves to the viewBox height (and sets width to viewBox width). "unset", "none", or "undefined" remove both width and height attributes entirely.

func (*Icon) IsEmpty

func (ic *Icon) IsEmpty() bool

IsEmpty reports whether the icon has no inner content.

func (*Icon) Opacity

func (ic *Icon) Opacity(o float64) *Icon

Opacity returns a new Icon with the opacity attribute set to o.

func (*Icon) Rotate

func (ic *Icon) Rotate(degrees float64) *Icon

Rotate returns a new Icon with a CSS rotate transform appended to the style attribute. Chaining with Flip produces a single combined transform declaration.

func (*Icon) Size

func (ic *Icon) Size(size int) *Icon

Size returns a new Icon with width and height both set to size.

func (*Icon) String

func (ic *Icon) String() string

String implements fmt.Stringer and returns the same value as ToHTML.

func (*Icon) Stroke

func (ic *Icon) Stroke(stroke string) *Icon

Stroke returns a new Icon with the stroke attribute set to the given value.

func (*Icon) StrokeWidth

func (ic *Icon) StrokeWidth(w string) *Icon

StrokeWidth returns a new Icon with the stroke-width attribute set to w.

func (*Icon) Title

func (ic *Icon) Title(title string) *Icon

Title returns a new Icon with a <title> element prepended to the SVG content for screen-reader accessibility.

func (*Icon) ToHTML

func (ic *Icon) ToHTML() string

ToHTML renders the Icon as a complete <svg> element string.

func (*Icon) ViewBox

func (ic *Icon) ViewBox() (minX, minY, w, h int)

ViewBox parses the icon's viewBox attribute and returns its four components. Falls back to width/height attributes if viewBox is absent. Returns 0,0,0,0 when neither is available.

func (*Icon) ViewBoxSize

func (ic *Icon) ViewBoxSize() (w, h int)

ViewBoxSize returns the width and height from the icon's viewBox attribute.

func (*Icon) Width

func (ic *Icon) Width(w string) *Icon

Width returns a new Icon with width set to w and height derived from the viewBox aspect ratio. Supports CSS units ("24", "1.5em", "2rem").

Special values: "auto" resolves to the viewBox width (and sets height to viewBox height). "unset", "none", or "undefined" remove both width and height attributes entirely.

type IconManager

type IconManager struct {
	// contains filtered or unexported fields
}

IconManager is the central registry and resolver for SVG icons. It maps prefixes to providers, resolves aliases, applies attribute rendering, and handles fallback logic. All methods are safe for concurrent use.

func Default

func Default(prefix string, provider Provider) *IconManager

Default creates an IconManager pre-configured with the given provider registered under prefix, which is also set as the default prefix.

func (*IconManager) All

func (m *IconManager) All(prefix string) []string

All returns the names of every icon available in the provider registered under prefix. Returns nil if no provider is registered for that prefix.

func (*IconManager) Get

func (m *IconManager) Get(name string, attrs ...map[string]string) (*Icon, error)

Get resolves the icon named by name (in "prefix:name" or bare "name" format), applies the five-layer attribute merge, and returns the rendered Icon. The optional attrs map provides caller-level attributes at the highest precedence layer.

func (*IconManager) Has

func (m *IconManager) Has(name string) bool

Has reports whether the icon identified by name can be resolved against a registered provider.

func (*IconManager) Register

func (m *IconManager) Register(prefix string, p Provider) *IconManager

Register adds provider p under the given prefix, replacing any existing provider for that prefix.

func (*IconManager) SetAlias

func (m *IconManager) SetAlias(alias, target string)

SetAlias maps alias to target so that Get(alias) resolves the same icon as Get(target).

func (*IconManager) SetDefaultPrefix

func (m *IconManager) SetDefaultPrefix(prefix string)

SetDefaultPrefix sets the prefix applied when Get receives a bare icon name with no colon.

func (*IconManager) SetFallbackIcon

func (m *IconManager) SetFallbackIcon(name string)

SetFallbackIcon sets the global fallback icon name returned when a requested icon is not found.

func (*IconManager) SetFallbackIconForPrefix

func (m *IconManager) SetFallbackIconForPrefix(prefix, name string)

SetFallbackIconForPrefix sets a fallback icon name used only when an icon from the given prefix is not found.

func (*IconManager) SetIgnoreNotFound

func (m *IconManager) SetIgnoreNotFound(ignore bool)

SetIgnoreNotFound controls whether Get silently returns an empty Icon instead of an error when a requested icon or its provider cannot be found.

func (*IconManager) SetRenderer

func (m *IconManager) SetRenderer(r *IconRenderer)

SetRenderer replaces the IconRenderer used for attribute merging and ARIA injection.

type IconRenderer

type IconRenderer struct {
	// contains filtered or unexported fields
}

IconRenderer merges SVG attributes across five precedence layers and injects ARIA attributes for accessibility. Create one with NewIconRenderer and pass it to an IconManager.

func NewIconRenderer

func NewIconRenderer(defaultAttrs map[string]string, prefixAttrs map[string]map[string]string) *IconRenderer

NewIconRenderer creates an IconRenderer with the given global default attributes and per-prefix attribute maps. Either argument may be nil.

func (*IconRenderer) Render

func (r *IconRenderer) Render(icon *Icon, prefix, iconName string, callerAttrs map[string]string) *Icon

Render applies the five-layer attribute merge and ARIA injection to icon and returns a new Icon with the merged attributes.

func (*IconRenderer) SetSuffixAttributes

func (r *IconRenderer) SetSuffixAttributes(prefix, suffix string, attrs map[string]string)

SetSuffixAttributes registers attributes applied to icons under prefix whose name ends with "-suffix" (e.g., suffix "solid" matches "heroicons:arrow-right-solid"). Use an empty suffix as a catch-all for all icons under the prefix.

type IconifyOption

type IconifyOption func(*IconifyProvider)

IconifyOption is a functional option for configuring an IconifyProvider.

func WithHTTPClient

func WithHTTPClient(client *http.Client) IconifyOption

WithHTTPClient sets a custom HTTP client for all API requests made by the provider.

func WithHosts

func WithHosts(hosts []string) IconifyOption

WithHosts overrides the default Iconify API host list used for fallback requests.

func WithTimeout

func WithTimeout(d time.Duration) IconifyOption

WithTimeout sets the HTTP request timeout for the provider's HTTP client.

type IconifyProvider

type IconifyProvider struct {
	// contains filtered or unexported fields
}

IconifyProvider fetches icons from the Iconify HTTP API with fallback across multiple hosts. Results are cached in memory after the first successful fetch.

func NewIconifyProvider

func NewIconifyProvider(prefix string, opts ...IconifyOption) *IconifyProvider

NewIconifyProvider creates an IconifyProvider for the given icon set prefix (e.g., "tabler", "mdi").

func (*IconifyProvider) All

func (p *IconifyProvider) All() []string

All returns an empty slice; the Iconify API provides no icon listing endpoint.

func (*IconifyProvider) Get

func (p *IconifyProvider) Get(name string) (*Icon, bool)

Get fetches the icon from the Iconify API and caches the result for subsequent calls.

func (*IconifyProvider) Has

func (p *IconifyProvider) Has(name string) bool

Has reports whether the icon exists. If the icon is not already cached, this method makes an HTTP request to the Iconify API to fetch it. Use Has sparingly in hot paths or when network access is unavailable.

type JsonCollectionProvider

type JsonCollectionProvider struct {
	// contains filtered or unexported fields
}

JsonCollectionProvider loads icons from an Iconify JSON collection file. The collection is parsed lazily on first access and icons are cached in memory.

func NewJsonCollectionFromBytes

func NewJsonCollectionFromBytes(data []byte) *JsonCollectionProvider

NewJsonCollectionFromBytes creates a JsonCollectionProvider from raw JSON bytes. Use this with go:embed to bundle icon collections in the binary.

func NewJsonCollectionProvider

func NewJsonCollectionProvider(path string) (*JsonCollectionProvider, error)

NewJsonCollectionProvider creates a JsonCollectionProvider by reading the JSON file at path.

func (*JsonCollectionProvider) All

func (p *JsonCollectionProvider) All() []string

All returns the names of all icons and aliases in the collection.

func (*JsonCollectionProvider) Get

func (p *JsonCollectionProvider) Get(name string) (*Icon, bool)

Get returns the icon with the given name, resolving aliases up to 10 levels deep.

func (*JsonCollectionProvider) Has

func (p *JsonCollectionProvider) Has(name string) bool

Has reports whether the icon or alias with the given name exists in the collection.

type Provider

type Provider interface {
	// Get returns the icon with the given name. The boolean is false if not found.
	Get(name string) (*Icon, bool)
	// Has reports whether an icon with the given name exists.
	Has(name string) bool
	// All returns the names of every icon available in this provider.
	All() []string
}

Provider defines the interface for icon sources. Implementations load icons from disk, JSON collections, HTTP APIs, or composite fallback chains.

type SpriteCollector

type SpriteCollector struct {
	// contains filtered or unexported fields
}

SpriteCollector accumulates SVG icon symbols during a render pass and produces a hidden sprite sheet for injection into page HTML. It is thread-safe and designed to be shared across concurrent page renders.

func NewSpriteCollector

func NewSpriteCollector() *SpriteCollector

NewSpriteCollector returns a ready-to-use collector.

func (*SpriteCollector) Register

func (sc *SpriteCollector) Register(id, body, viewBox string)

Register stores a symbol under id. The body's internal SVG id/url/href references are namespaced with the base portion of the id (after stripping any "i-" prefix) to prevent collisions in the combined sprite sheet. First write wins; duplicate registrations are no-ops.

func (*SpriteCollector) Reset

func (sc *SpriteCollector) Reset()

Reset clears all registered symbols.

func (*SpriteCollector) SpriteSheet

func (sc *SpriteCollector) SpriteSheet(pageHTML []byte) []byte

SpriteSheet scans pageHTML for <use href="#i-..."> references, looks up each in the registered symbols, and returns a hidden <svg> containing one <symbol> per unique referenced icon (sorted by ID). Returns nil if no matching references are found.

Directories

Path Synopsis
cmd
swarm-icons module
goldmark module
internal
lucide module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL