Skip to content
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

UX-Icon - Allow to reuse same icon in one request #100

Merged
merged 1 commit into from
May 4, 2024
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
54 changes: 54 additions & 0 deletions src/Icon/IconAlreadyUsedRegistry.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace App\Icon;

use Symfony\Component\DependencyInjection\Attribute\AsDecorator;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\UX\Icons\Icon;
use Symfony\UX\Icons\IconRegistryInterface;

/**
* This class is a decorator for the IconRegistryInterface, that allow to render icon once
* and reuse it on the same page thanks to <use xlink:href="#icon-id"/> SVG tag.
*
* Check issue https://github.com/symfony/ux/issues/1800 for follow symfony integration
* and maybe one day, remove this one
*/
#[AsDecorator('.ux_icons.icon_registry')]
final class IconAlreadyUsedRegistry implements IconRegistryInterface
{
/**
* @var array<string, string>
*/
private array $alreadyUsed = [];

public function __construct(
private RequestStack $requestStack,
private IconRegistryInterface $decorated,
) {}

public function get(string $name): Icon
{
$icon = $this->decorated->get($name);

$id = $icon::nameToId($name);
// Generate an unique Id for each icon by Request
// Needed as static-site does not restart kernel on each request,
// and icon are considered as already used on new pages
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
return $icon;
}
$id = md5(sprintf('%s-%s', $id, spl_object_id($request)));
if (!\array_key_exists($id, $this->alreadyUsed)) {
$this->alreadyUsed[$id] = $id;

return $icon->withAttributes(['id' => $id]);
}

// Return a reusable icon, take only viewBox attribute to avoid rendering issues
return new Icon('<use xlink:href="#' . $id . '"/>', [$icon->getAttributes()['viewBox']]);
}
}
4 changes: 3 additions & 1 deletion templates/_partials/social.html.twig
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
title="{{ type|capitalize }}"
target="_blank"
rel="nofollow,noopener"
class="text-gray-600 hover:text-black"
>
{{ ux_icon('fa6-brands:' ~ type, {'class': 'icon-inline text-gray-600 hover:text-black'}) }}
{{ ux_icon('fa6-brands:' ~ type, {'class': 'icon-inline'}) }}
</a>
{% endfor %}

Loading