定制 hydrat/filament-table-layout-toggle 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

hydrat/filament-table-layout-toggle

Composer 安装命令:

composer require hydrat/filament-table-layout-toggle

包简介

Filament plugin adding a toggle button to tables, allowing user to switch between Grid and Table layouts.

README 文档

README

Software License Latest Version on Packagist Total Downloads Filament Version

This package brings a simple toggle button to Filament tables, allowing end users to switch between Grid and Table layouts on tables. This approach allows mobile users to benefit from the Grid layout, while desktop users can still benefit from Table layout features, such as the table headers, sorting and so on.

Big shoutout to awcodes/filament-curator, which implemented the toggle feature first on their package. This package is mainly an extraction of the feature so that it can be used in any project, and some other adding such as saving the selected layout in the cache or local storage.

Requirements

Screenshots

Video capture

screencast.mov

Screen capture

screenshot_table screenshot_grid

Installation

You can install the package via composer:

composer require hydrat/filament-table-layout-toggle:^4.0

Optionally, you can publish the views using

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

If you are using this package outside of filament panels (standalone tables), you should publish the configuration file :

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

If using panels, this configuration file WILL NOT be read by the plugin, as the configuration happens on the plugin registration itself.

Usage

Please chose the appropriate section for your use case (Panels or Standalone tables).

Panels

First, register the plugin on your Filament panel :

use Hydrat\TableLayoutToggle\TableLayoutTogglePlugin;

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: \Hydrat\TableLayoutToggle\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')
                ->enableAutoMobileLayout(), // automatically use grid layout for mobile users with no saved preference
        ]);
}

Read more about the Layout persister and the configuration options in the Configuration section.

Please note that all those configurations are optional, and have default values, which means you can omit them if you don't need to change the default behavior.

Then, on the component containing the table (ListRecord, ManageRelatedRecords, ...), you can use the HasToggleableTable trait :

use Hydrat\TableLayoutToggle\Concerns\HasToggleableTable;

class MyListRecords extends ListRecords
{
    use HasToggleableTable;
}

Finally, you need to configure your table so it dynamically sets the schema based on the selected layout. This is typically done on the resource's Table class (eg: App\Filament\Resources\Entries\Tables) :

class EntriesTable
{
    public static function configure(Table $table): Table
    {
        /** @var \Hydrat\TableLayoutToggle\Concerns\HasToggleableTable $livewire */
        $livewire = $table->getLivewire();

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

    // 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;
}

Please note that you must use the Layout tools described in the filament documentation in order for your Grid layout to render correctly. You may also use the description() method to print labels above your values.

use Filament\Tables\Columns\Layout\Split;
use Filament\Tables\Columns\Layout\Stack;
use Filament\Tables\Columns\TextColumn;

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

            TextColumn::make('status')->badge(),

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

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

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

Standalone tables

You can manage the plugin settings via the published configuration file. The options are self-documented, and should be pretty straightforward to use.

Then, on the component containing the table, you can use the HasToggleableTable trait :

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
}

If you plan to persist the layout in the local storage, you must also change your view to include the needed assets :

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

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

Finally, you need to configure your table so it dynamically sets the schema based on the selected layout. This is typically done on the component's table() method :

public static function table(Table $table): Table
{
    /** @var \Hydrat\TableLayoutToggle\Concerns\HasToggleableTable $livewire */
    $livewire = $table->getLivewire();

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

// 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;

Please note that you must use the Layout tools described in the filament documentation in order for your Grid layout to render correctly. You may also use the description() method to print labels above your values.

use Filament\Tables\Columns\Layout\Split;
use Filament\Tables\Columns\Layout\Stack;
use Filament\Tables\Columns\TextColumn;

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

            TextColumn::make('status')->badge(),

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

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

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

Configuration

Layout persister

The plugin proposes several persister classes to save the layout preference of the user :

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

The cache persister has several options, which you can toggle using the persistLayoutUsing method if using the Plugin in panels, or by changing the configuration file if using standalone tables.

// 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
],

You can also create your own persister by implementing the the LayoutPersister contract. The AbstractPersister class provides some default implementation which can be overridden if needed.

<?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...
    }
}

You can access the Livewire component using $this->component.

Auto mobile layout

When enabled, the grid layout is automatically applied for users visiting from a mobile device, but only if they have no previously saved layout preference. Once the user manually switches the layout, their choice is persisted as usual.

Detection is based on the User-Agent header sent by the browser.

Panel plugin:

TableLayoutTogglePlugin::make()
    ->enableAutoMobileLayout() // pass false to disable

Standalone tables (configuration file):

'auto_mobile_layout' => true,

Change settings per-table

You may need to tweak some settings for a specific table only. This can be done by overriding the default methods provided by this package in the component you are using the HasToggleableTable trait in :

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);
    }
}

Using own action

If you rather use your own action instead of the default one, you should first disable it on the plugin registration :

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

Then, you can get and extend base Action or TableAction from the provided helper :

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

Please see CHANGELOG for more information on what has changed recently.

Migration guide

Please see MIGRATION for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

License

The MIT License (MIT). Please see License File for more information.

hydrat/filament-table-layout-toggle 适用场景与选型建议

hydrat/filament-table-layout-toggle 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 114.27k 次下载、GitHub Stars 达 63, 最近一次更新时间为 2023 年 12 月 29 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「laravel」 「Hydrat」 「filament-table-layout-toggle」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 hydrat/filament-table-layout-toggle 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 hydrat/filament-table-layout-toggle 我们能提供哪些服务?
定制开发 / 二次开发

基于 hydrat/filament-table-layout-toggle 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 114.27k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 63
  • 点击次数: 27
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 63
  • Watchers: 2
  • Forks: 17
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-12-29