Skip to content

Commit

Permalink
Add ability to provide own defer hash
Browse files Browse the repository at this point in the history
- Ideal when you want to reuse deferred icons in your React/Vue components
- Related PR discussion blade-ui-kit#200
  • Loading branch information
pionl committed Sep 22, 2022
1 parent 26278e4 commit 90f220f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 3 deletions.
9 changes: 6 additions & 3 deletions src/Svg.php
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,17 @@ public function toHtml(): string
);
}

protected function deferContent($contents, $defer = false)
/**
* @param string|bool $defer
*/
protected function deferContent(string $contents, $defer = false): string
{
if (! $defer) {
if ($defer === false) {
return $contents;
}

$svgContent = strip_tags($contents, ['circle', 'ellipse', 'line', 'path', 'polygon', 'polyline', 'rect', 'g']);
$hash = 'icon-'.md5($svgContent);
$hash = 'icon-'.(is_string($defer) ? $defer : md5($svgContent));
$contents = str_replace($svgContent, strtr('<use href=":href"></use>', [':href' => '#'.$hash]), $contents);
$contents .= <<<BLADE
Expand Down
35 changes: 35 additions & 0 deletions tests/SvgTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,23 @@ public function it_can_compile_to_defered_html()
@endonce', $svgHtml);
}

/** @test */
public function it_can_compile_to_defered_html_custom_defer()
{
$svgPath = '<path d="M14 5l7 7m0 0l-7 7m7-7H3"></path>';
$svg = new Svg('heroicon-o-arrow-right', '<svg>'.$svgPath.'</svg>', ['defer' => 'my-custom-hash']);

$svgHtml = $svg->toHtml();
$this->assertEquals('<svg defer="my-custom-hash"><use href="#icon-my-custom-hash"></use></svg>
@once("icon-my-custom-hash")
@push("bladeicons")
<g id="icon-my-custom-hash">
<path d="M14 5l7 7m0 0l-7 7m7-7H3"></path>
</g>
@endpush
@endonce', $svgHtml);
}

/** @test */
public function it_can_compile_to_defered_html_with_group()
{
Expand All @@ -60,6 +77,24 @@ public function it_can_compile_to_defered_html_with_group()
@endonce', $svgHtml);
}

/** @test */
public function it_can_compile_to_defered_html_with_group_custom_defer()
{
$svgPath = '<g id="test" transform="translate(1 1)"><path d="M14 5l7 7m0 0l-7 7m7-7H3"></path></g>';
$svg = new Svg('heroicon-o-arrow-right', '<svg>'.$svgPath.'</svg>', ['defer' => 'my-custom-hash']);

$svgHtml = $svg->toHtml();

$this->assertEquals('<svg defer="my-custom-hash"><use href="#icon-my-custom-hash"></use></svg>
@once("icon-my-custom-hash")
@push("bladeicons")
<g id="icon-my-custom-hash">
<g id="test" transform="translate(1 1)"><path d="M14 5l7 7m0 0l-7 7m7-7H3"></path></g>
</g>
@endpush
@endonce', $svgHtml);
}

/** @test */
public function it_can_compile_to_defered_html_with_group_and_whitespace()
{
Expand Down

0 comments on commit 90f220f

Please sign in to comment.