hydrat/filament-table-layout-toggle

Filament 插件,为表格添加切换按钮,允许用户在网格和表格布局之间切换。

v2.0.0 2024-08-06 11:22 UTC

This package is auto-updated.

Last update: 2024-09-06 11:26:00 UTC


README

Software License Latest Version on Packagist Total Downloads

此包为 Filament 表格添加了一个简单的切换按钮,允许最终用户在表格上在网格和表格布局之间切换。这种方法允许移动用户从网格布局中受益,而桌面用户仍然可以享受表格布局功能,如表头、排序等。

awcodes/filament-curator 致敬,该包首先在其包中实现了切换功能。此包主要是提取该功能以便在任何项目中使用,并添加了一些其他功能,例如在缓存或本地存储中保存所选布局。

从 1.x 迁移到 2.x 吗?:请阅读 迁移指南

截图

视频捕获

screencast.mov

屏幕截图

screenshot_table screenshot_grid

安装

您可以通过 composer 安装此包

composer require hydrat/filament-table-layout-toggle

可选地,您可以使用以下命令发布视图

php artisan vendor:publish --tag="table-layout-toggle-views"

如果您在 Filament 面板(独立表格)之外使用此包,您应发布配置文件

php artisan vendor:publish --tag="table-layout-toggle-config"

如果使用面板,此配置文件 不会 被插件读取,因为配置是在插件注册时发生的。

使用方法

请根据您的用例选择合适的部分(面板或独立表格)。

面板

首先,在您的 Filament 面板上注册插件

use Hydrat\TableLayoutToggle\TableLayoutTogglePlugin;
use Hydrat\TableLayoutToggle\Persisters;

public function panel(Panel $panel): Panel
{
    return $panel
        ->plugins([
            TableLayoutTogglePlugin::make()
                ->setDefaultLayout('grid') // default layout for user seeing the table for the first time
                ->persistLayoutUsing(
                    persister: Persisters\LocalStoragePersister::class, // chose a persister to save the layout preference of the user
                    cacheStore: 'redis', // optional, change the cache store for the Cache persister
                    cacheTtl: 60 * 24, // optional, change the cache time for the Cache persister
                )
                ->shareLayoutBetweenPages(false) // allow all tables to share the layout option for this user
                ->displayToggleAction() // used to display the toggle action button automatically
                ->toggleActionHook('tables::toolbar.search.after') // chose the Filament view hook to render the button on
                ->listLayoutButtonIcon('heroicon-o-list-bullet')
                ->gridLayoutButtonIcon('heroicon-o-squares-2x2'),
        ]);
}

配置 部分中了解更多关于布局持久化和配置选项的信息。

请注意,所有这些配置都是可选的,并具有默认值,这意味着如果不需要更改默认行为,您可以省略它们。

然后,在包含表格的组件(ListRecord、ManageRelatedRecords 等)上,您可以使用 HasToggleableTable 特性

use Hydrat\TableLayoutToggle\Concerns\HasToggleableTable;

class MyListRecords extends ListRecords
{
    use HasToggleableTable;
}

最后,您需要配置您的表格,以便它根据所选布局动态设置模式。这通常在资源的方法 table() 中完成

public static function table(Table $table): Table
{
    $livewire = $table->getLivewire();

    return $table
        ->columns(
            $livewire->isGridLayout()
                ? static::getGridTableColumns()
                : static::getListTableColumns()
        )
        ->contentGrid(
            fn () => $livewire->isListLayout()
                ? null
                : [
                    'md' => 2,
                    'lg' => 3,
                    'xl' => 4,
                ]
        );
}

// Define the columns for the table when displayed in list layout
public static function getListTableColumns(): array;

// Define the columns for the table when displayed in grid layout
public static function getGridTableColumns(): array;

请注意,您必须使用 filament 文档 中描述的布局工具,以便您的网格布局正确渲染。您还可以使用 description() 方法在值上方打印标签。

public static function getGridTableColumns(): array
{
    return [
        // Make sure to stack your columns together
        Tables\Columns\Layout\Stack::make([

            Tables\Columns\TextColumn::make('status')->badge(),

            // You may group columns together using the Split layout, so they are displayed side by side
            Tables\Columns\Layout\Split::make([
                Tables\Columns\TextColumn::make('customer')
                    ->description(__('Customer'), position: 'above')
                    ->searchable(),

                Tables\Columns\TextColumn::make('owner.name')
                    ->description(__('Owner'), position: 'above')
                    ->searchable(),
            ]),

        ])->space(3)->extraAttributes([
            'class' => 'pb-2',
        ]),
    ];
}

独立表格

您可以通过发布的配置文件管理插件设置。选项是自文档化的,应该很容易使用。

然后,在包含表格的组件上,您可以使用 HasToggleableTable 特性

namespace App\Livewire\Users;

use Hydrat\TableLayoutToggle\Concerns\HasToggleableTable;

class ListUsers extends Component implements HasForms, HasTable, HasActions
{
    use InteractsWithTable;
    use InteractsWithActions;
    use InteractsWithForms;
    use HasToggleableTable; // <-- Add this line
}

如果您计划在本地存储中持久化布局,您还必须更改视图以包含所需的资源

[...]
{{ $this->table }}

{{ $this->renderLayoutViewPersister() }} <-- Add this line

最后,您需要配置表格,以便它根据所选布局动态设置模式。这通常在组件的 table() 方法中完成

public function table(Table $table): Table
{
    return $table
        ->columns(
            $this->isGridLayout()
                ? $this->getGridTableColumns()
                : $this->getListTableColumns()
        )
        ->contentGrid(
            fn () => $this->isListLayout()
                ? null
                : [
                    'md' => 2,
                    'lg' => 3,
                    'xl' => 4,
                ]
        );
}

// Define the columns for the table when displayed in list layout
public static function getListTableColumns(): array;

// Define the columns for the table when displayed in grid layout
public static function getGridTableColumns(): array;

请注意,您必须使用 filament 文档 中描述的布局工具,以便您的网格布局正确渲染。您还可以使用 description() 方法在值上方打印标签。

public static function getGridTableColumns(): array
{
    return [
        // Make sure to stack your columns together
        Tables\Columns\Layout\Stack::make([

            Tables\Columns\TextColumn::make('status')->badge(),

            // You may group columns together using the Split layout, so they are displayed side by side
            Tables\Columns\Layout\Split::make([
                Tables\Columns\TextColumn::make('customer')
                    ->description(__('Customer'), position: 'above')
                    ->searchable(),

                Tables\Columns\TextColumn::make('owner.name')
                    ->description(__('Owner'), position: 'above')
                    ->searchable(),
            ]),

        ])->space(3)->extraAttributes([
            'class' => 'pb-2',
        ]),
    ];
}

配置

布局持久化

该插件提出了几个持久化类,用于保存用户的布局偏好

Persisters\LocalStoragePersister::class  # Save the layout in the local storage
Persisters\CachePersister::class         # Save the layout in the application cache
Persisters\DisabledPersister::class      # Do not persist the layout

缓存持久化有多个选项,如果您在面板中使用插件,可以使用 persistLayoutUsing 方法进行切换;如果您使用独立表格,可以通过修改配置文件来实现。

// Plugin registration
TableLayoutTogglePlugin::make()
    ->persistLayoutUsing(
        persister: Persisters\CachePersister::class,
        cacheStore: 'redis', // change storage to redis
        cacheTtl: 60 * 24 * 7 * 4, // change ttl to 1 month
    );

// Configuration file
'persiter' => Persisters\CachePersister::class,

'cache' => [
    'storage' => 'redis', // change storage to redis

    'time' => 60 * 24 * 7 * 4, // change ttl to 1 month
],

您还可以通过实现 LayoutPersister 接口来创建自己的持久化类。AbstractPersister 类提供了一些默认实现,必要时可以覆盖。

<?php

namespace App\Filament\Persisters;

use Hydrat\TableLayoutToggle\Persisters;
use Hydrat\TableLayoutToggle\Contracts\LayoutPersister;

class CustomPersister extends AbstractPersister implements LayoutPersister
{
    public function setState(string $layoutState): self
    {
        persisterSetState($this->getKey(), $layoutState);

        return $this;
    }

    public function getState(): ?string
    {
        return persisterGetState($this->getKey());
    }

    public function onComponentBoot(): void
    {
        // add filament hooks to render a custom view or so...
    }
}

您可以使用 $this->component 访问 Livewire 组件。

按表更改设置

您可能只需要针对特定表调整一些设置。这可以通过在组件中覆盖该包提供的默认方法来实现,该组件使用 HasToggleableTable 特性。

namespace App\Livewire\Users;

class ListUsers extends Component implements HasForms, HasTable, HasActions
{
    use HasToggleableTable;

    /**
     * Set the default layout for this table, when the user sees it for the first time.
     */
    public function getDefaultLayoutView(): string
    {
        return 'grid';
    }

    /**
     * Modify the persister configuration,
     * or initialize a new one for this component.
     */
    public function configurePersister(): void
    {
        // customize the persister for this specific table
        $this->layoutPersister
            ->setKey('custom_key'. auth()->id())
            ->setCacheDriver('redis')
            ->setExpiration(60 * 24 * 7 * 4);

        // or create a new persister for this specific table
        $this->layoutPersister = new CustomPersister($this);
    }
}

使用自定义操作

如果您想使用自己的操作而不是默认操作,您应该首先在插件注册时禁用它。

$panel
    ->plugins([
      TableLayoutTogglePlugin::make()
          ->displayToggleAction(false),
    ])

然后,您可以从提供的辅助程序获取并扩展基本 ActionTableAction

use Hydrat\TableLayoutToggle\Facades\TableLayoutToggle;

# eg: Display action on top of the table :
return $table
    ->columns(...)
    ->headerActions([
        TableLayoutToggle::getToggleViewTableAction(compact: true),
    ]);

# eg: As Filament page header action :
protected function getHeaderActions(): array
{
    return [
        TableLayoutToggle::getToggleViewAction(compact: false)
            ->hiddenLabel(false)
            ->label('Toggle layout'),
    ];
}

变更日志

请参阅 CHANGELOG 了解最近的变化。

迁移指南

请参阅 MIGRATION 了解最近的变化。

贡献

请参阅 CONTRIBUTING 获取详细信息。

安全漏洞

请查阅 我们的安全策略 了解如何报告安全漏洞。

鸣谢

许可证

MIT 许可证(MIT)。请参阅 许可文件 了解更多信息。