Skip to content

Commit

Permalink
Merge pull request #14033 from iyashpal/3.x
Browse files Browse the repository at this point in the history
Ability to add script data attributes or custom attributes.
  • Loading branch information
danharrin authored Aug 25, 2024
2 parents e231d8e + 7af1fc8 commit 82b76f2
Showing 1 changed file with 40 additions and 2 deletions.
42 changes: 40 additions & 2 deletions packages/support/src/Assets/Js.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,11 @@ class Js extends Asset

protected bool $isModule = false;

/**
* @var array<string, string>
*/
protected array $extraAttributes = [];

protected string | Htmlable | null $html = null;

public function async(bool $condition = true): static
Expand Down Expand Up @@ -87,6 +92,16 @@ public function isModule(): bool
return $this->isModule;
}

/**
* @param array<string, string> $attributes
*/
public function extraAttributes(array $attributes): static
{
$this->extraAttributes = $attributes;

return $this;
}

public function getHtml(): Htmlable
{
$html = $this->html;
Expand All @@ -100,22 +115,45 @@ public function getHtml(): Htmlable
$async = $this->isAsync() ? 'async' : '';
$defer = $this->isDeferred() ? 'defer' : '';
$module = $this->isModule() ? 'type="module"' : '';
$extraAttributesHtml = $this->getExtraAttributesHtml();

$hasSpaMode = FilamentView::hasSpaMode();

$navigateOnce = ($hasSpaMode && $this->isNavigateOnce()) ? 'data-navigate-once' : '';
$navigateTrack = $hasSpaMode ? 'data-navigate-track' : '';

return new HtmlString("
return new HtmlString(
"
<script
src=\"{$html}\"
{$async}
{$defer}
{$module}
{$extraAttributesHtml}
{$navigateOnce}
{$navigateTrack}
></script>
");
",
);
}

/**
* @return array<string, string>
*/
public function getExtraAttributes(): array
{
return $this->extraAttributes;
}

public function getExtraAttributesHtml(): string
{
$attributes = '';

foreach ($this->getExtraAttributes() as $key => $value) {
$attributes .= " {$key}=\"{$value}\"";
}

return $attributes;
}

public function getSrc(): string
Expand Down

0 comments on commit 82b76f2

Please sign in to comment.