| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262 | <?php
namespace App\Filament\Company\Pages\Setting;
use App\Enums\{Font, MaxContentWidth, ModalWidth, PrimaryColor, RecordsPerPage, TableSortDirection};
use App\Models\Setting\Appearance as AppearanceModel;
use Filament\Actions\{Action, ActionGroup};
use Filament\Forms\Components\{Component, Section, Select};
use Filament\Forms\Form;
use Filament\Notifications\Notification;
use Filament\Pages\Concerns\InteractsWithFormActions;
use Filament\Pages\Page;
use Filament\Support\Exceptions\Halt;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\Model;
use Livewire\Attributes\Locked;
use Wallo\FilamentSelectify\Components\{ButtonGroup, ToggleButton};
use function Filament\authorize;
/**
 * @property Form $form
 */
class Appearance extends Page
{
    use InteractsWithFormActions;
    protected static ?string $navigationIcon = 'heroicon-o-paint-brush';
    protected static ?string $navigationLabel = 'Appearance';
    protected static ?string $navigationGroup = 'Settings';
    protected static ?string $slug = 'settings/appearance';
    protected ?string $heading = 'Appearance';
    protected static string $view = 'filament.company.pages.setting.appearance';
    public ?array $data = [];
    #[Locked]
    public ?AppearanceModel $record = null;
    public function mount(): void
    {
        $this->record = AppearanceModel::firstOrNew([
            'company_id' => auth()->user()->currentCompany->id,
        ]);
        abort_unless(static::canView($this->record), 404);
        $this->fillForm();
    }
    public function fillForm(): void
    {
        $data = $this->record->attributesToArray();
        $data = $this->mutateFormDataBeforeFill($data);
        $this->form->fill($data);
    }
    protected function mutateFormDataBeforeFill(array $data): array
    {
        return $data;
    }
    protected function mutateFormDataBeforeSave(array $data): array
    {
        return $data;
    }
    public function save(): void
    {
        try {
            $data = $this->form->getState();
            $data = $this->mutateFormDataBeforeSave($data);
            $this->handleRecordUpdate($this->record, $data);
        } catch (Halt $exception) {
            return;
        }
        $this->getSavedNotification()?->send();
        if ($redirectUrl = $this->getRedirectUrl()) {
            $this->redirect($redirectUrl);
        }
    }
    protected function getSavedNotification(): ?Notification
    {
        $title = $this->getSavedNotificationTitle();
        if (blank($title)) {
            return null;
        }
        return Notification::make()
            ->success()
            ->title($this->getSavedNotificationTitle());
    }
    protected function getSavedNotificationTitle(): ?string
    {
        return __('filament-panels::pages/tenancy/edit-tenant-profile.notifications.saved.title');
    }
    protected function getRedirectUrl(): ?string
    {
        return null;
    }
    public function form(Form $form): Form
    {
        return $form
            ->schema([
                $this->getGeneralSection(),
                $this->getLayoutSection(),
                $this->getDataPresentationSection(),
            ])
            ->model($this->record)
            ->statePath('data')
            ->operation('edit');
    }
    protected function getGeneralSection(): Component
    {
        return Section::make('General')
            ->schema([
                Select::make('primary_color')
                    ->label('Primary Color')
                    ->native(false)
                    ->allowHtml()
                    ->selectablePlaceholder(false)
                    ->rule('required')
                    ->options(
                        collect(PrimaryColor::cases())
                            ->mapWithKeys(static fn ($case) => [
                                $case->value => "<span class='flex items-center gap-x-4'>
                                <span class='rounded-full w-4 h-4' style='background:rgb(" . $case->getColor()[600] . ")'></span>
                                <span>" . str($case->value)->title() . '</span>
                                </span>',
                            ]),
                    ),
                Select::make('font')
                    ->label('Font')
                    ->native(false)
                    ->selectablePlaceholder(false)
                    ->rule('required')
                    ->allowHtml()
                    ->options(
                        collect(Font::cases())
                            ->mapWithKeys(static fn ($case) => [
                                $case->value => "<span style='font-family:{$case->getLabel()}'>{$case->getLabel()}</span>",
                            ]),
                    ),
            ])->columns();
    }
    protected function getLayoutSection(): Component
    {
        return Section::make('Layout')
            ->schema([
                Select::make('max_content_width')
                    ->label('Max Content Width')
                    ->native(false)
                    ->selectablePlaceholder(false)
                    ->rule('required')
                    ->options(MaxContentWidth::class),
                Select::make('modal_width')
                    ->label('Modal Width')
                    ->native(false)
                    ->selectablePlaceholder(false)
                    ->rule('required')
                    ->options(ModalWidth::class),
                ButtonGroup::make('has_top_navigation')
                    ->label('Navigation Layout')
                    ->boolean('Top Navigation', 'Side Navigation')
                    ->rule('required'),
                ToggleButton::make('is_table_striped')
                    ->label('Striped Tables')
                    ->onLabel('Enabled')
                    ->offLabel('Disabled')
                    ->rule('required'),
            ])->columns();
    }
    protected function getDataPresentationSection(): Component
    {
        return Section::make('Data Presentation')
            ->schema([
                Select::make('table_sort_direction')
                    ->label('Table Sort Direction')
                    ->native(false)
                    ->selectablePlaceholder(false)
                    ->rule('required')
                    ->options(TableSortDirection::class),
                Select::make('records_per_page')
                    ->label('Records Per Page')
                    ->native(false)
                    ->selectablePlaceholder(false)
                    ->rule('required')
                    ->options(RecordsPerPage::class),
            ])->columns();
    }
    protected function handleRecordUpdate(AppearanceModel $record, array $data): AppearanceModel
    {
        $record_array = array_map('strval', $record->toArray());
        $data_array = array_map('strval', $data);
        $diff = array_diff_assoc($data_array, $record_array);
        $keysToWatch = [
            'primary_color',
            'max_content_width',
            'has_top_navigation',
            'font',
        ];
        foreach ($diff as $key => $value) {
            if (in_array($key, $keysToWatch, true)) {
                $this->dispatch('appearanceUpdated');
            }
        }
        $record->update($data);
        return $record;
    }
    /**
     * @return array<Action | ActionGroup>
     */
    protected function getFormActions(): array
    {
        return [
            $this->getSaveFormAction(),
        ];
    }
    protected function getSaveFormAction(): Action
    {
        return Action::make('save')
            ->label(__('filament-panels::pages/tenancy/edit-tenant-profile.form.actions.save.label'))
            ->submit('save')
            ->keyBindings(['mod+s']);
    }
    public static function canView(Model $record): bool
    {
        try {
            return authorize('update', $record)->allowed();
        } catch (AuthorizationException $exception) {
            return $exception->toResponse()->allowed();
        }
    }
}
 |