ingress-it-solutions/livewire-toaster 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

ingress-it-solutions/livewire-toaster

Composer 安装命令:

composer require ingress-it-solutions/livewire-toaster

包简介

Beautiful toast notifications for Laravel / Livewire.

README 文档

README

Toaster Banner

Beautiful toast notifications for Livewire

Latest Version on Packagist GitHub Tests Action Status Total Downloads

Toaster provides a seamless experience to display toast notifications in your Livewire powered Laravel apps.

Unlike many other toast implementations that are available, Toaster makes it effortless to dispatch a toast notification from either a standard Controller or a Livewire Component. You don't have to think about "flashing" things to the session or "dispatching browser events" from your Livewire components. Just dispatch your toast and Toaster will route the message accordingly.

Showcase

Toaster Demo

Contents

Installation

You can install the package via composer:

composer require masmerise/livewire-toaster

You can publish the package's config file:

php artisan vendor:publish --tag=toaster-config

This is the contents of the toaster.php config file:

return [

    /**
     * Add an additional second for every 100th word of the toast messages.
     *
     * Supported: true | false
     */
    'accessibility' => true,

    /**
     * The vertical alignment of the toast container.
     *
     * Supported: "bottom" or "top"
     */
    'alignment' => 'bottom',

    /**
     * Allow users to close toast messages prematurely.
     *
     * Supported: true | false
     */
    'closeable' => true,

    /**
     * The on-screen duration of each toast.
     *
     * Minimum: 3000 (in milliseconds)
     */
    'duration' => 3000,

    /**
     * The horizontal position of each toast.
     *
     * Supported: "center", "left" or "right"
     */
    'position' => 'right',

    /**
     * Whether messages passed as translation keys should be translated automatically.
     *
     * Supported: true | false
     */
    'translate' => true,
];

Preparing your template

Next, you'll need to use the <x-toaster-hub /> component in your master template:

<!DOCTYPE html>
<html>
<head>
    <!-- ... -->
</head>

<body>
    <!-- Application content -->

    <x-toaster-hub /> <!-- 👈 -->
</body>
</html>

Configuring scripts

After that, you'll need to register the Toaster plugin with your resources/js/app.js bundle to start listening to incoming toasts:

import Alpine from 'alpinejs';
import Toaster from '../../vendor/masmerise/livewire-toaster/resources/js'; // 👈

Alpine.plugin(Toaster); // 👈

window.Alpine = Alpine;
Alpine.start();

Tailwind styles

Note Skip this step if you're going to customize Toaster's default view.

Toaster provides a minimal view that utilizes Tailwind CSS defaults.

If the default toast appearances suffice your needs, you'll need to register it with Tailwind's purge list:

module.exports = {
    content: [
        './resources/**/*.blade.php',
        './vendor/masmerise/livewire-toaster/resources/views/*.blade.php', // 👈
    ],
}

Otherwise, please refer to View customization.

Usage

Sending toasts from the back-end

Note Toaster supports the dispatch of multiple toasts at once, you are not limited to dispatching a single toast.

Toaster

The standard recommended way for dispatching toast messages is through the Toaster facade.

use Masmerise\Toaster\Toaster;

final class RegistrationForm extends Component
{
    public function submit(): void
    {
        $this->validate();
        
        User::create($this->form);
        
        Toaster::success('User created!'); // 👈
    }
}

If you need fine-grained control, you can always use the PendingToast class directly to which Toaster proxies its calls:

use Masmerise\Toaster\PendingToast;

final class RegistrationForm extends Component
{
    public function submit(): void
    {
        $this->validate();
        
        $user = User::create($this->form);
        
        // 👇
        PendingToast::create()
            ->when($user->isAdmin(),
                fn (PendingToast $toast) => $toast->message('Admin created')
            )
            ->unless($user->isAdmin(),
                fn (PendingToast $toast) => $toast->message('User created')
            )
            ->success();
    }
}

Toastable

You can make any class Toastable to dispatch toasts from:

use Masmerise\Toaster\Toastable;

final class ProductListing extends Component
{
    use Toastable; // 👈

    public function check(): void
    {
        $result = Product::query()
            ->tap(new Available())
            ->count();
            
        if ($result < 5) {
            $this->warning('The quantity on hand is critically low.'); // 👈
        }
    }
}

Redirects

Whenever you return a RedirectResponse from anywhere in your app, you can chain any of the Toaster methods to dispatch a toast message:

final class CompanyController extends Controller
{
    /** @throws ValidationException */
    public function store(Request $request): RedirectResponse
    {
        $validator = Validator::make($request->all(), [...]);
        
        if ($validator->fails()) {
            return Redirect::back()
                ->error('The form contains several errors'); // 👈
        }
    
        Company::create($validator->validate());
        
        return Redirect::route('dashboard')
            ->info('Company created!'); // 👈
    }
}

This is, of course, not limited to Controllers as you can also redirect in Livewire Components.

Dependency injection

If you'd like to keep things "pure", you can also inject the Collector contract and use the ToastBuilder to dispatch your toasts:

use Masmerise\Toaster\Collector;
use Masmerise\Toaster\ToasterConfig;
use Masmerise\Toaster\ToastBuilder;

final readonly class SendEmailVerifiedNotification
{
    public function __construct(
        private ToasterConfig $config,
        private Collector $toasts,
    ) {}
    
    public function handle(Verified $event): void
    {
        $toast = ToastBuilder::create()
            ->duration($this->config->duration)
            ->success()
            ->message("Thank you, {$event->user->name}!")
            ->get();
            
        $this->toasts->collect($toast);
    }
}

Sending toasts from the front-end

You can invoke the globally available Toaster instance to dispatch any toast message from anywhere:

<button @click="Toaster.success('Form submitted!')">
    Submit
</button>

Available methods: error, info, warning & success

Automatic translation of messages

Note The translate configuration value must be set to true.

Instead of doing this:

Toaster::success(
    Lang::get('path.to.translation', ['replacement' => 'value'])
);

Toaster makes it possible to do this:

Toaster::success('path.to.translation', ['replacement' => 'value']);

You can mix and match without any problems:

Toaster::info('user.created', ['name' => $user->full_name]);
Toaster::info('You now have full access!');

You can do whatever you want, whenever you want.

Accessibility

Note The accessibility configuration value must be set to true.

Toaster will add an additional second to a toast's on-screen duration for every 100th word. This way, your users will have enough time to read toasts that are a tad larger than usual.

So, if your base duration value is 3 seconds and your toast contains 223 words, the total on-screen duration of the toast will be 3 + 2 = 5 seconds

Unit testing

Note If you make use of automatic translation of messages, you should assert whether the translation keys are passed along correctly instead of the human readable messages that are replaced by Laravel's translator. Otherwise, your tests are going to fail as the messages are not translated during unit testing.

Toaster provides a couple of testing capabilities in order for you to build a robust application:

use Masmerise\Toaster\Toaster;

final class RegisterUserControllerTest extends TestCase
{
    #[Test]
    public function users_can_register(): void
    {
        // Arrange
        Toaster::fake();
        Toaster::assertNothingDispatched();
        
        // Act
        $response = $this->post('users', [ ... ]);
        
        // Assert
        $response->assertRedirect('profile');
        Toaster::assertDispatched('Welcome!');
    }
}

View customization

Warning You must keep the x-data and x-init directives and you must keep using the x-for loop. Otherwise, the Alpine component that powers Toaster will start malfunctioning.

Even though the default toasts are pretty, they might not fit your design and you may want to customize them.

You can do so by publishing Toaster's views:

php artisan vendor:publish --tag=toaster-views

The hub.blade.php view will be published to your application's resources/views/vendor/toaster directory. Feel free to modify anything to your liking.

Available viewData

  • $alignment - can be used to align the toast container vertically depending on the configuration
  • $closeable - whether the close button should be rendered by the Blade component
  • $config - default configuration values, used by the Alpine component
  • $position - can be used to position the toasts depending on the configuration
  • $toasts - toasts that were flashed to the session by Toaster, used by the Alpine component

Testing

composer test

Changelog

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

Security

If you discover any security related issues, please email support@muhammedsari.me instead of using the issue tracker.

Credits

License

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

ingress-it-solutions/livewire-toaster 适用场景与选型建议

ingress-it-solutions/livewire-toaster 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 8 次下载、GitHub Stars 达 0, 最近一次更新时间为 2023 年 04 月 25 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 ingress-it-solutions/livewire-toaster 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 8
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 18
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2023-04-25