Skip to content

[Icons] Configure icon sets: path, alias & icon attributes #2156

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/Icons/config/services.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
use Symfony\UX\Icons\Command\WarmCacheCommand;
use Symfony\UX\Icons\IconCacheWarmer;
use Symfony\UX\Icons\IconRenderer;
use Symfony\UX\Icons\IconRendererInterface;
use Symfony\UX\Icons\Registry\CacheIconRegistry;
use Symfony\UX\Icons\Registry\ChainIconRegistry;
use Symfony\UX\Icons\Registry\LocalSvgIconRegistry;
Expand Down Expand Up @@ -60,7 +61,7 @@
abstract_arg('icon_aliases'),
])

->alias('Symfony\UX\Icons\IconRendererInterface', '.ux_icons.icon_renderer')
->alias(IconRendererInterface::class, '.ux_icons.icon_renderer')

->set('.ux_icons.icon_finder', IconFinder::class)
->args([
Expand Down
69 changes: 61 additions & 8 deletions src/Icons/src/DependencyInjection/UXIconsExtension.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,32 +42,66 @@ public function getConfigTreeBuilder(): TreeBuilder
->variableNode('default_icon_attributes')
->info('Default attributes to add to all icons.')
->defaultValue(['fill' => 'currentColor'])
->example(['class' => 'icon'])
->end()
->arrayNode('icon_sets')
->info('Icon sets configuration.')
->defaultValue([])
->normalizeKeys(false)
->useAttributeAsKey('prefix')
->arrayPrototype()
->info('the icon set prefix (e.g. "acme")')
->children()
->scalarNode('path')
->info("The local icon set directory path.\n(cannot be used with 'alias')")
->example('%kernel.project_dir%/assets/svg/acme')
->end()
->scalarNode('alias')
->info("The remote icon set identifier.\n(cannot be used with 'path')")
->example('simple-icons')
->end()
->arrayNode('icon_attributes')
->info('Override default icon attributes for icons in this set.')
->example(['class' => 'icon icon-acme', 'fill' => 'none'])
->normalizeKeys(false)
->variablePrototype()
->end()
->end()
->end()
->end()
->validate()
->ifTrue(fn (array $v) => isset($v['path']) && isset($v['alias']))
->thenInvalid('You cannot define both "path" and "alias" for an icon set.')
->end()
->end()
->arrayNode('aliases')
->info('Icon aliases (alias => icon name).')
->example(['dots' => 'clarity:ellipsis-horizontal-line'])
->info('Icon aliases (map of alias => full name).')
->example([
'dots' => 'clarity:ellipsis-horizontal-line',
'privacy' => 'bi:cookie',
])
->normalizeKeys(false)
->scalarPrototype()
->cannotBeEmpty()
->end()
->end()
->arrayNode('iconify')
->info('Configuration for the "on demand" icons powered by Iconify.design.')
->info('Configuration for the remote icon service.')
->{interface_exists(HttpClientInterface::class) ? 'canBeDisabled' : 'canBeEnabled'}()
->children()
->booleanNode('on_demand')
->info('Whether to use the "on demand" icons powered by Iconify.design.')
->info('Whether to download icons "on demand".')
->defaultTrue()
->end()
->scalarNode('endpoint')
->info('The endpoint for the Iconify API.')
->info('The endpoint for the Iconify icons API.')
->defaultValue(Iconify::API_ENDPOINT)
->cannotBeEmpty()
->end()
->end()
->end()
->booleanNode('ignore_not_found')
->info('Ignore error when an icon is not found.')
->info("Ignore error when an icon is not found.\nSet to 'true' to fail silently.")
->defaultFalse()
->end()
->end()
Expand All @@ -94,9 +128,25 @@ protected function loadInternal(array $mergedConfig, ContainerBuilder $container
$loader->load('asset_mapper.php');
}

$iconSetAliases = [];
$iconSetAttributes = [];
$iconSetPaths = [];
foreach ($mergedConfig['icon_sets'] as $prefix => $config) {
if (isset($config['icon_attributes'])) {
$iconSetAttributes[$prefix] = $config['icon_attributes'];
}
if (isset($config['alias'])) {
$iconSetAliases[$prefix] = $config['alias'];
}
if (isset($config['path'])) {
$iconSetPaths[$prefix] = $config['path'];
}
}

$container->getDefinition('.ux_icons.local_svg_icon_registry')
->setArguments([
$mergedConfig['icon_dir'],
$iconSetPaths,
])
;

Expand All @@ -107,6 +157,7 @@ protected function loadInternal(array $mergedConfig, ContainerBuilder $container
$container->getDefinition('.ux_icons.icon_renderer')
->setArgument(1, $mergedConfig['default_icon_attributes'])
->setArgument(2, $mergedConfig['aliases'])
->setArgument(3, $iconSetAttributes)
;

$container->getDefinition('.ux_icons.twig_icon_runtime')
Expand All @@ -117,8 +168,10 @@ protected function loadInternal(array $mergedConfig, ContainerBuilder $container
$loader->load('iconify.php');

$container->getDefinition('.ux_icons.iconify')
->setArgument(1, $mergedConfig['iconify']['endpoint'])
;
->setArgument(1, $mergedConfig['iconify']['endpoint']);

$container->getDefinition('.ux_icons.iconify_on_demand_registry')
->setArgument(1, $iconSetAliases);

if (!$mergedConfig['iconify']['on_demand']) {
$container->removeDefinition('.ux_icons.iconify_on_demand_registry');
Expand Down
21 changes: 16 additions & 5 deletions src/Icons/src/IconRenderer.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,16 @@
*/
final class IconRenderer implements IconRendererInterface
{
/**
* @param array<string, mixed> $defaultIconAttributes
* @param array<string, string> $iconAliases
* @param array<string, array<string, mixed>> $iconSetsAttributes
*/
public function __construct(
private readonly IconRegistryInterface $registry,
private readonly array $defaultIconAttributes = [],
private readonly ?array $iconAliases = [],
private readonly array $iconAliases = [],
private readonly array $iconSetsAttributes = [],
) {
}

Expand All @@ -36,11 +42,16 @@ public function __construct(
*/
public function renderIcon(string $name, array $attributes = []): string
{
$name = $this->iconAliases[$name] ?? $name;
$iconName = $this->iconAliases[$name] ?? $name;

$icon = $this->registry->get($name)
->withAttributes($this->defaultIconAttributes)
->withAttributes($attributes);
$icon = $this->registry->get($iconName);

if (0 < (int) $pos = strpos($name, ':')) {
$setAttributes = $this->iconSetsAttributes[substr($name, 0, $pos)] ?? [];
} elseif ($iconName !== $name && 0 < (int) $pos = strpos($iconName, ':')) {
$setAttributes = $this->iconSetsAttributes[substr($iconName, 0, $pos)] ?? [];
}
$icon = $icon->withAttributes([...$this->defaultIconAttributes, ...($setAttributes ?? []), ...$attributes]);

foreach ($this->getPreRenderers() as $preRenderer) {
$icon = $preRenderer($icon);
Expand Down
9 changes: 6 additions & 3 deletions src/Icons/src/Registry/IconifyOnDemandRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,19 @@
*/
final class IconifyOnDemandRegistry implements IconRegistryInterface
{
public function __construct(private Iconify $iconify)
{
public function __construct(
private Iconify $iconify,
private ?array $prefixAliases = [],
) {
}

public function get(string $name): Icon
{
if (2 !== \count($parts = explode(':', $name))) {
throw new IconNotFoundException(\sprintf('The icon name "%s" is not valid.', $name));
}
[$prefix, $icon] = $parts;

return $this->iconify->fetchIcon(...$parts);
return $this->iconify->fetchIcon($this->prefixAliases[$prefix] ?? $prefix, $icon);
}
}
31 changes: 26 additions & 5 deletions src/Icons/src/Registry/LocalSvgIconRegistry.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,38 @@
*/
final class LocalSvgIconRegistry implements IconRegistryInterface
{
public function __construct(private string $iconDir)
{
/**
* @param array<string, string> $iconSetPaths
*/
public function __construct(
private readonly string $iconDir,
private readonly array $iconSetPaths = [],
) {
}

public function get(string $name): Icon
{
if (!file_exists($filename = \sprintf('%s/%s.svg', $this->iconDir, str_replace(':', '/', $name)))) {
throw new IconNotFoundException(\sprintf('The icon "%s" (%s) does not exist.', $name, $filename));
if (str_contains($name, ':')) {
[$prefix, $icon] = explode(':', $name, 2) + ['', ''];
if ('' === $prefix || '' === $icon) {
throw new IconNotFoundException(\sprintf('The icon name "%s" is not valid.', $name));
}

if ($prefixPath = $this->iconSetPaths[$prefix] ?? null) {
if (!file_exists($filename = $prefixPath.'/'.str_replace(':', '/', $icon).'.svg')) {
throw new IconNotFoundException(\sprintf('The icon "%s" (%s) does not exist.', $name, $filename));
}

return Icon::fromFile($filename);
}
}

$filepath = str_replace(':', '/', $name).'.svg';
if (file_exists($filename = $this->iconDir.'/'.$filepath)) {
return Icon::fromFile($filename);
}

return Icon::fromFile($filename);
throw new IconNotFoundException(\sprintf('The icon "%s" (%s) does not exist.', $name, $filename));
}

public function has(string $name): bool
Expand Down
10 changes: 9 additions & 1 deletion src/Icons/tests/Fixtures/TestKernel.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ protected function configureContainer(ContainerConfigurator $container): void
]);

$container->extension('twig', [
'default_path' => __DIR__ . '/templates',
'default_path' => __DIR__.'/templates',
]);

$container->extension('twig_component', [
Expand All @@ -60,6 +60,14 @@ protected function configureContainer(ContainerConfigurator $container): void

$container->extension('ux_icons', [
'icon_dir' => '%kernel.project_dir%/tests/Fixtures/icons',
'icon_sets' => [
'fla' => [
'path' => '%kernel.project_dir%/tests/Fixtures/images/flags',
],
'lu' => [
'alias' => 'lucide',
],
],
]);

$container->services()->set('logger', NullLogger::class);
Expand Down
3 changes: 3 additions & 0 deletions src/Icons/tests/Fixtures/icons/a/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/Icons/tests/Fixtures/images/a/b/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/Icons/tests/Fixtures/images/a/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/Icons/tests/Fixtures/images/ab/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
3 changes: 3 additions & 0 deletions src/Icons/tests/Fixtures/images/icon.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading