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 ¶
- Variables
- type ChainProvider
- type Config
- func (c *Config) AddDirectory(prefix, dir string) *Config
- func (c *Config) AddHybridSet(prefix, dir string) *Config
- func (c *Config) AddIconifySet(prefix string) *Config
- func (c *Config) AddJsonCollection(prefix, path string) *Config
- func (c *Config) AddProvider(prefix string, provider Provider) *Config
- func (c *Config) Alias(alias, target string) *Config
- func (c *Config) Build() (*IconManager, error)
- func (c *Config) DefaultAttributes(attrs map[string]string) *Config
- func (c *Config) DefaultPrefix(prefix string) *Config
- func (c *Config) DiscoverJsonSets(dir string) *Config
- func (c *Config) FallbackIcon(name string) *Config
- func (c *Config) FallbackIconForPrefix(prefix, name string) *Config
- func (c *Config) IgnoreNotFound() *Config
- func (c *Config) PrefixAttributes(prefix string, attrs map[string]string) *Config
- func (c *Config) PrefixSuffix(prefix, suffix string, attrs map[string]string) *Config
- type DirectoryOption
- type DirectoryProvider
- type Icon
- func (ic *Icon) Attr(attrs map[string]string) *Icon
- func (ic *Icon) Attributes() map[string]string
- func (ic *Icon) Class(classes ...string) *Icon
- func (ic *Icon) Content() string
- func (ic *Icon) Fill(fill string) *Icon
- func (ic *Icon) Flip(direction string) *Icon
- func (ic *Icon) Height(h string) *Icon
- func (ic *Icon) IsEmpty() bool
- func (ic *Icon) Opacity(o float64) *Icon
- func (ic *Icon) Rotate(degrees float64) *Icon
- func (ic *Icon) Size(size int) *Icon
- func (ic *Icon) String() string
- func (ic *Icon) Stroke(stroke string) *Icon
- func (ic *Icon) StrokeWidth(w string) *Icon
- func (ic *Icon) Title(title string) *Icon
- func (ic *Icon) ToHTML() string
- func (ic *Icon) ViewBox() (minX, minY, w, h int)
- func (ic *Icon) ViewBoxSize() (w, h int)
- func (ic *Icon) Width(w string) *Icon
- type IconManager
- func (m *IconManager) All(prefix string) []string
- func (m *IconManager) Get(name string, attrs ...map[string]string) (*Icon, error)
- func (m *IconManager) Has(name string) bool
- func (m *IconManager) Register(prefix string, p Provider) *IconManager
- func (m *IconManager) SetAlias(alias, target string)
- func (m *IconManager) SetDefaultPrefix(prefix string)
- func (m *IconManager) SetFallbackIcon(name string)
- func (m *IconManager) SetFallbackIconForPrefix(prefix, name string)
- func (m *IconManager) SetIgnoreNotFound(ignore bool)
- func (m *IconManager) SetRenderer(r *IconRenderer)
- type IconRenderer
- type IconifyOption
- type IconifyProvider
- type JsonCollectionProvider
- type Provider
- type SpriteCollector
Constants ¶
This section is empty.
Variables ¶
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 ¶
AddDirectory registers a DirectoryProvider that loads SVG files from dir under the given prefix.
func (*Config) AddHybridSet ¶
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 ¶
AddIconifySet registers an IconifyProvider that fetches icons from the Iconify HTTP API under the given prefix.
func (*Config) AddJsonCollection ¶
AddJsonCollection registers a JsonCollectionProvider loaded from an Iconify JSON file at path under the given prefix.
func (*Config) AddProvider ¶
AddProvider registers a pre-built provider under the given prefix.
func (*Config) Alias ¶
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 ¶
DefaultAttributes sets attributes applied globally to every icon at layer 2 (after the icon's own attributes).
func (*Config) DefaultPrefix ¶
DefaultPrefix sets the prefix used when an icon name has no colon separator.
func (*Config) DiscoverJsonSets ¶
DiscoverJsonSets scans dir for *.json files and registers each as a JsonCollectionProvider, using the filename without extension as the prefix.
func (*Config) FallbackIcon ¶
FallbackIcon sets the global fallback icon name returned when a requested icon is not found.
func (*Config) FallbackIconForPrefix ¶
FallbackIconForPrefix sets a fallback icon name used only when an icon from the given prefix is not found.
func (*Config) IgnoreNotFound ¶
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 ¶
PrefixAttributes sets attributes applied to all icons from the given prefix at layer 3.
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 FromString ¶
FromString parses an SVG string and returns the resulting Icon.
func New ¶
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 ¶
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 ¶
Attributes returns a deep copy of the icon's SVG attribute map.
func (*Icon) Class ¶
Class returns a new Icon with the given CSS classes appended to any existing class attribute.
func (*Icon) Fill ¶
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 ¶
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 ¶
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) Rotate ¶
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) StrokeWidth ¶
StrokeWidth returns a new Icon with the stroke-width attribute set to w.
func (*Icon) Title ¶
Title returns a new Icon with a <title> element prepended to the SVG content for screen-reader accessibility.
func (*Icon) ViewBox ¶
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 ¶
ViewBoxSize returns the width and height from the icon's viewBox attribute.
func (*Icon) Width ¶
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 ¶
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.