Skip to content
全部文档

构建独立插件

前言

继续之前,请先阅读 面板插件开发快速开始指南

简介

本教程将构建一个简单插件,向表单添加一个新的表单组件;该组件也会在用户的面板中可用。

本插件最终代码见 https://github.com/awcodes/headings

步骤 1:创建插件

首先,按快速开始指南中的步骤创建插件。

步骤 2:清理

接下来清理插件,移除不需要的样板代码。看起来很多,但本插件很简单,可去掉大量样板。

删除以下目录与文件:

  1. bin
  2. config
  3. database
  4. src/Commands
  5. src/Facades
  6. stubs

现在清理 composer.json,移除不需要的选项。

json
"autoload": {
    "psr-4": {
        // We can remove the database factories
        "Awcodes\\Headings\\Database\\Factories\\": "database/factories/"
    }
},
"extra": {
    "laravel": {
        // We can remove the facade
        "aliases": {
            "Headings": "Awcodes\\Headings\\Facades\\ClockWidget"
        }
    }
},

通常 Filament 建议用户用自定义 Filament theme 为插件设置样式;为便于演示,我们提供自己的样式表,并利用 Filament v3 的 x-load 特性异步加载。因此更新 package.json,加入 cssnanopostcsspostcss-clipostcss-nesting 以构建样式表。

json
{
    "private": true,
    "scripts": {
        "build": "postcss resources/css/index.css -o resources/dist/headings.css"
    },
    "devDependencies": {
        "cssnano": "^6.0.1",
        "postcss": "^8.4.27",
        "postcss-cli": "^10.1.0",
        "postcss-nesting": "^13.0.0"
    }
}

然后安装依赖。

bash
npm install

还需更新 postcss.config.js 以配置 postcss。

js
module.exports = {
    plugins: [
        require('postcss-nesting')(),
        require('cssnano')({
            preset: 'default',
        }),
    ],
};

也可删除 testing 相关目录与文件;本例暂时保留且不会使用。我们强烈建议你为插件编写测试。

步骤 3:配置 provider

插件清理完成后即可开始写代码。src/HeadingsServiceProvider.php 中的样板较多,我们全部删掉从头开始。

需要把样式表注册到 Filament Asset Manager,以便在 Blade 视图中按需加载。为此,在 service provider 的 packageBooted 方法中加入如下内容。

Note the loadedOnRequest() method. This is important, because it tells Filament to only load the stylesheet when it's needed.

php
namespace Awcodes\Headings;

use Filament\Support\Assets\Css;
use Filament\Support\Facades\FilamentAsset;
use Spatie\LaravelPackageTools\Package;
use Spatie\LaravelPackageTools\PackageServiceProvider;

class HeadingsServiceProvider extends PackageServiceProvider
{
    public static string $name = 'headings';

    public function configurePackage(Package $package): void
    {
        $package->name(static::$name)
            ->hasViews();
    }

    public function packageBooted(): void
    {
        FilamentAsset::register([
            Css::make('headings', __DIR__ . '/../resources/dist/headings.css')->loadedOnRequest(),
        ], 'awcodes/headings');
    }
}

步骤 4:创建组件

接下来创建组件。在 src/Heading.php 新建文件并加入如下代码。

php
namespace Awcodes\Headings;

use Closure;
use Filament\Schemas\Components\Component;
use Filament\Support\Colors\Color;
use Filament\Support\Concerns\HasColor;

class Heading extends Component
{
    use HasColor;

    protected string | int $level = 2;

    protected string | Closure $content = '';

    protected string $view = 'headings::heading';

    final public function __construct(string | int $level)
    {
        $this->level($level);
    }

    public static function make(string | int $level): static
    {
        return app(static::class, ['level' => $level]);
    }

    public function content(string | Closure $content): static
    {
        $this->content = $content;

        return $this;
    }

    public function level(string | int $level): static
    {
        $this->level = $level;

        return $this;
    }

    public function getColor(): array
    {
        return $this->evaluate($this->color) ?? Color::Amber;
    }

    public function getContent(): string
    {
        return $this->evaluate($this->content);
    }

    public function getLevel(): string
    {
        return is_int($this->level) ? 'h' . $this->level : $this->level;
    }
}

步骤 5:渲染组件

接下来为组件创建视图。在 resources/views/heading.blade.php 新建文件并加入如下代码。

我们使用 x-load 异步加载样式表,仅在需要时加载。详见文档的 Core Concepts 一节。

blade
@php
    $level = $getLevel();
    $color = $getColor();
@endphp

<{{ $level }}
    x-data
    x-load-css="[@js(\Filament\Support\Facades\FilamentAsset::getStyleHref('headings', package: 'awcodes/headings'))]"
    {{
        $attributes
            ->class([
                'headings-component',
                match ($color) {
                    'gray' => 'text-gray-600 dark:text-gray-400',
                    default => 'text-custom-500',
                },
            ])
            ->style([
                \Filament\Support\get_color_css_variables($color, [500]) => $color !== 'gray',
            ])
    }}
>
    {{ $getContent() }}
</{{ $level }}>

步骤 6:添加样式

接下来为字段提供自定义样式。将以下内容加入 resources/css/index.css,并运行 npm run build 编译 CSS。

css
.headings-component {
    &:is(h1, h2, h3, h4, h5, h6) {
         font-weight: 700;
         letter-spacing: -.025em;
         line-height: 1.1;
     }

    &h1 {
         font-size: 2rem;
     }

    &h2 {
         font-size: 1.75rem;
     }

    &h3 {
         font-size: 1.5rem;
     }

    &h4 {
         font-size: 1.25rem;
     }

    &h5,
    &h6 {
         font-size: 1rem;
     }
}

然后构建样式表。

bash
npm run build

步骤 7:更新 README

请更新 README.md,加入插件安装说明以及希望与用户分享的其他信息,例如如何在项目中使用。例如:

php
use Awcodes\Headings\Heading;

Heading::make(2)
    ->content('Product Information')
    ->color(Color::Lime),

就这样,用户现在可以安装并在项目中使用我们的插件了。