mirror of
https://github.com/filamentphp/filament.git
synced 2026-10-31 02:58:53 +08:00
114 lines
3.5 KiB
PHP
114 lines
3.5 KiB
PHP
<?php
|
|
|
|
namespace Filament\Forms\Components;
|
|
|
|
use Filament\Forms\ComponentContainer;
|
|
use Illuminate\Support\Arr;
|
|
use Illuminate\Support\Str;
|
|
|
|
class Repeater extends Field
|
|
{
|
|
protected string $view = 'forms::components.repeater';
|
|
|
|
protected function setUp(): void
|
|
{
|
|
parent::setUp();
|
|
|
|
$this->registerListeners([
|
|
'repeater.createItem' => [
|
|
function (Repeater $component, string $statePath): void {
|
|
if ($component->isDisabled()) {
|
|
return;
|
|
}
|
|
|
|
if ($statePath !== $component->getStatePath()) {
|
|
return;
|
|
}
|
|
|
|
$newUuid = (string) Str::uuid();
|
|
|
|
$livewire = $component->getLivewire();
|
|
data_set($livewire, "{$statePath}.{$newUuid}", []);
|
|
|
|
$component->hydrateDefaultItemState($newUuid);
|
|
},
|
|
],
|
|
'repeater.deleteItem' => [
|
|
function (Repeater $component, string $statePath, string $uuidToDelete): void {
|
|
if ($component->isDisabled()) {
|
|
return;
|
|
}
|
|
|
|
if ($statePath !== $component->getStatePath()) {
|
|
return;
|
|
}
|
|
|
|
$items = $component->getNormalisedState();
|
|
|
|
unset($items[$uuidToDelete]);
|
|
|
|
$livewire = $component->getLivewire();
|
|
data_set($livewire, $statePath, $items);
|
|
},
|
|
],
|
|
'repeater.moveItemDown' => [
|
|
function (Repeater $component, string $statePath, string $uuidToMoveDown): void {
|
|
if ($component->isDisabled()) {
|
|
return;
|
|
}
|
|
|
|
if ($statePath !== $component->getStatePath()) {
|
|
return;
|
|
}
|
|
|
|
$items = Arr::moveElementAfter($component->getNormalisedState(), $uuidToMoveDown);
|
|
|
|
$livewire = $component->getLivewire();
|
|
data_set($livewire, $statePath, $items);
|
|
},
|
|
],
|
|
'repeater.moveItemUp' => [
|
|
function (Repeater $component, string $statePath, string $uuidToMoveUp): void {
|
|
if ($component->isDisabled()) {
|
|
return;
|
|
}
|
|
|
|
if ($statePath !== $component->getStatePath()) {
|
|
return;
|
|
}
|
|
|
|
$items = Arr::moveElementBefore($component->getNormalisedState(), $uuidToMoveUp);
|
|
|
|
$livewire = $component->getLivewire();
|
|
data_set($livewire, $statePath, $items);
|
|
},
|
|
],
|
|
]);
|
|
}
|
|
|
|
public function hydrateDefaultItemState(string $uuid): void
|
|
{
|
|
$this->getChildComponentContainers()[$uuid]->hydrateDefaultState();
|
|
}
|
|
|
|
public function getChildComponentContainers(): array
|
|
{
|
|
return collect($this->getNormalisedState())
|
|
->map(function ($item, $index): ComponentContainer {
|
|
return $this
|
|
->getChildComponentContainer()
|
|
->getClone()
|
|
->statePath($index);
|
|
})->toArray();
|
|
}
|
|
|
|
public function getNormalisedState(): array
|
|
{
|
|
if (! is_array($state = $this->getState())) {
|
|
return [];
|
|
}
|
|
|
|
return array_filter($state, fn ($item) => is_array($item));
|
|
}
|
|
}
|