-
-
Save dhruva81/812480487d14030dbc985dce833c6c0e to your computer and use it in GitHub Desktop.
Filament CopyToClipboardAction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Filament\Pages\Actions; | |
use Closure; | |
use Filament\Pages\Actions\Action as BaseAction; | |
use Illuminate\Support\HtmlString; | |
class CopyToClipboardAction extends BaseAction | |
{ | |
protected string|Closure|null $copyText = null; | |
public static function getDefaultName(): ?string | |
{ | |
return 'copy-to-clipboard'; | |
} | |
protected function setUp(): void | |
{ | |
parent::setUp(); | |
$this->extraAttributes(fn () => [ | |
'x-on:click' => new HtmlString(<<<JS | |
() => { | |
const copyText = '{$this->getCopyText()}'; | |
const copyFailNotification = new Notification() | |
.title('Copy Failed!') | |
.danger(); | |
if (!window.navigator.clipboard || !copyText) { | |
copyFailNotification.send(); | |
return; | |
} | |
window.navigator.clipboard.writeText(copyText) | |
.then(() => { | |
new Notification() | |
.title('Copied to Clipboard!') | |
.success() | |
.send(); | |
}).catch(() => { | |
copyFailNotification.send(); | |
}); | |
} | |
JS), | |
]); | |
} | |
public function copyText(string|Closure|null $copyText = null): static | |
{ | |
$this->copyText = $copyText; | |
return $this; | |
} | |
public function getCopyText(): string|null | |
{ | |
return $this->evaluate($this->copyText); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Is this using the premium Alpine UI components? I get errors for the
Notification
calls about invalid Alpine expressions. Removing those calls (using Filament notifications instead) works.