Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Clipboard Laravel Package

moox/clipboard

Moox Clipboard adds Filament form fields with a built-in “copy to clipboard” action, making it easy for users to copy values like tokens, IDs, or URLs from your admin panels. Install via Composer and run moox:install to get started.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require moox/clipboard
    php artisan moox:install
    
    • The moox:install command publishes the package's assets (JS, CSS) and config file to your project.
  2. First Use Case:

    • Add the Clipboard action to a Filament field (e.g., TextInput, Textarea, or MarkdownEditor):
      use Moox\Clipboard\Actions\Clipboard;
      
      TextInput::make('api_key')
          ->extraAttributes(['class' => 'w-full'])
          ->afterStateUpdated(
              Clipboard::make()
                  ->label('Copy to Clipboard')
                  ->icon('heroicon-o-clipboard-document-check')
          ),
      
    • The action will automatically appear as a button next to the field.
  3. Where to Look First:

    • User Guide for field-specific configurations.
    • Get Started for basic usage examples.
    • Published config file (config/moox-clipboard.php) for global settings (e.g., default icon, toast messages).

Implementation Patterns

Common Workflows

  1. Dynamic Clipboard Actions:

    • Use afterStateUpdated or afterStateHydrated for fields that update dynamically (e.g., API keys, tokens):
      TextInput::make('secret_token')
          ->afterStateUpdated(
              Clipboard::make()
                  ->successMessage('Token copied!')
                  ->errorMessage('Failed to copy.')
          ),
      
  2. Conditional Visibility:

    • Show/hide the clipboard action based on field state or logic:
      TextInput::make('email')
          ->extraAttributes(['class' => 'w-full'])
          ->afterStateUpdated(
              Clipboard::make()
                  ->visible(fn ($record) => $record->isVerified())
          ),
      
  3. Customizing the Copied Value:

    • Override the default value (e.g., append a prefix/suffix):
      Clipboard::make()
          ->copyValue(fn ($state) => "Bearer {$state}")
      
  4. Bulk Actions:

    • Combine with Filament’s Table actions for bulk copying (e.g., copy multiple IDs):
      use Moox\Clipboard\Actions\TableClipboard;
      
      Tables\Actions\Action::make('copyIds')
          ->action(TableClipboard::make('id'))
          ->label('Copy Selected IDs'),
      
  5. Integration with Filament Forms/Tables:

    • Forms: Attach to any field in create() or edit() methods.
    • Tables: Use TableClipboard for column-specific actions (e.g., copy emails or URLs).
  6. Localization:

    • Translate labels/messages via Filament’s localization system:
      Clipboard::make()
          ->label(__('actions.copy'))
          ->successMessage(__('messages.copied'))
      

Pro Tips

  • Performance: For large datasets in tables, use lazy loading for clipboard actions to avoid rendering all rows at once.
  • Styling: Customize the button via extraAttributes or Filament’s CSS utilities:
    Clipboard::make()
        ->extraAttributes(['class' => 'bg-blue-500 hover:bg-blue-600'])
    

Gotchas and Tips

Pitfalls

  1. Asset Conflicts:

    • Ensure the package’s JS/CSS isn’t conflicting with other clipboard libraries (e.g., clipboard.js). The package uses Filament’s asset pipeline, so conflicts are rare but possible if multiple clipboard solutions are loaded.
    • Fix: Check resources/js/app.js for duplicate clipboard initializations.
  2. Field State Timing:

    • Clipboard actions tied to afterStateUpdated may not work as expected in create() forms if the field is initially empty. Use afterStateHydrated for pre-filled fields:
      ->afterStateHydrated(
          Clipboard::make()
      )
      
  3. Browser Permissions:

    • Clipboard writes may be blocked by browser extensions (e.g., privacy tools) or user permissions. Test in incognito mode to rule out extension interference.
    • Tip: Add a fallback for permission errors:
      Clipboard::make()
          ->errorMessage('Permission denied. Try again or use Ctrl+C.')
      
  4. Dynamic Fields:

    • If using Filament’s repeatable or file upload fields, ensure the clipboard action targets the correct state path:
      TextInput::make('repeatable.field')
          ->columnSpanFull()
          ->afterStateUpdated(
              Clipboard::make()
                  ->copyValue(fn ($state, $record) => $record->repeatable->field)
          )
      
  5. Caching Issues:

    • After updating the package, clear Filament’s view cache:
      php artisan filament:cache-reset
      

Debugging

  • Check Console: Open browser dev tools (F12) to verify clipboard events fire. Look for errors like:

    Uncaught TypeError: clipboard.copy is not a function
    
    • Cause: Missing or misconfigured package assets. Re-run npm run dev or php artisan filament:assets.
  • Log State: Debug the copied value by logging it in the copyValue callback:

    ->copyValue(fn ($state) => {
        \Log::info('Copying:', ['state' => $state]);
        return $state;
    })
    

Extension Points

  1. Custom Clipboard Logic:

    • Extend the Clipboard action class to add pre/post-copy logic:
      namespace App\Filament\Actions;
      
      use Moox\Clipboard\Actions\Clipboard;
      
      class CustomClipboard extends Clipboard {
          public function handle() {
              // Pre-copy logic (e.g., validate state)
              if (empty($this->state)) {
                  return $this->fail('Field is empty.');
              }
              parent::handle();
              // Post-copy logic (e.g., log event)
              event(new ClipboardCopied($this->state));
          }
      }
      
  2. Global Configuration:

    • Override defaults in config/moox-clipboard.php:
      'default_icon' => 'heroicon-o-copy',
      'toast_duration' => 2000,
      'copy_fallback' => true, // Fallback to text selection if clipboard fails
      
  3. Testing:

    • Mock clipboard actions in PHPUnit:
      $this->partialMock(Clipboard::class, 'handle')
          ->shouldReceive('handle')
          ->once();
      
  4. Server-Side Fallback:

    • For environments where clipboard access is restricted (e.g., headless servers), generate a downloadable file instead:
      Clipboard::make()
          ->fallbackAction(
              Tables\Actions\DownloadAction::make()
                  ->filename(fn ($record) => "{$record->id}.txt")
                  ->content(fn ($record) => $record->secret)
          )
      
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
althinect/enum-permission
andydefer/laravel-actions
aimeos/prisma
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor