Skip to content

Instantly share code, notes, and snippets.

@dhruva81
Forked from Z3d0X/CopyToClipboardAction.php
Created November 13, 2023 18:31
Show Gist options
  • Save dhruva81/812480487d14030dbc985dce833c6c0e to your computer and use it in GitHub Desktop.
Save dhruva81/812480487d14030dbc985dce833c6c0e to your computer and use it in GitHub Desktop.
Filament CopyToClipboardAction
<?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);
}
}
@nikspyratos
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment