定制 capevace/livewire-optimistic-ui 二次开发

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

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

capevace/livewire-optimistic-ui

Composer 安装命令:

composer require capevace/livewire-optimistic-ui

包简介

A utility package for better Optimistic UI support in Laravel Livewire.

README 文档

README

Demo.mp4

Installation

You can install the package via composer:

composer require capevace/livewire-optimistic-ui

Example

# In your Livewire component's .blade.php file
<x-optimistic::injector class="max-w-lg mx-auto mt-10">
  <x-demo.saving-indicator wire:loading.delay />

  <form
    class="w-full flex items-center gap-5 mb-10"
    x-data="{ text: '' }"
    @submit.prevent="
      $optimistic.addTask(text);
      text = '';
    "
  >
    <input
      autofocus
      name="text"
      x-model="text"
      placeholder="Type your task here..."
      class="flex-1 px-5 py-3 border shadow rounded-lg"
    />

    <button class="px-5 py-3 border shadow rounded-lg bg-green-400">Add +</button>
  </form>

  <x-demo.list>
    @foreach($todos as $task)
      <x-demo.task
        wire:key="{{ $task['id'] }}"
        x-optimistic
        x-optimistic.removed.remove
      >
        <x-demo.button @click="$optimistic.deleteTask('{{ $task['id'] }}')"/>

        <form
          x-data="{
            text: $item?.text ?? @js($task['text']),
          }"
          class="flex-1"
        >
          <x-demo.input
            name="text_{{ $task['id'] }}"
            x-model="text"
            x-optimistic.edited.class="italic"

            @input.debounce="$optimistic.editTask('{{ $task['id'] }}', text)"
          />
        </form>

      </x-demo.task>
    @endforeach

    <x-optimistic::added>
      <x-demo.task
        x-bind:data-id="$item.id"
        x-bind:wire:key="$item.id"
        x-optimistic.removed.remove
      >
        <x-demo.button @click="$optimistic.deleteTask($item.id)"/>

        <div class="flex-1">
          <x-demo.input
            x-bind:name="'text_' + $item.id"
            x-bind:value="$item.text"
            class="italic"
          />
        </div>
      </x-demo.task>
    </x-optimistic::added>
  </x-demo.list>
</x-optimistic::injector>
use Capevace\OptimisticUI\WithOptimisticUI;
use Capevace\OptimisticUI\Optimistic;

/**
 * @property-read Collection $todos
 */
class OptimisticPage extends Component
{
    use WithOptimisticUI;

    #[Optimistic(crud: 'create', model: Task::class, injectOptimisticId: true)]
    public function addTask(string $id, string $text): void
    {
        if (!uuid_is_valid($id) || Task::find($id)) {
            return;
        }

        $task = new Task([
            'text' => $text,
        ]);

        $task->id = $id;
        $task->save();
    }

    #[Optimistic(crud: 'delete', model: Task::class)]
    public function deleteTask(string $id): void
    {
        Task::find($id)?->delete();
    }

    #[Optimistic(crud: 'update', model: Task::class)]
    public function editTask(string $id, string $text): void
    {
        Task::find($id)?->update([
            'text' => $text,
        ]);
    }

    #[Computed]
    public function todos(): Collection
    {
        return Task::all();
    }

    public function render(): \Illuminate\View\View
    {
        return view("messages", [
            'todos' => $this->todos,
        ]);
    }
}

Usage

Adding optimistic UI to your Livewire component

You need to wrap your UI with the x-optimistic::injector component. This component will handle the optimistic UI for you.

<x-optimistic::injector class="max-w-lg mx-auto mt-10">
  <!-- Your UI here -->
</x-optimistic::injector>

You can then call your functions optimistically by using the $optimistic object.

<form
  @submit.prevent="
    $optimistic.addTask(text);
    text = '';
  "
>
    <input x-model="text" />
</form>

<!-- OR -->

@foreach($todos as $task)
  <form
    x-data="{ text: $item?.text ?? @js($task['text']) }"  
    @submit.prevent="$optimistic.editTask('{{ $task['id'] }}', text)"
  >
    <input x-model="text" />
  </form>
@endforeach

Displaying the added items

You can use the x-optimistic::added directive to display items that are added optimistically. The component will loop all added items and makes each available in the $item variable.

<x-optimistic::added>
  <x-demo.task
    x-bind:data-id="$item.id"
    x-bind:wire:key="$item.id"
  >
    <div x-text="$item.text"></div>
  </x-demo.task>
</x-optimistic::added>

Optimistic Directives

You can add the x-optimistic directive to inject the optimistic state of a given item. The ID will be inferred from the wire:key attribute or can be passed with x-optimistic="<id>".

<x-demo.task 
    x-optimistic
    x-optimistic.edited.class="italic"
    x-optimistic.removed.remove
>
  <!-- Your task here -->
</x-demo.task>

Optimistic Functions

To add an optimistic function to your Livewire component, you can use the #[Optimistic] attribute.

use Capevace\OptimisticUI\Optimistic;

#[Optimistic(
    fn: "update(params[0], { message: params[1] })"
)] 
public function changeMessage(string $id, string $message): void
{
    Message::find($id)->update([
        'message' => $message,
    ]);
}

The Javascript in the fn parameter will be executed on the client-side when the function is called. The params array contains the parameters passed to the function.

Locally generated IDs

When creating new items, a new UUID will be generated for the item. This ID identifies the item in transit. If you use this ID to actually create the item, you can support interactions with the items in transit, as they will be queued.

To use this feature, set the injectOptimisticId parameter to true.

Locally, you'd still be calling $optimized.addTask(text), but the ID will be injected server-side.

#[Optimistic(
    fn: "create({ text: params[0] })"
    injectOptimisticId: true
)]
public function addTask(string $id, string $text): void
{
    if (!uuid_is_valid($id) || Task::find($id)) {
        return;
    }

    $task = new Task([
        'text' => $text,
    ]);

    $task->id = $id;
    $task->save();
}

Ready-made CRUD functions

The most commonly used functions are implemented out of the box using the crud parameter.

Setting this to create, update, or delete will look at your PHP function's parameters using reflection and automatically generate the Javascript function for you.

You also need to supply the model parameter, which is then used to only allow updates to fillable attributes.

#[Optimistic(crud: 'create', model: Task::class)]
public function addTask(string $id, string $text): void
{
    if (!uuid_is_valid($id) || Task::find($id)) {
        return;
    }

    $task = new Task([
        'text' => $text,
    ]);

    $task->id = $id;
    $task->save();
}

#[Optimistic(crud: 'delete', model: Task::class)]
public function deleteTask(string $id): void
{
    Task::find($id)?->delete();
}

#[Optimistic(crud: 'update', model: Task::class)]
public function editTask(string $id, string $text): void
{
    Task::find($id)?->update([
        'text' => $text,
    ]);
}

Testing

composer test

Changelog

Please see CHANGELOG 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.

capevace/livewire-optimistic-ui 适用场景与选型建议

capevace/livewire-optimistic-ui 是一款 基于 JavaScript 开发的 Composer 扩展包,目前已累计 7 次下载、GitHub Stars 达 7, 最近一次更新时间为 2024 年 06 月 09 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 capevace/livewire-optimistic-ui 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

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

GitHub 信息

  • Stars: 7
  • Watchers: 1
  • Forks: 0
  • 开发语言: JavaScript

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-06-09