Skip to content

Instantly share code, notes, and snippets.

@Log1x
Last active December 13, 2023 14:40
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Log1x/c01458f7e4053ed242c88e61ef6bb1c8 to your computer and use it in GitHub Desktop.
Save Log1x/c01458f7e4053ed242c88e61ef6bb1c8 to your computer and use it in GitHub Desktop.
Filament Peek URL Preview Helper
<?php
namespace App\Filament\Resources\PostResource\Pages;
use App\Concerns\HasPreview;
use App\Filament\Resources\PostResource;
use Filament\Resources\Pages\EditRecord;
use Pboivin\FilamentPeek\Pages\Actions\PreviewAction;
use Pboivin\FilamentPeek\Pages\Concerns\HasPreviewModal;
class EditPost extends EditRecord
{
use HasPreview, HasPreviewModal;
/**
* The resource model.
*/
protected static string $resource = PostResource::class;
/**
* The preview modal URL.
*/
protected function getPreviewModalUrl(): ?string
{
$this->createPreviewSession();
return route('post.show', [
'post' => $this->record->slug,
'previewToken' => $this->previewToken,
]);
}
/**
* The header actions.
*/
protected function getHeaderActions(): array
{
return [
PreviewAction::make(),
];
}
}
<?php
namespace App\Concerns;
use Illuminate\Support\Str;
trait HasPreview
{
/**
* The preview token.
*/
protected ?string $previewToken = null;
/**
* The preview status.
*/
public bool $isPreview = false;
/**
* Handle the preview.
*/
protected function handlePreview(string $resource = null, string $token = 'previewToken'): void
{
if (! request()->has($token)) {
return;
}
$attributes = session()->get('preview-'.request()->get($token));
if (empty($attributes)) {
return;
}
if (empty($resource) && ! empty($this->__name)) {
$resource = Str::before($this->__name, '.');
}
$resource = Str::afterLast($resource, '\\');
$resource = Str::slug($resource, '_');
$this->isPreview = true;
$this->{$resource}->fill($attributes);
}
/**
* Generate a preview token and create a session.
*/
protected function createPreviewSession(string $record = 'record'): void
{
if (empty($resource = $this->previewModalData[$record])) {
return;
}
$this->previewToken = uniqid();
session()->put("preview-{$this->previewToken}", $resource->toArray());
}
}
<div>
@if ($isPreview)
<style>
a { pointer-events: none !important; }
</style>
@endif
<div>
<h1>{{ $post->title }}</h1>
<p>{{ $post->content }}</p>
</div>
</div>
<?php
namespace App\Livewire\Post;
use App\Concerns\HasPreview;
use App\Models\Post;
use Livewire\Component;
class Show extends Component
{
use HasPreview;
/**
* The post instance.
*/
public Post $post;
/**
* Render the component.
*
* @return \Illuminate\Contracts\View\View
*/
public function render()
{
$this->handlePreview();
return view('livewire.post.show');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment