Phase 0: Fundament für Inhaus
Some checks failed
CI / PHP 8.3 / mariadb:10.6 (pull_request) Successful in 1m14s
CI / PHP 8.4 / mariadb:10.6 (pull_request) Successful in 1m12s
CI / PHP 8.4 / mariadb:11.4 (pull_request) Successful in 1m7s
CI / PHP 8.3 / mariadb:11.4 (pull_request) Successful in 1m19s
CI / PHP 8.3 / mysql:8.0 (pull_request) Successful in 1m32s
CI / PHP 8.4 / mysql:8.0 (pull_request) Successful in 1m22s
CI / PHP 8.4 / mysql:8.4 (pull_request) Successful in 1m32s
CI / PHP 8.3 / mysql:8.4 (pull_request) Successful in 1m35s
CI / Build-Artefakte aktuell (pull_request) Failing after 1m7s

- Laravel 13 mit Filament 5 (Admin), Inertia 3 + Vue 3 + Vuetify 4 (Material 3)
- Anmeldung über Fortify (Login, Passwort vergessen/ändern), keine Selbstregistrierung
- Profil mit Profilbild (WebP in festen Größen), Personenseiten, Header mit Avatar-Menü
- Material-3-Farbschema aus der Primärfarbe, hell/dunkel/System pro Person
- Basis-Branding (Portalname, Logo, Primärfarbe) im Admin unter „Erscheinungsbild“
- Benutzerverwaltung im Admin, Zugang vorläufig über is_admin
- vendor/ (ohne Dev-Pakete) und Frontend-Build mitversioniert, Dev-Pakete in vendor-dev/
- PHPUnit-Tests gegen MySQL/MariaDB, Forgejo-CI-Matrix, Docker-Entwicklungsumgebung
- VERSION, CHANGELOG.md und CONTRIBUTING.md mit Release-Ablauf

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Friederich Loheide 2026-09-25 20:35:30 +00:00
parent 7197eaebf2
commit 9c0f8de791
15771 changed files with 1564103 additions and 5 deletions

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,102 @@
<?php
namespace Filament\Forms\Components\Builder;
use BackedEnum;
use Closure;
use Filament\Forms\Components\Concerns;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Concerns\HasLabel;
use Filament\Schemas\Components\Concerns\HasName;
use Illuminate\Contracts\Support\Htmlable;
use InvalidArgumentException;
class Block extends Component
{
use Concerns\HasPreview;
use HasLabel {
getLabel as getBaseLabel;
}
use HasName;
protected string | BackedEnum | Htmlable | Closure | null $icon = null;
protected int | Closure | null $maxItems = null;
final public function __construct(string $name)
{
$this->name($name);
}
public static function make(?string $name = null): static
{
$blockClass = static::class;
$name ??= static::getDefaultName();
if (blank($name)) {
throw new InvalidArgumentException("Block of class [$blockClass] must have a unique name, passed to the [make()] method.");
}
$static = app($blockClass, ['name' => $name]);
$static->configure();
return $static;
}
public static function getDefaultName(): ?string
{
return null;
}
public function icon(string | BackedEnum | Htmlable | Closure | null $icon): static
{
$this->icon = $icon;
return $this;
}
public function getIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->icon);
}
public function maxItems(int | Closure | null $maxItems): static
{
$this->maxItems = $maxItems;
return $this;
}
public function getMaxItems(): ?int
{
return $this->evaluate($this->maxItems);
}
/**
* @param array<string, mixed> | null $state
*/
public function getLabel(?array $state = null, ?string $key = null, ?int $index = null): string | Htmlable
{
$label = $this->evaluate(
$this->label,
['index' => $index, 'key' => $key, 'state' => $state, 'uuid' => $key],
);
if (blank($label) && filled($label = $this->getBaseLabel())) {
return $label;
}
if (blank($label)) {
$label = (string) str($this->getName())
->afterLast('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
}
return (is_string($label) && $this->shouldTranslateLabel) ?
__($label) :
$label;
}
}

View file

@ -0,0 +1,78 @@
<?php
namespace Filament\Forms\Components;
use Filament\Schemas\Components\StateCasts\BooleanStateCast;
use Filament\Schemas\Components\StateCasts\Contracts\StateCast;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Enums\VerticalAlignment;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\Support\HtmlString;
class Checkbox extends Field implements HasEmbeddedView
{
use Concerns\CanBeAccepted;
use Concerns\CanBeInline;
use Concerns\CanFixIndistinctState;
use Concerns\HasExtraInputAttributes;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.checkbox';
protected function setUp(): void
{
parent::setUp();
$this->default(false);
$this->rule('boolean');
}
public function toEmbeddedHtml(): string
{
$statePath = $this->getStatePath();
$hasError = $this->hasErrorForPath($statePath);
$attributes = (new FilamentComponentAttributeBag)
->merge([
'autofocus' => $this->isAutofocused(),
'disabled' => $this->isDisabled(),
'id' => $this->getId(),
'required' => $this->isRequired(),
'wire:loading.attr' => 'disabled',
$this->applyStateBindingModifiers('wire:model') => $statePath,
], escape: false)
->merge($this->getExtraAttributes(), escape: false)
->merge($this->getExtraInputAttributes(), escape: false)
->class([
'fi-checkbox-input',
'fi-valid' => ! $hasError,
'fi-invalid' => $hasError,
]);
$inputHtml = '<input type="checkbox" ' . $attributes->toHtml() . ' />';
if ($this->isInline()) {
return $this->wrapEmbeddedHtml(
'',
labelPrefix: new HtmlString($inputHtml),
inlineLabelVerticalAlignment: VerticalAlignment::Center,
);
}
return $this->wrapEmbeddedHtml(
$inputHtml,
inlineLabelVerticalAlignment: VerticalAlignment::Center,
);
}
/**
* @return array<StateCast>
*/
public function getDefaultStateCasts(): array
{
return [
...parent::getDefaultStateCasts(),
app(BooleanStateCast::class, ['isNullable' => false]),
];
}
}

View file

@ -0,0 +1,695 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Actions\Action;
use Filament\Forms\View\FormsIconAlias;
use Filament\Schemas\Components\StateCasts\Contracts\StateCast;
use Filament\Schemas\Components\StateCasts\EnumArrayStateCast;
use Filament\Schemas\Components\StateCasts\OptionsArrayStateCast;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Concerns\HasExtraAlpineAttributes;
use Filament\Support\Enums\GridDirection;
use Filament\Support\Enums\Size;
use Filament\Support\Facades\FilamentAsset;
use Filament\Support\Icons\Heroicon;
use Filament\Support\Services\RelationshipJoiner;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Filament\Support\View\Components\InputComponent\WrapperComponent\IconComponent;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Js;
use Illuminate\Support\Str;
use LogicException;
use function Filament\Support\generate_icon_html;
class CheckboxList extends Field implements Contracts\CanDisableOptions, Contracts\HasNestedRecursiveValidationRules, HasEmbeddedView
{
use Concerns\CanAllowHtml;
use Concerns\CanDisableOptions;
use Concerns\CanDisableOptionsWhenSelectedInSiblingRepeaterItems;
use Concerns\CanFixIndistinctState;
use Concerns\CanLimitItemsLength;
use Concerns\HasDescriptions;
use Concerns\HasExtraInputAttributes;
use Concerns\HasGridDirection;
use Concerns\HasNestedRecursiveValidationRules;
use Concerns\HasOptions;
use Concerns\HasPivotData;
use HasExtraAlpineAttributes;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.checkbox-list';
protected bool | Closure | null $isSearchable = false;
protected string | Htmlable | Closure | null $searchPrompt = null;
protected string | Htmlable | Closure | null $noSearchResultsMessage = null;
protected int | Closure $searchDebounce = 0;
protected string | Closure | null $relationshipTitleAttribute = null;
protected ?Closure $getOptionLabelFromRecordUsing = null;
protected ?Closure $getOptionDescriptionFromRecordUsing = null;
protected string | Closure | null $relationship = null;
protected ?Closure $modifyRelationshipQueryUsing = null;
protected bool | Closure $isBulkToggleable = false;
protected ?Closure $modifySelectAllActionUsing = null;
protected ?Closure $modifyDeselectAllActionUsing = null;
protected function setUp(): void
{
parent::setUp();
$this->registerActions([
fn (CheckboxList $component): Action => $component->getSelectAllAction(),
fn (CheckboxList $component): Action => $component->getDeselectAllAction(),
]);
}
public function searchable(bool | Closure | null $condition = true): static
{
$this->isSearchable = $condition;
return $this;
}
public function isSearchable(): bool
{
return (bool) $this->evaluate($this->isSearchable);
}
public function searchPrompt(string | Htmlable | Closure | null $message): static
{
$this->searchPrompt = $message;
return $this;
}
public function getSearchPrompt(): string | Htmlable
{
return $this->evaluate($this->searchPrompt) ?? __('filament-forms::components.select.search_prompt');
}
public function noSearchResultsMessage(string | Htmlable | Closure | null $message): static
{
$this->noSearchResultsMessage = $message;
return $this;
}
public function getNoSearchResultsMessage(): string | Htmlable
{
return $this->evaluate($this->noSearchResultsMessage) ?? __('filament-forms::components.select.no_search_results_message');
}
public function searchDebounce(int | Closure $debounce): static
{
$this->searchDebounce = $debounce;
return $this;
}
public function getSearchDebounce(): int
{
return $this->evaluate($this->searchDebounce);
}
public function getSelectAllAction(): Action
{
$action = Action::make($this->getSelectAllActionName())
->label(__('filament-forms::components.checkbox_list.actions.select_all.label'))
->livewireClickHandlerEnabled(false)
->link()
->size(Size::Small);
if ($this->modifySelectAllActionUsing) {
$action = $this->evaluate($this->modifySelectAllActionUsing, [
'action' => $action,
]) ?? $action;
}
return $action;
}
public function selectAllAction(?Closure $callback): static
{
$this->modifySelectAllActionUsing = $callback;
return $this;
}
public function getSelectAllActionName(): string
{
return 'selectAll';
}
public function getDeselectAllAction(): Action
{
$action = Action::make($this->getDeselectAllActionName())
->label(__('filament-forms::components.checkbox_list.actions.deselect_all.label'))
->livewireClickHandlerEnabled(false)
->link()
->size(Size::Small);
if ($this->modifyDeselectAllActionUsing) {
$action = $this->evaluate($this->modifyDeselectAllActionUsing, [
'action' => $action,
]) ?? $action;
}
return $action;
}
public function deselectAllAction(?Closure $callback): static
{
$this->modifyDeselectAllActionUsing = $callback;
return $this;
}
public function getDeselectAllActionName(): string
{
return 'deselectAll';
}
public function relationship(string | Closure | null $name = null, string | Closure | null $titleAttribute = null, ?Closure $modifyQueryUsing = null): static
{
$this->relationship = $name ?? $this->getName();
$this->relationshipTitleAttribute = $titleAttribute;
$this->modifyRelationshipQueryUsing = $modifyQueryUsing;
$cachedRecords = null;
$cachedOptions = null;
$this->options(static function (CheckboxList $component) use ($modifyQueryUsing, &$cachedRecords, &$cachedOptions): array {
$relationship = Relation::noConstraints(fn () => $component->getRelationship());
if ($component->hasOptionLabelFromRecordUsingCallback() || $component->hasOptionDescriptionFromRecordUsingCallback()) {
if (
(! $modifyQueryUsing) &&
($cachedRecords !== null)
) {
$records = $cachedRecords;
} else {
$relationshipQuery = app(RelationshipJoiner::class)->prepareQueryForNoConstraints($relationship);
if ($modifyQueryUsing) {
$relationshipQuery = $component->evaluate($modifyQueryUsing, [
'query' => $relationshipQuery,
]) ?? $relationshipQuery;
}
$records = $relationshipQuery->get();
if (! $modifyQueryUsing) {
$cachedRecords = $records;
}
}
if ($component->hasOptionDescriptionFromRecordUsingCallback()) {
$descriptions = $records
->mapWithKeys(static fn (Model $record) => [
$record->{Str::afterLast($relationship->getQualifiedRelatedKeyName(), '.')} => $component->getOptionDescriptionFromRecord($record),
])
->toArray();
$component->descriptions($descriptions);
}
if ($component->hasOptionLabelFromRecordUsingCallback()) {
return $records
->mapWithKeys(static fn (Model $record) => [
$record->{Str::afterLast($relationship->getQualifiedRelatedKeyName(), '.')} => $component->getOptionLabelFromRecord($record),
])
->toArray();
}
}
if (
(! $modifyQueryUsing) &&
($cachedOptions !== null)
) {
return $cachedOptions;
}
$relationshipQuery = app(RelationshipJoiner::class)->prepareQueryForNoConstraints($relationship);
if ($modifyQueryUsing) {
$relationshipQuery = $component->evaluate($modifyQueryUsing, [
'query' => $relationshipQuery,
]) ?? $relationshipQuery;
}
$relationshipTitleAttribute = $component->getRelationshipTitleAttribute();
if (empty($relationshipQuery->getQuery()->orders)) {
$relationshipOrderByAttribute = $relationshipTitleAttribute;
if (str_contains($relationshipOrderByAttribute, ' as ')) {
$relationshipOrderByAttribute = (string) str($relationshipOrderByAttribute)->before(' as ');
}
$relationshipQuery->orderBy($relationshipQuery->qualifyColumn($relationshipOrderByAttribute));
}
if (str_contains($relationshipTitleAttribute, '->')) {
if (! str_contains($relationshipTitleAttribute, ' as ')) {
$relationshipTitleAttribute .= " as {$relationshipTitleAttribute}";
}
} else {
$relationshipTitleAttribute = $relationshipQuery->qualifyColumn($relationshipTitleAttribute);
}
$options = $relationshipQuery
->pluck($relationshipTitleAttribute, $relationship->getQualifiedRelatedKeyName())
->toArray();
if (! $modifyQueryUsing) {
$cachedOptions = $options;
}
return $options;
});
$this->loadStateFromRelationshipsUsing(static function (CheckboxList $component): void {
$component->fillStateFromRelationship();
});
$this->saveRelationshipsUsing(static function (CheckboxList $component): void {
$component->saveStateToRelationship();
});
$this->dehydrated(false);
return $this;
}
public function fillStateFromRelationship(): void
{
$relationship = $this->getRelationship();
$relationshipName = $this->getRelationshipName();
if (
(! $this->modifyRelationshipQueryUsing) &&
($record = $this->getRecord()) instanceof Model &&
$record->relationLoaded($relationshipName)
) {
/** @var Collection $relatedRecords */
$relatedRecords = $record->getRelationValue($relationshipName);
$this->state(
$relatedRecords
->pluck($relationship->getRelatedKeyName())
->map(static fn ($key): string => strval($key))
->all(),
);
return;
}
if ($this->modifyRelationshipQueryUsing) {
$this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $relationship->getQuery(),
]);
}
/** @var Collection $relatedRecords */
$relatedRecords = $relationship->getResults();
$this->state(
// Cast the related keys to a string, otherwise Livewire does not
// know how to handle deselection.
//
// https://github.com/filamentphp/filament/issues/1111
$relatedRecords
->pluck($relationship->getRelatedKeyName())
->map(static fn ($key): string => strval($key))
->all(),
);
}
public function saveStateToRelationship(): void
{
$relationship = $this->getRelationship();
$record = $this->getRecord();
$relationshipName = $this->getRelationshipName();
if ($this->modifyRelationshipQueryUsing) {
$this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $relationship->getQuery(),
]);
}
/** @var Collection $relatedRecords */
$relatedRecords = $relationship->getResults();
$state = $this->getState() ?? [];
$recordsToDetach = array_diff(
$relatedRecords
->pluck($relationship->getRelatedKeyName())
->map(static fn ($key): string => strval($key))
->all(),
$state,
);
if (count($recordsToDetach) > 0) {
$relationship->detach($recordsToDetach);
}
$pivotData = $this->getPivotData();
if ($pivotData === []) {
$relationship->sync($state, detaching: false);
$record->unsetRelation($relationshipName);
return;
}
$relationship->syncWithPivotValues($state, $pivotData, detaching: false);
$record->unsetRelation($relationshipName);
}
public function bulkToggleable(bool | Closure $condition = true): static
{
$this->isBulkToggleable = $condition;
return $this;
}
public function getOptionLabelFromRecordUsing(?Closure $callback): static
{
$this->getOptionLabelFromRecordUsing = $callback;
return $this;
}
public function hasOptionLabelFromRecordUsingCallback(): bool
{
return $this->getOptionLabelFromRecordUsing !== null;
}
public function getOptionLabelFromRecord(Model $record): string | Htmlable
{
return $this->evaluate(
$this->getOptionLabelFromRecordUsing,
namedInjections: [
'record' => $record,
],
typedInjections: [
Model::class => $record,
$record::class => $record,
],
);
}
public function getOptionDescriptionFromRecordUsing(?Closure $callback): static
{
$this->getOptionDescriptionFromRecordUsing = $callback;
return $this;
}
public function hasOptionDescriptionFromRecordUsingCallback(): bool
{
return $this->getOptionDescriptionFromRecordUsing !== null;
}
public function getOptionDescriptionFromRecord(Model $record): string | Htmlable | null
{
return $this->evaluate(
$this->getOptionDescriptionFromRecordUsing,
namedInjections: [
'record' => $record,
],
typedInjections: [
Model::class => $record,
$record::class => $record,
],
);
}
public function getRelationshipTitleAttribute(): ?string
{
return $this->evaluate($this->relationshipTitleAttribute);
}
public function getLabel(): string | Htmlable | null
{
if ($this->label === null && $this->getRelationship()) {
$label = (string) str($this->getRelationshipName())
->before('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
return ($this->shouldTranslateLabel) ? __($label) : $label;
}
return parent::getLabel();
}
public function getRelationship(): ?BelongsToMany
{
$name = $this->getRelationshipName();
if (blank($name)) {
return null;
}
$record = $this->getModelInstance();
if ($record->hasAttribute($name) || (! $record->isRelation($name))) {
throw new LogicException("The relationship [{$name}] does not exist on the model [{$this->getModel()}].");
}
return $record->{$name}();
}
public function getRelationshipName(): ?string
{
return $this->evaluate($this->relationship);
}
public function isBulkToggleable(): bool
{
return (bool) $this->evaluate($this->isBulkToggleable);
}
public function getEnumDefaultStateCast(): ?StateCast
{
$enum = $this->getEnum();
if (blank($enum)) {
return null;
}
return app(
EnumArrayStateCast::class,
['enum' => $enum],
);
}
/**
* @return array<StateCast>
*/
public function getDefaultStateCasts(): array
{
if ($this->hasCustomStateCasts() || filled($this->getEnum())) {
return parent::getDefaultStateCasts();
}
return [app(OptionsArrayStateCast::class)];
}
/**
* @return ?array<string>
*/
public function getInValidationRuleValues(): ?array
{
$values = parent::getInValidationRuleValues();
if ($values !== null) {
return $values;
}
return array_keys($this->getEnabledOptions());
}
public function hasInValidationOnMultipleValues(): bool
{
return true;
}
public function toEmbeddedHtml(): string
{
$extraInputAttributeBag = $this->getExtraInputAttributeBag();
$id = $this->getId();
$isHtmlAllowed = $this->isHtmlAllowed();
$gridDirection = $this->getGridDirection() ?? GridDirection::Column;
$isBulkToggleable = $this->isBulkToggleable();
$isDisabled = $this->isDisabled();
$isSearchable = $this->isSearchable();
$statePath = $this->getStatePath();
$options = $this->getOptions();
$livewireKey = $this->getLivewireKey();
$wireModelAttribute = $this->applyStateBindingModifiers('wire:model');
$hasError = $this->hasErrorForPath($statePath);
$optionsAttributes = $this->getExtraAttributeBag()
->grid($this->getColumns(), $gridDirection)
->merge([
'x-show' => $isSearchable ? 'visibleCheckboxListOptions.length' : null,
], escape: false)
->class(['fi-fo-checkbox-list-options']);
ob_start(); ?>
<div
aria-labelledby="<?= e($id) ?>-label"
role="group"
x-load
x-load-src="<?= e(FilamentAsset::getAlpineComponentSrc('checkbox-list', 'filament/forms')) ?>"
x-data="checkboxListFormComponent({
livewireId: <?= Js::from($this->getLivewire()->getId()) ?>,
})"
<?= $this->getExtraAlpineAttributeBag()->class(['fi-fo-checkbox-list'])->toHtml() ?>
>
<?php if (! $isDisabled) { ?>
<?php if ($isSearchable) { ?>
<div <?= (new FilamentComponentAttributeBag)->class(['fi-input-wrp', 'fi-fo-checkbox-list-search-input-wrp'])->toHtml() ?>>
<div class="fi-input-wrp-prefix fi-input-wrp-prefix-has-content fi-inline">
<?= generate_icon_html(
Heroicon::MagnifyingGlass,
FormsIconAlias::COMPONENTS_CHECKBOX_LIST_SEARCH_FIELD,
(new FilamentComponentAttributeBag)->color(IconComponent::class, 'gray'),
)?->toHtml() ?>
</div>
<div class="fi-input-wrp-content-ctn">
<input
aria-label="<?= e($this->getSearchPrompt()) ?>"
placeholder="<?= e($this->getSearchPrompt()) ?>"
type="search"
x-model.debounce.<?= $this->getSearchDebounce() ?>="search"
class="fi-input fi-input-has-inline-prefix"
/>
</div>
</div>
<?php } ?>
<?php if ($isBulkToggleable && count($options)) { ?>
<div
x-cloak
class="fi-fo-checkbox-list-actions"
wire:key="<?= e($livewireKey) ?>.actions"
>
<span
x-show="! areAllCheckboxesChecked"
x-on:click="toggleAllCheckboxes()"
wire:key="<?= e($livewireKey) ?>.actions.select-all"
>
<?= $this->getAction('selectAll')->toHtml() ?>
</span>
<span
x-show="areAllCheckboxesChecked"
x-on:click="toggleAllCheckboxes()"
wire:key="<?= e($livewireKey) ?>.actions.deselect-all"
>
<?= $this->getAction('deselectAll')->toHtml() ?>
</span>
</div>
<?php } ?>
<?php } ?>
<div <?= $optionsAttributes->toHtml() ?>>
<?php if (count($options)) { ?>
<?php foreach ($options as $value => $label) { ?>
<div
wire:key="<?= e($livewireKey) ?>.options.<?= e($value) ?>"
<?php if ($isSearchable) { ?>
x-show="
$el
.querySelector('.fi-fo-checkbox-list-option-label')
?.innerText.toLowerCase()
.includes(search.toLowerCase()) ||
$el
.querySelector('.fi-fo-checkbox-list-option-description')
?.innerText.toLowerCase()
.includes(search.toLowerCase())
"
<?php } ?>
class="fi-fo-checkbox-list-option-ctn"
>
<label class="fi-fo-checkbox-list-option">
<input
type="checkbox"
<?= $extraInputAttributeBag
->merge([
'disabled' => $isDisabled || $this->isOptionDisabled($value, $label),
'value' => e($value),
'wire:loading.attr' => 'disabled',
$wireModelAttribute => $statePath,
'x-on:change' => $isBulkToggleable ? 'checkIfAllCheckboxesAreChecked()' : null,
], escape: false)
->class([
'fi-checkbox-input',
'fi-valid' => ! $hasError,
'fi-invalid' => $hasError,
])
->toHtml() ?>
/>
<div class="fi-fo-checkbox-list-option-text">
<span class="fi-fo-checkbox-list-option-label">
<?php if ($isHtmlAllowed) { ?>
<?= $label ?>
<?php } else { ?>
<?= e($label) ?>
<?php } ?>
</span>
<?php if ($this->hasDescription($value)) { ?>
<p class="fi-fo-checkbox-list-option-description">
<?= e($this->getDescription($value)) ?>
</p>
<?php } ?>
</div>
</label>
</div>
<?php } ?>
<?php } else { ?>
<div wire:key="<?= e($livewireKey) ?>.empty"></div>
<?php } ?>
</div>
<?php if ($isSearchable) { ?>
<div
x-cloak
x-show="search && ! visibleCheckboxListOptions.length"
role="status"
aria-live="polite"
class="fi-fo-checkbox-list-no-search-results-message"
>
<?= e($this->getNoSearchResultsMessage()) ?>
</div>
<?php } ?>
</div>
<?php return $this->wrapEmbeddedHtml(ob_get_clean(), labelTag: 'div');
}
}

View file

@ -0,0 +1,86 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Forms\Components\CodeEditor\Enums\Language;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Concerns\CanWrap;
use Filament\Support\Concerns\HasExtraAlpineAttributes;
use Filament\Support\Facades\FilamentAsset;
use Illuminate\Support\Js;
class CodeEditor extends Field implements HasEmbeddedView
{
use CanWrap;
use HasExtraAlpineAttributes;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.code-editor';
protected Language | Closure | null $language = null;
public function language(Language | Closure | null $language): static
{
$this->language = $language;
return $this;
}
public function getLanguage(): ?Language
{
return $this->evaluate($this->language);
}
public function toEmbeddedHtml(): string
{
$id = $this->getId();
$isDisabled = $this->isDisabled();
$isLive = $this->isLive();
$isLiveOnBlur = $this->isLiveOnBlur();
$isLiveDebounced = $this->isLiveDebounced();
$label = $this->getLabel();
$liveDebounce = $this->getLiveDebounce();
$language = $this->getLanguage();
$statePath = $this->getStatePath();
$livewireKey = $this->getLivewireKey();
$wrapperAttributes = $this->getExtraAttributeBag()
->class(['fi-fo-code-editor']);
ob_start(); ?>
<div
aria-labelledby="<?= e($id) ?>-label"
id="<?= e($id) ?>"
role="group"
x-load
x-load-src="<?= e(FilamentAsset::getAlpineComponentSrc('code-editor', 'filament/forms')) ?>"
x-data="codeEditorFormComponent({
canWrap: <?= Js::from($this->canWrap()) ?>,
isDisabled: <?= Js::from($isDisabled) ?>,
isLive: <?= Js::from($isLive) ?>,
isLiveDebounced: <?= Js::from($isLiveDebounced) ?>,
isLiveOnBlur: <?= Js::from($isLiveOnBlur) ?>,
label: <?= Js::from($label) ?>,
liveDebounce: <?= Js::from($liveDebounce) ?>,
language: <?= Js::from($language?->value) ?>,
state: $wire.<?= $this->applyStateBindingModifiers("\$entangle('{$statePath}')", isOptimisticallyLive: false) ?>,
})"
wire:ignore
wire:key="<?= e($livewireKey) ?>.<?= substr(md5(serialize([$isDisabled, $language?->value])), 0, 64) ?>"
<?= $this->getExtraAlpineAttributeBag()->toHtml() ?>
>
<div x-ref="editor" x-cloak></div>
</div>
<?php $slotHtml = ob_get_clean();
return $this->wrapEmbeddedHtml(
$this->wrapInputHtml(
$slotHtml,
attributes: $wrapperAttributes,
),
labelTag: 'div',
);
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Filament\Forms\Components\CodeEditor\Enums;
enum Language: string
{
case Cpp = 'cpp';
case Css = 'css';
case Go = 'go';
case Html = 'html';
case Java = 'java';
case JavaScript = 'javascript';
case Json = 'json';
case Markdown = 'markdown';
case Php = 'php';
case Python = 'python';
case Sql = 'sql';
case Xml = 'xml';
case Yaml = 'yaml';
}

View file

@ -0,0 +1,197 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Actions\Action;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Concerns\HasExtraAlpineAttributes;
use Filament\Support\Enums\VerticalAlignment;
use Filament\Support\Facades\FilamentAsset;
use Illuminate\Support\Js;
class ColorPicker extends Field implements Contracts\HasAffixes, HasEmbeddedView
{
use Concerns\HasAffixes;
use Concerns\HasExtraInputAttributes;
use Concerns\HasPlaceholder;
use HasExtraAlpineAttributes;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.color-picker';
protected string | Closure $format = 'hex';
public function format(string | Closure $format): static
{
$this->format = $format;
return $this;
}
public function hex(): static
{
$this->format('hex');
return $this;
}
public function hsl(): static
{
$this->format('hsl');
return $this;
}
public function rgb(): static
{
$this->format('rgb');
return $this;
}
public function rgba(): static
{
$this->format('rgba');
return $this;
}
public function getFormat(): string
{
return $this->evaluate($this->format);
}
public function toEmbeddedHtml(): string
{
$extraAttributeBag = $this->getExtraAttributeBag();
$id = $this->getId();
$isAutofocused = $this->isAutofocused();
$isDisabled = $this->isDisabled();
$isLive = $this->isLive();
$isLiveOnBlur = $this->isLiveOnBlur();
$isLiveDebounced = $this->isLiveDebounced();
$isPrefixInline = $this->isPrefixInline();
$isSuffixInline = $this->isSuffixInline();
$liveDebounce = $this->getLiveDebounce();
$prefixActions = $this->getPrefixActions();
$prefixIcon = $this->getPrefixIcon();
$prefixIconColor = $this->getPrefixIconColor();
$prefixLabel = $this->getPrefixLabel();
$suffixActions = $this->getSuffixActions();
$suffixIcon = $this->getSuffixIcon();
$suffixIconColor = $this->getSuffixIconColor();
$suffixLabel = $this->getSuffixLabel();
$statePath = $this->getStatePath();
$placeholder = $this->getPlaceholder();
$livewireKey = $this->getLivewireKey();
$format = $this->getFormat();
// Filter visible prefix/suffix actions
$prefixActions = array_filter(
$prefixActions,
static fn (Action $action): bool => $action->isVisible(),
);
$suffixActions = array_filter(
$suffixActions,
static fn (Action $action): bool => $action->isVisible(),
);
$hasPrefix = count($prefixActions) || $prefixIcon || filled($prefixLabel);
$hasSuffix = count($suffixActions) || $suffixIcon || filled($suffixLabel);
$tag = match ($format) {
'hsl' => 'hsl-string',
'rgb' => 'rgb-string',
'rgba' => 'rgba-string',
default => 'hex',
} . '-color-picker';
$inputAttributes = $this->getExtraInputAttributeBag()
->merge([
// `aria-expanded` / `aria-haspopup` are not supported on a plain textbox, so only
// `aria-controls` (a global ARIA attribute) associates the input with its panel.
'aria-controls' => "{$id}-panel",
'autocomplete' => 'off',
'disabled' => $isDisabled,
'id' => $id,
'placeholder' => filled($placeholder) ? e($placeholder) : null,
'required' => $this->isRequired(),
'type' => 'text',
'x-model' . ($isLiveDebounced ? '.debounce.' . $liveDebounce : null) => 'state',
'x-on:blur' => $isLiveOnBlur ? 'isOpen() ? null : commitState()' : null,
], escape: false)
->class([
'fi-input',
'fi-input-has-inline-prefix' => $isPrefixInline && $hasPrefix,
'fi-input-has-inline-suffix' => $isSuffixInline && $hasSuffix,
]);
$wrapperAttributes = $extraAttributeBag
->merge([
'x-on:focus-input.stop' => "\$el.querySelector('input')?.focus()",
], escape: false)
->class(['fi-fo-color-picker']);
$alpineComponentSrc = FilamentAsset::getAlpineComponentSrc('color-picker', 'filament/forms');
ob_start(); ?>
<div
x-load
x-load-src="<?= e($alpineComponentSrc) ?>"
x-data="colorPickerFormComponent({
isAutofocused: <?= Js::from($isAutofocused) ?>,
isDisabled: <?= Js::from($isDisabled) ?>,
isLive: <?= Js::from($isLive) ?>,
isLiveDebounced: <?= Js::from($isLiveDebounced) ?>,
isLiveOnBlur: <?= Js::from($isLiveOnBlur) ?>,
liveDebounce: <?= Js::from($liveDebounce) ?>,
state: $wire.$entangle('<?= e($statePath) ?>'),
})"
x-on:keydown.esc="isOpen() && $event.stopPropagation()"
x-on:focusout="if (isOpen() && ! $el.contains($event.relatedTarget)) $refs.panel.close()"
<?= $this->getExtraAlpineAttributeBag()->class(['fi-input-wrp-content'])->toHtml() ?>
>
<input
x-on:focus="$refs.panel.open($refs.input)"
x-on:keydown.enter.prevent.stop="togglePanelVisibility()"
x-ref="input"
<?= $inputAttributes->toHtml() ?>
/>
<div
aria-hidden="true"
class="fi-fo-color-picker-preview my-auto me-3 size-5 shrink-0 rounded-full select-none"
x-on:click="togglePanelVisibility()"
x-bind:class="{
'fi-empty': ! state,
}"
x-bind:style="{ 'background-color': state }"
></div>
<div
wire:ignore.self
wire:key="<?= e($livewireKey) ?>.panel"
x-cloak
x-float.placement.bottom-start.offset.flip.shift="{ offset: 8 }"
x-ref="panel"
id="<?= e($id) ?>-panel"
role="dialog"
aria-label="<?= e(__('filament-forms::components.color_picker.panel_label')) ?>"
class="fi-fo-color-picker-panel"
>
<<?= $tag ?> x-ref="picker" color="<?= e($this->getState()) ?>" />
</div>
</div>
<?php $slotHtml = ob_get_clean();
return $this->wrapEmbeddedHtml(
$this->wrapInputHtml(
$slotHtml,
attributes: $wrapperAttributes,
),
inlineLabelVerticalAlignment: VerticalAlignment::Center,
);
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanAllowHtml
{
// Security: Enabling HTML rendering on form components means the content
// will not be escaped. Only enable for trusted content you control —
// never for raw user input without proper sanitization.
protected bool | Closure $isHtmlAllowed = false;
public function allowHtml(bool | Closure $condition = true): static
{
$this->isHtmlAllowed = $condition;
return $this;
}
public function isHtmlAllowed(): bool
{
return (bool) $this->evaluate($this->isHtmlAllowed);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanBeAccepted
{
public function accepted(bool | Closure $condition = true): static
{
$this->rule('accepted', $condition);
return $this;
}
public function declined(bool | Closure $condition = true): static
{
$this->rule('declined', $condition);
return $this;
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Forms\Components\Field;
trait CanBeAutocapitalized
{
protected bool | string | Closure | null $autocapitalize = null;
public function autocapitalize(bool | string | Closure | null $autocapitalize = true): static
{
$this->autocapitalize = $autocapitalize;
return $this;
}
/**
* @deprecated Use `autocapitalize()` instead.
*/
public function disableAutocapitalize(bool | Closure $condition = true): static
{
$this->autocapitalize(static function (Field $component) use ($condition): ?bool {
return $component->evaluate($condition) ? false : null;
});
return $this;
}
public function getAutocapitalize(): ?string
{
return match ($autocapitalize = $this->evaluate($this->autocapitalize)) {
true => 'on',
false => 'off',
default => $autocapitalize,
};
}
}

View file

@ -0,0 +1,39 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Forms\Components\Field;
trait CanBeAutocompleted
{
protected bool | string | Closure | null $autocomplete = null;
public function autocomplete(bool | string | Closure | null $autocomplete = true): static
{
$this->autocomplete = $autocomplete;
return $this;
}
/**
* @deprecated Use `autocomplete()` instead.
*/
public function disableAutocomplete(bool | Closure $condition = true): static
{
$this->autocomplete(static function (Field $component) use ($condition): ?bool {
return $component->evaluate($condition) ? false : null;
});
return $this;
}
public function getAutocomplete(): ?string
{
return match ($autocomplete = $this->evaluate($this->autocomplete)) {
true => 'on',
false => 'off',
default => $autocomplete,
};
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanBeAutofocused
{
protected bool | Closure $isAutofocused = false;
public function autofocus(bool | Closure $condition = true): static
{
$this->isAutofocused = $condition;
return $this;
}
public function isAutofocused(): bool
{
return (bool) $this->evaluate($this->isAutofocused);
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanBeCloned
{
protected bool | Closure $isCloneable = false;
public function cloneable(bool | Closure $condition = true): static
{
$this->isCloneable = $condition;
return $this;
}
public function isCloneable(): bool
{
if ($this->isDisabled()) {
return false;
}
if (filled($this->getMaxItems()) && ($this->getMaxItems() <= $this->getItemsCount())) {
return false;
}
return (bool) $this->evaluate($this->isCloneable);
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanBeInline
{
protected bool | Closure $isInline = true;
public function inline(bool | Closure $condition = true): static
{
$this->isInline = $condition;
return $this;
}
public function isInline(): bool
{
if ($this->hasInlineLabel()) {
return false;
}
return (bool) $this->evaluate($this->isInline);
}
}

View file

@ -0,0 +1,83 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Forms\Components\Contracts\CanHaveNumericState;
trait CanBeLengthConstrained
{
protected int | Closure | null $length = null;
protected int | Closure | null $maxLength = null;
protected int | Closure | null $minLength = null;
public function length(int | Closure | null $length): static
{
$this->length = $length;
$this->maxLength = $length;
$this->minLength = $length;
return $this;
}
public function maxLength(int | Closure | null $length): static
{
$this->maxLength = $length;
return $this;
}
public function minLength(int | Closure | null $length): static
{
$this->minLength = $length;
return $this;
}
public function getLength(): ?int
{
return $this->evaluate($this->length);
}
public function getMaxLength(): ?int
{
return $this->evaluate($this->maxLength);
}
public function getMinLength(): ?int
{
return $this->evaluate($this->minLength);
}
/**
* @return array<string>
*/
public function getLengthValidationRules(): array
{
$isNumeric = $this instanceof CanHaveNumericState && $this->isNumeric();
if (filled($length = $this->getLength())) {
return $isNumeric ?
["digits:{$length}"] :
["size:{$length}"];
}
$rules = [];
if (filled($maxLength = $this->getMaxLength())) {
$rules[] = $isNumeric ?
"max_digits:{$maxLength}" :
"max:{$maxLength}";
}
if (filled($minLength = $this->getMinLength())) {
$rules[] = $isNumeric ?
"min_digits:{$minLength}" :
"min:{$minLength}";
}
return $rules;
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanBeMarkedAsRequired
{
protected bool | Closure | null $isMarkedAsRequired = null;
public function markAsRequired(bool | Closure | null $condition = true): static
{
$this->isMarkedAsRequired = $condition;
return $this;
}
public function isMarkedAsRequired(): bool
{
return $this->evaluate($this->isMarkedAsRequired) ?? $this->isRequired();
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanBeNative
{
protected bool | Closure $isNative = true;
public function native(bool | Closure $condition = true): static
{
$this->isNative = $condition;
return $this;
}
public function isNative(): bool
{
return (bool) $this->evaluate($this->isNative);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanBePreloaded
{
protected bool | Closure $isPreloaded = false;
public function preload(bool | Closure $condition = true): static
{
$this->isPreloaded = $condition;
return $this;
}
public function isPreloaded(): bool
{
return (bool) $this->evaluate($this->isPreloaded);
}
}

View file

@ -0,0 +1,42 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Schemas\Contracts\HasSchemas;
use Illuminate\Support\Arr;
trait CanBeReadOnly
{
protected bool | Closure $isReadOnly = false;
public function readOnly(bool | Closure $condition = true): static
{
$this->isReadOnly = $condition;
return $this;
}
/**
* @param string | array<string> $operations
*/
public function readOnlyOn(string | array $operations): static
{
$this->readOnly(static function (HasSchemas $livewire, string $operation) use ($operations): bool {
foreach (Arr::wrap($operations) as $readOnlyOperation) {
if ($readOnlyOperation === $operation || $livewire instanceof $readOnlyOperation) {
return true;
}
}
return false;
});
return $this;
}
public function isReadOnly(): bool
{
return (bool) $this->evaluate($this->isReadOnly);
}
}

View file

@ -0,0 +1,132 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
trait CanBeSearchable
{
protected bool | Closure | null $isSearchable = null;
protected string | Htmlable | Closure | null $noOptionsMessage = null;
protected string | Htmlable | Closure | null $noSearchResultsMessage = null;
protected int | Closure $searchDebounce = 1000;
protected string | Closure | null $searchingMessage = null;
protected string | Htmlable | Closure | null $searchPrompt = null;
protected bool | Closure $shouldSearchLabels = true;
protected bool | Closure $shouldSearchValues = false;
public function searchable(bool | Closure | null $condition = true): static
{
$this->isSearchable = $condition;
return $this;
}
public function noOptionsMessage(string | Htmlable | Closure | null $message): static
{
$this->noOptionsMessage = $message;
return $this;
}
public function noSearchResultsMessage(string | Htmlable | Closure | null $message): static
{
$this->noSearchResultsMessage = $message;
return $this;
}
public function searchDebounce(int | Closure $debounce): static
{
$this->searchDebounce = $debounce;
return $this;
}
public function searchingMessage(string | Closure | null $message): static
{
$this->searchingMessage = $message;
return $this;
}
public function searchPrompt(string | Htmlable | Closure | null $message): static
{
$this->searchPrompt = $message;
return $this;
}
public function searchLabels(bool | Closure | null $condition = true): static
{
$this->shouldSearchLabels = $condition;
return $this;
}
public function searchValues(bool | Closure | null $condition = true): static
{
$this->shouldSearchValues = $condition;
return $this;
}
public function getNoOptionsMessage(): string | Htmlable
{
return $this->evaluate($this->noOptionsMessage) ?? __('filament-forms::components.select.no_options_message');
}
public function getNoSearchResultsMessage(): string | Htmlable
{
return $this->evaluate($this->noSearchResultsMessage) ?? __('filament-forms::components.select.no_search_results_message');
}
public function getSearchPrompt(): string | Htmlable
{
return $this->evaluate($this->searchPrompt) ?? __('filament-forms::components.select.search_prompt');
}
public function shouldSearchLabels(): bool
{
return (bool) $this->evaluate($this->shouldSearchLabels);
}
public function shouldSearchValues(): bool
{
return (bool) $this->evaluate($this->shouldSearchValues);
}
/**
* @return array<string>
*/
public function getSearchableOptionFields(): array
{
return [
...($this->shouldSearchLabels() ? ['label'] : []),
...($this->shouldSearchValues() ? ['value'] : []),
];
}
public function getSearchDebounce(): int
{
return $this->evaluate($this->searchDebounce);
}
public function getSearchingMessage(): string
{
return $this->evaluate($this->searchingMessage) ?? __('filament-forms::components.select.searching_message');
}
public function isSearchable(): bool
{
return (bool) $this->evaluate($this->isSearchable);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanDisableGrammarly
{
protected bool | Closure $isGrammarlyDisabled = false;
public function disableGrammarly(bool | Closure $condition = true): static
{
$this->isGrammarlyDisabled = $condition;
return $this;
}
public function isGrammarlyDisabled(): bool
{
return (bool) $this->evaluate($this->isGrammarlyDisabled);
}
}

View file

@ -0,0 +1,90 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
use Illuminate\Support\Collection;
trait CanDisableOptions
{
/**
* @var array<bool | Closure>
*/
protected array $isOptionDisabled = [];
public function disableOptionWhen(bool | Closure | null $callback, bool $merge = false): static
{
if ($merge) {
$this->isOptionDisabled[] = $callback;
} else {
$this->isOptionDisabled = Arr::wrap($callback);
}
return $this;
}
/**
* @return array<string>
*/
public function getEnabledOptions(): array
{
return collect($this->getOptions())
->reduce(function (Collection $carry, $label, $value): Collection {
if (is_array($label)) {
foreach ($label as $key => $value) {
$carry->put($key, $value);
}
return $carry;
}
return $carry->put($value, $label);
}, collect())
->when(
$this->hasDisabledOptions(),
fn (Collection $options): Collection => $options->filter(fn ($label, $value) => ! $this->isOptionDisabled($value, $label)),
)
->all();
}
/**
* @param array-key $value
*/
public function isOptionDisabled($value, string | Htmlable $label): bool
{
foreach ($this->isOptionDisabled as $isOptionDisabled) {
if ($this->evaluate($isOptionDisabled, [
'label' => $label,
'value' => $value,
])) {
return true;
}
}
return false;
}
public function hasDisabledOptions(): bool
{
foreach ($this->isOptionDisabled as $isOptionDisabled) {
if ($isOptionDisabled !== false) {
return true;
}
}
return false;
}
public function hasDynamicDisabledOptions(): bool
{
foreach ($this->isOptionDisabled as $isOptionDisabled) {
if ($isOptionDisabled instanceof Closure) {
return true;
}
}
return false;
}
}

View file

@ -0,0 +1,45 @@
<?php
namespace Filament\Forms\Components\Concerns;
use BackedEnum;
use Filament\Forms\Components\Contracts\CanDisableOptions;
use Filament\Schemas\Components\Component;
use Illuminate\Support\Arr;
trait CanDisableOptionsWhenSelectedInSiblingRepeaterItems
{
public function disableOptionsWhenSelectedInSiblingRepeaterItems(): static
{
$this->distinct();
$this->live();
$this->disableOptionWhen(static function (Component & CanDisableOptions $component, string $value, mixed $state) {
$repeater = $component->getParentRepeater();
if (! $repeater) {
return false;
}
return collect($repeater->getRawState())
->pluck(
(string) str($component->getStatePath())
->after("{$repeater->getStatePath()}.")
->after('.'),
)
->flatten()
->map(function (mixed $siblingItemState): mixed {
if ($siblingItemState instanceof BackedEnum) {
return $siblingItemState->value;
}
return $siblingItemState;
})
->diff(Arr::wrap(($state instanceof BackedEnum) ? $state->value : $state))
->filter(fn (mixed $siblingItemState): bool => filled($siblingItemState))
->contains($value);
});
return $this;
}
}

View file

@ -0,0 +1,89 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Utilities\Set;
use Illuminate\Support\Arr;
trait CanFixIndistinctState
{
public function fixIndistinctState(bool | Closure $condition = true): static
{
$this->distinct($condition);
$this->live(condition: $condition);
$this->afterStateUpdated(static function (Component $component, mixed $state, Set $set) use ($condition): void {
if (! $component->evaluate($condition)) {
return;
}
if (blank($state)) {
return;
}
$repeater = $component->getParentRepeater();
if (! $repeater) {
return;
}
$repeaterStatePath = $repeater->getStatePath();
$componentItemStatePath = (string) str($component->getStatePath())
->after("{$repeaterStatePath}.")
->after('.');
$repeaterItemKey = (string) str($component->getStatePath())
->after("{$repeaterStatePath}.")
->beforeLast(".{$componentItemStatePath}");
$repeaterSiblingState = Arr::except($repeater->getRawState(), [$repeaterItemKey]);
if (empty($repeaterSiblingState)) {
return;
}
if (is_array($state)) {
collect($repeaterSiblingState)
->filter(fn (array $itemState): bool => filled(array_intersect(data_get($itemState, $componentItemStatePath, []), $state)))
->map(fn (array $itemState): array => collect(data_get($itemState, $componentItemStatePath) ?? [])
->diff($state)
->values()
->all())
->each(fn (array $newSiblingItemState, string $itemKey) => $set(
path: "{$repeaterStatePath}.{$itemKey}.{$componentItemStatePath}",
state: $newSiblingItemState,
isAbsolute: true,
));
return;
}
collect($repeaterSiblingState)
->map(fn (array $itemState): mixed => data_get($itemState, $componentItemStatePath))
->filter(function (mixed $siblingItemComponentState) use ($state): bool {
if ($siblingItemComponentState === false) {
return false;
}
if (blank($siblingItemComponentState)) {
return false;
}
return $siblingItemComponentState === $state;
})
->each(fn (mixed $siblingItemComponentState, string $itemKey) => $set(
path: "{$repeaterStatePath}.{$itemKey}.{$componentItemStatePath}",
state: match ($siblingItemComponentState) {
true => false,
default => null,
},
isAbsolute: true,
));
});
return $this;
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Illuminate\Support\Str;
trait CanGenerateUuids
{
protected Closure | bool | null $generateUuidUsing = null;
public function generateUuidUsing(Closure | bool | null $callback): static
{
$this->generateUuidUsing = $callback;
return $this;
}
public function generateUuid(): ?string
{
if ($this->generateUuidUsing) {
return $this->evaluate($this->generateUuidUsing);
}
if ($this->generateUuidUsing === false) {
return null;
}
return (string) Str::uuid();
}
public static function fake(): Closure
{
return static::configureUsing(
fn ($component) => $component->generateUuidUsing(false),
);
}
}

View file

@ -0,0 +1,80 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Schemas\Components\Component;
trait CanLimitItemsLength
{
protected int | Closure | null $maxItems = null;
protected int | Closure | null $minItems = null;
public function maxItems(int | Closure | null $count): static
{
$this->maxItems = $count;
$this->rule('array', static function (Component $component): bool {
/** @var static $component */
$count = $component->getMaxItems();
return $count !== null;
});
$this->rule(static function (Component $component): string {
/** @var static $component */
$count = $component->getMaxItems();
return "max:{$count}";
}, static function (Component $component): bool {
/** @var static $component */
$count = $component->getMaxItems();
return $count !== null;
});
return $this;
}
public function minItems(int | Closure | null $count): static
{
$this->minItems = $count;
$this->rule('array', static function (Component $component): bool {
/** @var static $component */
$count = $component->getMinItems();
return $count !== null;
});
$this->rule(static function (Component $component): string {
/** @var static $component */
$count = $component->getMinItems();
return "min:{$count}";
}, static function (Component $component): bool {
/** @var static $component */
$count = $component->getMinItems();
return $count !== null;
});
return $this;
}
public function getMaxItems(): ?int
{
return $this->evaluate($this->maxItems);
}
public function getMinItems(): ?int
{
return $this->evaluate($this->minItems);
}
public function getItemsCount(): int
{
$state = $this->getRawState();
return is_array($state) ? count($state) : 0;
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait CanSelectPlaceholder
{
protected bool | Closure | null $canSelectPlaceholder = true;
public function selectablePlaceholder(bool | Closure $condition = true): static
{
$this->canSelectPlaceholder = $condition;
return $this;
}
/**
* @deprecated Use `selectablePlaceholder()` instead.
*/
public function disablePlaceholderSelection(bool | Closure $condition = true): static
{
$this->selectablePlaceholder(fn (): bool => ! $this->evaluate($condition));
return $this;
}
public function canSelectPlaceholder(): bool
{
return (bool) $this->evaluate($this->canSelectPlaceholder);
}
}

View file

@ -0,0 +1,270 @@
<?php
namespace Filament\Forms\Components\Concerns;
use BackedEnum;
use Closure;
use Filament\Actions\Action;
use Filament\Support\Enums\Size;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
trait HasAffixes
{
/**
* @var array<Action> | null
*/
protected ?array $cachedSuffixActions = null;
/**
* @var array<Action | Closure>
*/
protected array $suffixActions = [];
protected string | Htmlable | Closure | null $suffixLabel = null;
/**
* @var array<Action> | null
*/
protected ?array $cachedPrefixActions = null;
/**
* @var array<Action | Closure>
*/
protected array $prefixActions = [];
protected string | Htmlable | Closure | null $prefixLabel = null;
protected string | BackedEnum | Htmlable | Closure | null $prefixIcon = null;
/**
* @var string | array<string> | Closure | null
*/
protected string | array | Closure | null $prefixIconColor = null;
protected string | BackedEnum | Htmlable | Closure | null $suffixIcon = null;
/**
* @var string | array<string> | Closure | null
*/
protected string | array | Closure | null $suffixIconColor = null;
protected bool | Closure $isPrefixInline = false;
protected bool | Closure $isSuffixInline = false;
public function prefix(string | Htmlable | Closure | null $label, bool | Closure $isInline = false): static
{
$this->prefixLabel = $label;
$this->inlinePrefix($isInline);
return $this;
}
public function postfix(string | Htmlable | Closure | null $label, bool | Closure $isInline = false): static
{
return $this->suffix($label, $isInline);
}
public function prefixAction(Action | Closure $action, bool | Closure $isInline = false): static
{
$this->prefixActions([$action], $isInline);
return $this;
}
/**
* @param array<Action | Closure> $actions
*/
public function prefixActions(array $actions, bool | Closure $isInline = false): static
{
$this->prefixActions = [
...$this->prefixActions,
...$actions,
];
$this->inlinePrefix($isInline);
return $this;
}
public function suffixAction(Action | Closure $action, bool | Closure $isInline = false): static
{
$this->suffixActions([$action], $isInline);
return $this;
}
/**
* @param array<Action | Closure> $actions
*/
public function suffixActions(array $actions, bool | Closure $isInline = false): static
{
$this->suffixActions = [
...$this->suffixActions,
...$actions,
];
$this->inlineSuffix($isInline);
return $this;
}
public function suffix(string | Htmlable | Closure | null $label, bool | Closure $isInline = false): static
{
$this->suffixLabel = $label;
$this->inlineSuffix($isInline);
return $this;
}
public function inlinePrefix(bool | Closure $isInline = true): static
{
$this->isPrefixInline = $isInline;
return $this;
}
public function inlineSuffix(bool | Closure $isInline = true): static
{
$this->isSuffixInline = $isInline;
return $this;
}
public function prefixIcon(string | BackedEnum | Htmlable | Closure | null $icon, bool | Closure $isInline = false): static
{
$this->prefixIcon = $icon;
$this->inlinePrefix($isInline);
return $this;
}
/**
* @param string | array<string> | Closure | null $color
*/
public function prefixIconColor(string | array | Closure | null $color = null): static
{
$this->prefixIconColor = $color;
return $this;
}
public function suffixIcon(string | BackedEnum | Htmlable | Closure | null $icon, bool | Closure $isInline = false): static
{
$this->suffixIcon = $icon;
$this->inlineSuffix($isInline);
return $this;
}
/**
* @param string | array<string> | Closure | null $color
*/
public function suffixIconColor(string | array | Closure | null $color = null): static
{
$this->suffixIconColor = $color;
return $this;
}
/**
* @return array<Action>
*/
public function getPrefixActions(): array
{
return $this->cachedPrefixActions ?? $this->cachePrefixActions();
}
/**
* @return array<Action>
*/
public function cachePrefixActions(): array
{
$this->cachedPrefixActions = [];
foreach ($this->prefixActions as $prefixAction) {
foreach (Arr::wrap($this->evaluate($prefixAction)) as $action) {
$this->cachedPrefixActions[$action->getName()] = $this->prepareAction(
$action
->defaultSize(Size::Small)
->defaultView(Action::ICON_BUTTON_VIEW),
);
}
}
return $this->cachedPrefixActions;
}
/**
* @return array<Action>
*/
public function getSuffixActions(): array
{
return $this->cachedSuffixActions ?? $this->cacheSuffixActions();
}
/**
* @return array<Action>
*/
public function cacheSuffixActions(): array
{
$this->cachedSuffixActions = [];
foreach ($this->suffixActions as $suffixAction) {
foreach (Arr::wrap($this->evaluate($suffixAction)) as $action) {
$this->cachedSuffixActions[$action->getName()] = $this->prepareAction(
$action
->defaultSize(Size::Small)
->defaultView(Action::ICON_BUTTON_VIEW),
);
}
}
return $this->cachedSuffixActions;
}
public function getPrefixLabel(): string | Htmlable | null
{
return $this->evaluate($this->prefixLabel);
}
public function getSuffixLabel(): string | Htmlable | null
{
return $this->evaluate($this->suffixLabel);
}
public function getPrefixIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->prefixIcon);
}
public function getSuffixIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->suffixIcon);
}
/**
* @return string | array<string> | null
*/
public function getPrefixIconColor(): string | array | null
{
return $this->evaluate($this->prefixIconColor);
}
/**
* @return string | array<string> | null
*/
public function getSuffixIconColor(): string | array | null
{
return $this->evaluate($this->suffixIconColor);
}
public function isPrefixInline(): bool
{
return (bool) $this->evaluate($this->isPrefixInline);
}
public function isSuffixInline(): bool
{
return (bool) $this->evaluate($this->isSuffixInline);
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Support\Contracts\HasColor as ColorInterface;
use Illuminate\Contracts\Support\Arrayable;
use UnitEnum;
trait HasColors
{
/**
* @var array<string | array<int | string, string | int> | null> | Arrayable | Closure | null
*/
protected array | Arrayable | Closure | null $colors = null;
/**
* @var array<string | array<int | string, string | int> | null> | null
*/
protected ?array $cachedColors = null;
protected bool $hasCachedColors = false;
/**
* @param array<string | array<int | string, string | int> | null> | Arrayable | Closure | null $colors
*/
public function colors(array | Arrayable | Closure | null $colors): static
{
$this->colors = $colors;
$this->cachedColors = null;
$this->hasCachedColors = false;
return $this;
}
/**
* @return string | array<int | string, string | int> | null
*/
public function getColor(mixed $value): string | array | null
{
return $this->getColors()[$value] ?? null;
}
/**
* @return array<string | array<int | string, string | int> | null>
*/
public function getColors(): array
{
if ($this->hasCachedColors) {
return $this->cachedColors;
}
$colors = $this->evaluate($this->colors);
if ($colors instanceof Arrayable) {
$colors = $colors->toArray();
}
if (
blank($colors) &&
filled($enum = $this->getEnum()) &&
is_a($enum, ColorInterface::class, allow_string: true)
) {
$colors = array_reduce($enum::cases(), function (array $carry, ColorInterface & UnitEnum $case): array {
$carry[$case->value ?? $case->name] = $case->getColor();
return $carry;
}, []);
}
$this->hasCachedColors = true;
return $this->cachedColors = $colors ?? [];
}
}

View file

@ -0,0 +1,38 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Illuminate\Contracts\Support\Arrayable;
trait HasDatalistOptions
{
/**
* @var array<string> | Arrayable | Closure | null
*/
protected array | Arrayable | Closure | null $datalistOptions = null;
/**
* @param array<string> | Arrayable | Closure | null $options
*/
public function datalist(array | Arrayable | Closure | null $options): static
{
$this->datalistOptions = $options;
return $this;
}
/**
* @return array<string> | null
*/
public function getDatalistOptions(): ?array
{
$options = $this->evaluate($this->datalistOptions);
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
return $options;
}
}

View file

@ -0,0 +1,87 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Support\Contracts\HasDescription;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Htmlable;
use UnitEnum;
trait HasDescriptions
{
/**
* @var array<string | Htmlable> | Arrayable | Closure
*/
protected array | Arrayable | Closure $descriptions = [];
/**
* @var ?array<string | Htmlable>
*/
protected ?array $cachedDescriptions = null;
protected bool $hasCachedDescriptions = false;
/**
* @param array<string | Htmlable> | Arrayable | Closure $descriptions
*/
public function descriptions(array | Arrayable | Closure $descriptions): static
{
$this->descriptions = $descriptions;
$this->cachedDescriptions = null;
$this->hasCachedDescriptions = false;
return $this;
}
/**
* @param array-key $value
*/
public function hasDescription($value): bool
{
return array_key_exists($value, $this->getDescriptions());
}
/**
* @param array-key $value
*/
public function getDescription($value): string | Htmlable | null
{
return $this->getDescriptions()[$value] ?? null;
}
/**
* @return array<string | Htmlable>
*/
public function getDescriptions(): array
{
if ($this->hasCachedDescriptions) {
return $this->cachedDescriptions;
}
$descriptions = $this->evaluate($this->descriptions);
if ($descriptions instanceof Arrayable) {
$descriptions = $descriptions->toArray();
}
if (
blank($descriptions) &&
filled($enum = $this->getEnum()) &&
is_a($enum, HasDescription::class, allow_string: true)
) {
$descriptions = array_reduce($enum::cases(), function (array $carry, HasDescription & UnitEnum $case): array {
if (filled($description = $case->getDescription())) {
$carry[$case->value ?? $case->name] = $description;
}
return $carry;
}, []);
}
$this->hasCachedDescriptions = true;
return $this->cachedDescriptions = $descriptions;
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use UnitEnum;
trait HasEnum
{
protected string | Closure | null $enum = null;
public function enum(string | Closure | null $enum): static
{
$this->enum = $enum;
return $this;
}
/**
* @return ?class-string<UnitEnum>
*/
public function getEnum(): ?string
{
return $this->evaluate($this->enum);
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\View\ComponentAttributeBag;
trait HasExtraFieldWrapperAttributes
{
/**
* @var array<array<mixed> | Closure>
*/
protected array $extraFieldWrapperAttributes = [];
/**
* @param array<mixed> | Closure $attributes
*/
public function extraFieldWrapperAttributes(array | Closure $attributes, bool $merge = false): static
{
// Security: Attribute values are not escaped when rendered. Never
// pass unsanitized user input as attribute names or values.
if ($merge) {
if (($attributes instanceof Closure) && in_array($attributes, $this->extraFieldWrapperAttributes, strict: true)) {
return $this;
}
$this->extraFieldWrapperAttributes[] = $attributes;
} else {
$this->extraFieldWrapperAttributes = [$attributes];
}
return $this;
}
/**
* @return array<mixed>
*/
public function getExtraFieldWrapperAttributes(): array
{
$temporaryAttributeBag = new FilamentComponentAttributeBag;
foreach ($this->extraFieldWrapperAttributes as $extraFieldWrapperAttributes) {
$temporaryAttributeBag = $temporaryAttributeBag->merge($this->evaluate($extraFieldWrapperAttributes), escape: false);
}
return $temporaryAttributeBag->getAttributes();
}
public function getExtraFieldWrapperAttributesBag(): ComponentAttributeBag
{
return new FilamentComponentAttributeBag($this->getExtraFieldWrapperAttributes());
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\View\ComponentAttributeBag;
trait HasExtraInputAttributes
{
/**
* @var array<array<mixed> | Closure>
*/
protected array $extraInputAttributes = [];
/**
* @param array<mixed> | Closure $attributes
*/
public function extraInputAttributes(array | Closure $attributes, bool $merge = false): static
{
// Security: Attribute values are not escaped when rendered. Never
// pass unsanitized user input as attribute names or values.
if ($merge) {
if (($attributes instanceof Closure) && in_array($attributes, $this->extraInputAttributes, strict: true)) {
return $this;
}
$this->extraInputAttributes[] = $attributes;
} else {
$this->extraInputAttributes = [$attributes];
}
return $this;
}
/**
* @return array<mixed>
*/
public function getExtraInputAttributes(): array
{
$temporaryAttributeBag = new FilamentComponentAttributeBag;
foreach ($this->extraInputAttributes as $extraInputAttributes) {
$temporaryAttributeBag = $temporaryAttributeBag->merge($this->evaluate($extraInputAttributes), escape: false);
}
return $temporaryAttributeBag->getAttributes();
}
public function getExtraInputAttributeBag(): ComponentAttributeBag
{
return new FilamentComponentAttributeBag($this->getExtraInputAttributes());
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Actions\Action;
use Filament\Support\Enums\Size;
use Illuminate\Support\Arr;
trait HasExtraItemActions
{
/**
* @var array<Action | Closure>
*/
protected array $extraItemActions = [];
/**
* @var array<Action> | null
*/
protected ?array $cachedExtraItemActions = null;
/**
* @param array<Action | Closure> $actions
*/
public function extraItemActions(array $actions): static
{
$this->extraItemActions = [
...$this->extraItemActions,
...$actions,
];
return $this;
}
/**
* @return array<Action>
*/
public function getExtraItemActions(): array
{
return $this->cachedExtraItemActions ?? $this->cacheExtraItemActions();
}
/**
* @return array<Action>
*/
public function cacheExtraItemActions(): array
{
$this->cachedExtraItemActions = [];
foreach ($this->extraItemActions as $extraItemAction) {
foreach (Arr::wrap($this->evaluate($extraItemAction)) as $action) {
$this->cachedExtraItemActions[$action->getName()] = $this->prepareAction(
$action
->defaultColor('gray')
->defaultSize(Size::Small)
->defaultView(Action::ICON_BUTTON_VIEW),
);
}
}
return $this->cachedExtraItemActions;
}
}

View file

@ -0,0 +1,317 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Support\Components\Attributes\ExposedLivewireMethod;
use Illuminate\Contracts\Filesystem\Filesystem;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\ValidationException;
use League\Flysystem\UnableToCheckFileExistence;
use Livewire\Attributes\Renderless;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
use Throwable;
trait HasFileAttachments
{
protected string | Closure | null $fileAttachmentsDirectory = null;
protected string | Closure | null $fileAttachmentsDiskName = null;
protected ?Closure $getFileAttachmentUrlUsing = null;
protected ?Closure $saveUploadedFileAttachmentUsing = null;
protected string | Closure | null $fileAttachmentsVisibility = null;
protected bool | Closure | null $hasFileAttachments = null;
/**
* @var array<string> | Arrayable | Closure | null
*/
protected array | Arrayable | Closure | null $fileAttachmentsAcceptedFileTypes = ['image/png', 'image/jpeg', 'image/gif', 'image/webp'];
protected int | Closure | null $fileAttachmentsMaxSize = 12288;
public function fileAttachmentsDirectory(string | Closure | null $directory): static
{
$this->fileAttachmentsDirectory = $directory;
return $this;
}
public function fileAttachmentsDisk(string | Closure | null $name): static
{
$this->fileAttachmentsDiskName = $name;
return $this;
}
#[ExposedLivewireMethod]
#[Renderless]
public function getUploadedFileAttachmentTemporaryUrl(TemporaryUploadedFile | string | null $attachment = null): ?string
{
return $this->getUploadedFileAttachment($attachment)?->temporaryUrl();
}
public function getUploadedFileAttachment(TemporaryUploadedFile | string | null $attachment = null): ?TemporaryUploadedFile
{
if (is_string($attachment)) {
$attachment = data_get($this->getLivewire(), "componentFileAttachments.{$this->getStatePath()}.{$attachment}");
} elseif (! $attachment) {
$attachment = data_get($this->getLivewire(), "componentFileAttachments.{$this->getStatePath()}");
}
if ($attachment instanceof TemporaryUploadedFile) {
$maxSize = $this->getFileAttachmentsMaxSize();
$acceptedFileTypes = $this->getFileAttachmentsAcceptedFileTypes();
try {
Validator::validate(
['file' => $attachment],
rules: [
'file' => [
'file',
...($maxSize ? ["max:{$maxSize}"] : []),
...($acceptedFileTypes ? ['mimetypes:' . implode(',', $acceptedFileTypes)] : []),
],
],
);
} catch (ValidationException $exception) {
return null;
}
}
return $attachment;
}
public function saveUploadedFileAttachment(TemporaryUploadedFile $file): mixed
{
if (! $this->hasFileAttachments()) {
return null;
}
if ($callback = $this->saveUploadedFileAttachmentUsing) {
return $this->evaluate($callback, [
'file' => $file,
]);
}
if (filled($savedFile = $this->defaultSaveUploadedFileAttachment($file))) {
return $savedFile;
}
$path = $file->store($this->getFileAttachmentsDirectory(), $this->getFileAttachmentsDiskName());
if ($this->getFileAttachmentsVisibility() === 'public') {
rescue(fn () => $this->getFileAttachmentsDisk()->setVisibility($path, 'public'), report: false);
}
return $path;
}
public function defaultSaveUploadedFileAttachment(TemporaryUploadedFile $file): mixed
{
return null;
}
#[ExposedLivewireMethod]
#[Renderless]
public function saveUploadedFileAttachmentAndGetUrl(): ?string
{
$attachment = $this->getUploadedFileAttachment();
if (! $attachment) {
return null;
}
$file = $this->saveUploadedFileAttachment($attachment);
return $this->getFileAttachmentUrl($file);
}
public function fileAttachmentsVisibility(string | Closure | null $visibility): static
{
$this->fileAttachmentsVisibility = $visibility;
return $this;
}
public function getFileAttachmentUrlUsing(?Closure $callback): static
{
$this->getFileAttachmentUrlUsing = $callback;
return $this;
}
/**
* @deprecated Use `getFileAttachmentUrlUsing()` instead.
*/
public function getUploadedAttachmentUrlUsing(?Closure $callback): static
{
$this->getFileAttachmentUrlUsing($callback);
return $this;
}
public function saveUploadedFileAttachmentUsing(?Closure $callback): static
{
$this->saveUploadedFileAttachmentUsing = $callback;
return $this;
}
/**
* @deprecated Use `saveUploadedFileAttachmentUsing()` instead.
*/
public function saveUploadedFileAttachmentsUsing(?Closure $callback): static
{
$this->saveUploadedFileAttachmentUsing($callback);
return $this;
}
public function getFileAttachmentsDirectory(): ?string
{
return $this->evaluate($this->fileAttachmentsDirectory);
}
public function getFileAttachmentsDisk(): Filesystem
{
return Storage::disk($this->getFileAttachmentsDiskName());
}
public function getFileAttachmentsDiskName(): string
{
$name = $this->evaluate($this->fileAttachmentsDiskName) ?? $this->getDefaultFileAttachmentsDiskName();
if (filled($name)) {
return $name;
}
$name = config('filament.default_filesystem_disk');
if ($name !== 'local') {
return $name;
}
if ($this->getFileAttachmentsVisibility() !== 'public') {
return $name;
}
return 'public';
}
public function getDefaultFileAttachmentsDiskName(): ?string
{
return null;
}
public function getFileAttachmentsVisibility(): string
{
return $this->evaluate($this->fileAttachmentsVisibility) ?? $this->getDefaultFileAttachmentsVisibility() ?? 'public';
}
public function getDefaultFileAttachmentsVisibility(): ?string
{
return null;
}
public function getFileAttachmentUrl(mixed $file): ?string
{
if ($this->getFileAttachmentUrlUsing) {
return $this->evaluate($this->getFileAttachmentUrlUsing, [
'file' => $file,
]);
}
if (filled($url = $this->getDefaultFileAttachmentUrl($file))) {
return $url;
}
/** @var FilesystemAdapter $storage */
$storage = $this->getFileAttachmentsDisk();
try {
if (! $storage->exists($file)) {
return null;
}
} catch (UnableToCheckFileExistence $exception) {
return null;
}
if ($this->getFileAttachmentsVisibility() === 'private') {
try {
return $storage->temporaryUrl(
$file,
now()->addMinutes(config('filament.temporary_file_url_expiry_minutes', 30))->endOfHour(),
);
} catch (Throwable $exception) {
// This driver does not support creating temporary URLs.
}
}
return $storage->url($file);
}
public function getDefaultFileAttachmentUrl(mixed $file): ?string
{
return null;
}
/**
* @param array<string> | Arrayable | Closure $types
*/
public function fileAttachmentsAcceptedFileTypes(array | Arrayable | Closure $types): static
{
$this->fileAttachmentsAcceptedFileTypes = $types;
return $this;
}
/**
* @return array<string> | null
*/
public function getFileAttachmentsAcceptedFileTypes(): ?array
{
$types = $this->evaluate($this->fileAttachmentsAcceptedFileTypes);
if ($types instanceof Arrayable) {
$types = $types->toArray();
}
return $types;
}
public function fileAttachmentsMaxSize(int | Closure | null $size): static
{
$this->fileAttachmentsMaxSize = $size;
return $this;
}
public function getFileAttachmentsMaxSize(): ?int
{
return $this->evaluate($this->fileAttachmentsMaxSize);
}
public function fileAttachments(bool | Closure | null $condition): static
{
$this->hasFileAttachments = $condition;
return $this;
}
public function hasFileAttachments(?bool $default = null): bool
{
return $this->evaluate($this->hasFileAttachments) ?? ($default ?? $this->hasFileAttachmentsByDefault());
}
public function hasFileAttachmentsByDefault(): bool
{
return true;
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Support\Enums\GridDirection;
trait HasGridDirection
{
protected GridDirection | string | Closure | null $gridDirection = null;
public function gridDirection(GridDirection | string | Closure | null $gridDirection): static
{
$this->gridDirection = $gridDirection;
return $this;
}
public function getGridDirection(): ?GridDirection
{
$direction = $this->evaluate($this->gridDirection);
if (filled($direction) && (! ($direction instanceof GridDirection))) {
$direction = GridDirection::tryFrom($direction);
}
return $direction;
}
}

View file

@ -0,0 +1,26 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Text;
use Illuminate\Contracts\Support\Htmlable;
trait HasHelperText
{
public function helperText(string | Htmlable | Closure | null $text): static
{
$this->belowContent(function (Component $component) use ($text): ?Text {
$content = $component->evaluate($text);
if (blank($content)) {
return null;
}
return Text::make($content);
});
return $this;
}
}

View file

@ -0,0 +1,190 @@
<?php
namespace Filament\Forms\Components\Concerns;
use BackedEnum;
use Closure;
use Filament\Actions\Action;
use Filament\Forms\Components\Field;
use Filament\Forms\Components\Placeholder;
use Filament\Schemas\Components\Icon;
use Filament\Schemas\Components\Text;
use Illuminate\Contracts\Support\Htmlable;
trait HasHint
{
protected string | Htmlable | Closure | null $hint = null;
/**
* @var array<Action | Closure>
*/
protected array $hintActions = [];
/**
* @var string | array<string> | Closure | null
*/
protected string | array | Closure | null $hintColor = null;
protected string | BackedEnum | Htmlable | Closure | null $hintIcon = null;
protected string | Closure | null $hintIconTooltip = null;
protected function setUpHint(): void
{
$this->afterLabel(function (Field | Placeholder $component): array {
$components = [];
if ($component->hasHint()) {
$components[] = Text::make(static function (Text $component): string | Htmlable | null {
/** @var self $parentComponent */
$parentComponent = $component->getContainer()->getParentComponent();
return $parentComponent->getHint();
})
->color(static function (Text $component): string | array | null {
/** @var self $parentComponent */
$parentComponent = $component->getContainer()->getParentComponent();
return $parentComponent->getHintColor();
})
->visible(static function (Text $component): bool {
/** @var self $parentComponent */
$parentComponent = $component->getContainer()->getParentComponent();
return filled($parentComponent->getHint());
});
}
if ($component->hasHintIcon()) {
$components[] = Icon::make(static function (Icon $component): string | BackedEnum | Htmlable | null {
/** @var self $parentComponent */
$parentComponent = $component->getContainer()->getParentComponent();
return $parentComponent->getHintIcon();
})
->tooltip(static function (Icon $component): ?string {
/** @var self $parentComponent */
$parentComponent = $component->getContainer()->getParentComponent();
return $parentComponent->getHintIconTooltip();
})
->visible(static function (Icon $component): bool {
/** @var self $parentComponent */
$parentComponent = $component->getContainer()->getParentComponent();
return filled($parentComponent->getHintIcon());
})
->color(static function (Icon $component): string | array | null {
/** @var self $parentComponent */
$parentComponent = $component->getContainer()->getParentComponent();
return $parentComponent->getHintColor();
});
}
return [
...$components,
...$component->getHintActions(),
];
});
}
public function hint(string | Htmlable | Closure | null $hint): static
{
$this->hint = $hint;
return $this;
}
/**
* @param string | array<string> | Closure | null $color
*/
public function hintColor(string | array | Closure | null $color): static
{
$this->hintColor = $color;
return $this;
}
public function hintIcon(string | BackedEnum | Htmlable | Closure | null $icon, string | Closure | null $tooltip = null): static
{
$this->hintIcon = $icon;
if (func_num_args() >= 2) {
$this->hintIconTooltip($tooltip);
}
return $this;
}
public function hintIconTooltip(string | Closure | null $tooltip): static
{
$this->hintIconTooltip = $tooltip;
return $this;
}
public function hintAction(Action | Closure $action): static
{
$this->hintActions([$action]);
return $this;
}
/**
* @param array<Action | Closure> $actions
*/
public function hintActions(array $actions): static
{
$this->hintActions = [
...$this->hintActions,
...$actions,
];
return $this;
}
public function hasHint(): bool
{
return filled($this->hint);
}
public function getHint(): string | Htmlable | null
{
return $this->evaluate($this->hint);
}
/**
* @return string | array<string> | null
*/
public function getHintColor(): string | array | null
{
return $this->evaluate($this->hintColor);
}
public function hasHintIcon(): bool
{
return filled($this->hintIcon);
}
public function getHintIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->hintIcon);
}
public function getHintIconTooltip(): ?string
{
return $this->evaluate($this->hintIconTooltip);
}
/**
* @return array<Action>
*/
public function getHintActions(): array
{
return array_filter(array_map(
fn (Action | Closure $hintAction): ?Action => $this->evaluate($hintAction),
$this->hintActions,
));
}
}

View file

@ -0,0 +1,75 @@
<?php
namespace Filament\Forms\Components\Concerns;
use BackedEnum;
use Closure;
use Filament\Support\Contracts\HasIcon as IconInterface;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Htmlable;
use UnitEnum;
trait HasIcons
{
/**
* @var array<string| BackedEnum | Htmlable | null> | Arrayable | Closure | null
*/
protected array | Arrayable | Closure | null $icons = null;
/**
* @var array<string | BackedEnum | Htmlable | null> | null
*/
protected ?array $cachedIcons = null;
protected bool $hasCachedIcons = false;
/**
* @param array<string | BackedEnum | Htmlable | null> | Arrayable | Closure | null $icons
*/
public function icons(array | Arrayable | Closure | null $icons): static
{
$this->icons = $icons;
$this->cachedIcons = null;
$this->hasCachedIcons = false;
return $this;
}
public function getIcon(mixed $value): string | BackedEnum | Htmlable | null
{
return $this->getIcons()[$value] ?? null;
}
/**
* @return array<string | BackedEnum | Htmlable | null>
*/
public function getIcons(): array
{
if ($this->hasCachedIcons) {
return $this->cachedIcons;
}
$icons = $this->evaluate($this->icons);
if ($icons instanceof Arrayable) {
$icons = $icons->toArray();
}
if (
blank($icons) &&
filled($enum = $this->getEnum()) &&
is_a($enum, IconInterface::class, allow_string: true)
) {
$icons = array_reduce($enum::cases(), function (array $carry, IconInterface & UnitEnum $case): array {
$carry[$case->value ?? $case->name] = $case->getIcon();
return $carry;
}, []);
}
$this->hasCachedIcons = true;
return $this->cachedIcons = $icons ?? [];
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasInputMode
{
protected string | Closure | null $inputMode = null;
public function inputMode(string | Closure | null $mode): static
{
$this->inputMode = $mode;
return $this;
}
public function getInputMode(): ?string
{
return $this->evaluate($this->inputMode);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasLoadingMessage
{
protected string | Closure | null $loadingMessage = null;
public function loadingMessage(string | Closure | null $message): static
{
$this->loadingMessage = $message;
return $this;
}
public function getLoadingMessage(): string
{
return $this->evaluate($this->loadingMessage) ?? __('filament-forms::components.select.loading_message');
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasMaxHeight
{
protected string | Closure | null $maxHeight = null;
public function maxHeight(string | Closure | null $height): static
{
$this->maxHeight = $height;
return $this;
}
public function getMaxHeight(): ?string
{
return $this->evaluate($this->maxHeight);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasMinHeight
{
protected string | Closure | null $minHeight = '10rem';
public function minHeight(string | Closure | null $height): static
{
$this->minHeight = $height;
return $this;
}
public function getMinHeight(): ?string
{
return $this->evaluate($this->minHeight);
}
}

View file

@ -0,0 +1,65 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasNestedRecursiveValidationRules
{
/**
* @var array<mixed>
*/
protected array $nestedRecursiveValidationRules = [];
public function nestedRecursiveRule(mixed $rule, bool | Closure $condition = true): static
{
$this->nestedRecursiveValidationRules = [
...$this->nestedRecursiveValidationRules,
[$rule, $condition],
];
return $this;
}
/**
* @param string | array<mixed> $rules
*/
public function nestedRecursiveRules(string | array $rules, bool | Closure $condition = true): static
{
if (is_string($rules)) {
$rules = explode('|', $rules);
}
$this->nestedRecursiveValidationRules = [
...$this->nestedRecursiveValidationRules,
...array_map(static fn (string | object $rule): array => [$rule, $condition], $rules),
];
return $this;
}
/**
* @return array<mixed>
*/
public function getNestedRecursiveValidationRules(): array
{
$rules = [];
foreach ($this->nestedRecursiveValidationRules as [$rule, $condition]) {
if (is_numeric($rule)) {
$rules[] = $this->evaluate($condition);
} elseif ($this->evaluate($condition)) {
$rules[] = $this->evaluate($rule);
}
}
return $rules;
}
public function dehydrateValidationAttributes(array &$attributes): void
{
parent::dehydrateValidationAttributes($attributes);
$attributes["{$this->getStatePath()}.*"] = $this->getValidationAttribute();
}
}

View file

@ -0,0 +1,68 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Filament\Support\Contracts\HasLabel as LabelInterface;
use Illuminate\Contracts\Support\Arrayable;
use UnitEnum;
trait HasOptions
{
/**
* @var array<string | array<string>> | Arrayable | string | Closure | null
*/
protected array | Arrayable | string | Closure | null $options = null;
/**
* @param array<string | array<string>> | Arrayable | string | Closure | null $options
*/
public function options(array | Arrayable | string | Closure | null $options): static
{
$this->options = $options;
if (is_string($options) && enum_exists($options)) {
$this->enum($options);
}
return $this;
}
/**
* @return array<string | array<string>>
*/
public function getOptions(): array
{
$options = $this->evaluate($this->options) ?? $this->getEnum() ?? [];
if (
is_string($options) &&
enum_exists($enum = $options)
) {
if (is_a($enum, LabelInterface::class, allow_string: true)) {
return array_reduce($enum::cases(), function (array $carry, LabelInterface & UnitEnum $case): array {
$carry[$case->value ?? $case->name] = $case->getLabel() ?? $case->name;
return $carry;
}, []);
}
return array_reduce($enum::cases(), function (array $carry, UnitEnum $case): array {
$carry[$case->value ?? $case->name] = $case->name;
return $carry;
}, []);
}
if ($options instanceof Arrayable) {
$options = $options->toArray();
}
return $options;
}
public function hasDynamicOptions(): bool
{
return $this->options instanceof Closure;
}
}

View file

@ -0,0 +1,31 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasPivotData
{
/**
* @var array<string, mixed> | Closure
*/
protected array | Closure $pivotData = [];
/**
* @param array<string, mixed> | Closure $data
*/
public function pivotData(array | Closure $data): static
{
$this->pivotData = $data;
return $this;
}
/**
* @return array<string, mixed>
*/
public function getPivotData(): array
{
return $this->evaluate($this->pivotData) ?? [];
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasPlaceholder
{
protected string | Closure | null $placeholder = null;
public function placeholder(string | Closure | null $placeholder): static
{
$this->placeholder = $placeholder;
return $this;
}
public function getPlaceholder(): ?string
{
return $this->evaluate($this->placeholder);
}
}

View file

@ -0,0 +1,34 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Illuminate\Contracts\View\View;
trait HasPreview
{
protected string | Closure | null $preview = null;
public function preview(string | Closure | null $preview): static
{
$this->preview = $preview;
return $this;
}
public function hasPreview(): bool
{
return (bool) filled($this->evaluate($this->preview));
}
/**
* @param array<string, mixed> $data
*/
public function renderPreview(array $data): View
{
return view(
$this->evaluate($this->preview),
$data,
);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasStep
{
protected int | float | string | Closure | null $step = null;
public function step(int | float | string | Closure | null $interval): static
{
$this->step = $interval;
return $this;
}
public function getStep(): int | float | string | null
{
return $this->evaluate($this->step);
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasToggleColors
{
protected string | Closure | null $offColor = null;
protected string | Closure | null $onColor = null;
public function offColor(string | Closure | null $color): static
{
$this->offColor = $color;
return $this;
}
public function onColor(string | Closure | null $color): static
{
$this->onColor = $color;
return $this;
}
public function getOffColor(): ?string
{
return $this->evaluate($this->offColor);
}
public function getOnColor(): ?string
{
return $this->evaluate($this->onColor);
}
}

View file

@ -0,0 +1,48 @@
<?php
namespace Filament\Forms\Components\Concerns;
use BackedEnum;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
trait HasToggleIcons
{
protected string | BackedEnum | Htmlable | Closure | null $offIcon = null;
protected string | BackedEnum | Htmlable | Closure | null $onIcon = null;
public function offIcon(string | BackedEnum | Htmlable | Closure | null $icon): static
{
$this->offIcon = $icon;
return $this;
}
public function onIcon(string | BackedEnum | Htmlable | Closure | null $icon): static
{
$this->onIcon = $icon;
return $this;
}
public function getOffIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->offIcon);
}
public function getOnIcon(): string | BackedEnum | Htmlable | null
{
return $this->evaluate($this->onIcon);
}
public function hasOffIcon(): bool
{
return (bool) $this->getOffIcon();
}
public function hasOnIcon(): bool
{
return (bool) $this->getOnIcon();
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Illuminate\Contracts\Support\Htmlable;
trait HasTooltips
{
/**
* @var array<string | Htmlable> | Closure | null
*/
protected array | Closure | null $tooltips = null;
/**
* @var ?array<string | Htmlable>
*/
protected ?array $cachedTooltips = null;
protected bool $hasCachedTooltips = false;
/**
* @param array<string | Htmlable> | Closure | null $tooltips
*/
public function tooltips(array | Closure | null $tooltips): static
{
$this->tooltips = $tooltips;
$this->cachedTooltips = null;
$this->hasCachedTooltips = false;
return $this;
}
/**
* @return string | Htmlable | array<string | Htmlable> | null
*/
public function getTooltip(mixed $value): string | Htmlable | array | null
{
return $this->getTooltips()[$value] ?? null;
}
/**
* @return ?array<string | Htmlable>
*/
public function getTooltips(): ?array
{
if ($this->hasCachedTooltips) {
return $this->cachedTooltips;
}
$this->hasCachedTooltips = true;
return $this->cachedTooltips = $this->evaluate($this->tooltips);
}
}

View file

@ -0,0 +1,22 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
trait HasUploadingMessage
{
protected string | Closure | null $uploadingMessage = null;
public function uploadingMessage(string | Closure | null $message): static
{
$this->uploadingMessage = $message;
return $this;
}
public function getUploadingMessage(): string
{
return $this->evaluate($this->uploadingMessage) ?? __('filament::components/button.messages.uploading_file');
}
}

View file

@ -0,0 +1,307 @@
<?php
namespace Filament\Forms\Components\Concerns;
use Closure;
use Exception;
use LogicException;
trait InteractsWithToolbarButtons
{
/**
* @var array<int, string | object | array<int, string | object>> | Closure | null
*/
protected array | Closure | null $toolbarButtons = null;
/**
* @var array<array{type: string, buttons?: array<string>}>
*/
protected array $toolbarButtonsModifications = [];
public function disableAllToolbarButtons(bool $condition = true): static
{
if ($condition) {
$this->toolbarButtonsModifications[] = ['type' => 'disableAll'];
}
return $this;
}
/**
* @param array<string | array<string>> $buttonsToDisable
*/
public function disableToolbarButtons(array $buttonsToDisable = []): static
{
if ($this->toolbarButtons instanceof Closure) {
throw new LogicException('You cannot use the `disableToolbarButtons()` method when the toolbar buttons are dynamically returned from a function. Instead, do not return the disabled buttons from the function.');
}
$this->toolbarButtonsModifications[] = [
'type' => 'disable',
'buttons' => $buttonsToDisable,
];
return $this;
}
/**
* @param array<string | object | array<string | object>> $buttonsToEnable
*/
public function enableToolbarButtons(array $buttonsToEnable = []): static
{
if ($this->toolbarButtons instanceof Closure) {
throw new LogicException('You cannot use the `enableToolbarButtons()` method when the toolbar buttons are dynamically returned from a function. Instead, return the enabled buttons from the function.');
}
$this->toolbarButtonsModifications[] = [
'type' => 'enable',
'buttons' => $buttonsToEnable,
];
return $this;
}
/**
* @param array<int, string | object | array<int, string | object>> | Closure | null $buttons
*/
public function toolbarButtons(array | Closure | null $buttons): static
{
$this->toolbarButtons = $buttons;
$this->toolbarButtonsModifications = [];
return $this;
}
/**
* @return array<array<string | object>>
*/
public function getToolbarButtons(): array
{
$buttons = $this->evaluate($this->toolbarButtons) ?? $this->getDefaultToolbarButtons(); /** @phpstan-ignore method.notFound */
// Extra modifications (e.g. from plugins) are applied first,
// so that user-level modifications always take precedence.
$modifications = [...$this->getExtraToolbarButtonsModifications(), ...$this->toolbarButtonsModifications];
foreach ($modifications as $modification) {
$buttons = match ($modification['type']) {
'disableAll' => [],
'disable' => $this->applyDisableToolbarButtonsModification($buttons, $modification['buttons']),
'enable' => $this->applyEnableToolbarButtonsModification($buttons, $modification['buttons']),
default => throw new Exception('Unknown toolbar buttons modification type: [' . $modification['type'] . '].'),
};
}
// Group consecutive non-array items together; arrays become their own groups
$toolbar = [];
$newButtonGroup = [];
foreach ($buttons as $buttonGroup) {
if (blank($buttonGroup)) {
continue;
}
if (! is_array($buttonGroup)) {
$newButtonGroup[] = $buttonGroup;
continue;
}
if (filled($newButtonGroup)) {
$toolbar[] = $newButtonGroup;
$newButtonGroup = [];
}
if (filled($buttonGroup)) {
$toolbar[] = $buttonGroup;
}
}
if (filled($newButtonGroup)) {
$toolbar[] = $newButtonGroup;
}
return $toolbar;
}
/**
* @param array<int, string | object | array<int, string | object>> $buttons
* @param array<string> $buttonsToDisable
* @return array<int, string | object | array<int, string | object>>
*/
protected function applyDisableToolbarButtonsModification(array $buttons, array $buttonsToDisable): array
{
$modified = [];
foreach ($buttons as $button) {
if (is_object($button)) {
$button = $this->filterDisabledToolbarButtonsFromItem($button, $buttonsToDisable);
if ($button !== null) {
$modified[] = $button;
}
continue;
}
if (is_array($button)) {
$filteredGroup = [];
foreach ($button as $item) {
if (is_object($item)) {
$item = $this->filterDisabledToolbarButtonsFromItem($item, $buttonsToDisable);
if ($item !== null) {
$filteredGroup[] = $item;
}
continue;
}
if (! in_array($item, $buttonsToDisable)) {
$filteredGroup[] = $item;
}
}
if (filled($filteredGroup)) {
$modified[] = $filteredGroup;
}
continue;
}
if (! in_array($button, $buttonsToDisable)) {
$modified[] = $button;
}
}
return $modified;
}
/**
* @param array<string> $buttonsToDisable
*/
protected function filterDisabledToolbarButtonsFromItem(object $item, array $buttonsToDisable): ?object
{
return $item;
}
/**
* @param array<int, string | object | array<int, string | object>> $buttons
* @param array<int, string | object | array<int, string | object>> $buttonsToEnable
* @return array<int, string | object | array<int, string | object>>
*/
protected function applyEnableToolbarButtonsModification(array $buttons, array $buttonsToEnable): array
{
$modified = $buttons;
foreach ($buttonsToEnable as $button) {
if (is_object($button)) {
$modified[] = $button;
continue;
}
if (is_array($button)) {
$filteredGroup = [];
foreach ($button as $item) {
if (is_object($item)) {
$filteredGroup[] = $item;
continue;
}
if ($this->hasToolbarButtonInButtons($modified, $item) || in_array($item, $filteredGroup)) {
continue;
}
$filteredGroup[] = $item;
}
if (filled($filteredGroup)) {
$modified[] = $filteredGroup;
}
continue;
}
if ($this->hasToolbarButtonInButtons($modified, $button)) {
continue;
}
$modified[] = $button;
}
return $modified;
}
/**
* @param array<int, string | object | array<int, string | object>> $buttons
*/
protected function hasToolbarButtonInButtons(array $buttons, string $button): bool
{
foreach ($buttons as $item) {
if (is_array($item)) {
if ($this->hasToolbarButtonInButtons($item, $button)) {
return true;
}
continue;
}
if (is_string($item) && ($item === $button)) {
return true;
}
if (is_object($item) && $this->hasToolbarButtonInItem($item, $button)) {
return true;
}
}
return false;
}
protected function hasToolbarButtonInItem(object $item, string $button): bool
{
return false;
}
/**
* @return array<array{type: string, buttons?: array<string | array<string | array<string>>>}>
*/
protected function getExtraToolbarButtonsModifications(): array
{
return [];
}
/**
* @return array<string | array<string>>
*/
public function getDefaultToolbarButtons(): array
{
return [];
}
/**
* @param string | array<string> $button
*/
public function hasToolbarButton(string | array $button): bool
{
$buttonsToCheck = is_array($button) ? $button : [$button];
$toolbarButtons = $this->getToolbarButtons();
foreach ($buttonsToCheck as $buttonToCheck) {
if ($this->hasToolbarButtonInButtons($toolbarButtons, $buttonToCheck)) {
return true;
}
}
return false;
}
public function hasCustomToolbarButtons(): bool
{
return $this->evaluate($this->toolbarButtons) !== null;
}
}

View file

@ -0,0 +1,17 @@
<?php
namespace Filament\Forms\Components\Contracts;
interface CanBeLengthConstrained
{
public function getLength(): ?int;
public function getMaxLength(): ?int;
public function getMinLength(): ?int;
/**
* @return array<string>
*/
public function getLengthValidationRules(): array;
}

View file

@ -0,0 +1,10 @@
<?php
namespace Filament\Forms\Components\Contracts;
use Closure;
interface CanDisableOptions
{
public function disableOptionWhen(bool | Closure $callback): static;
}

View file

@ -0,0 +1,8 @@
<?php
namespace Filament\Forms\Components\Contracts;
interface CanHaveNumericState
{
public function isNumeric(): bool;
}

View file

@ -0,0 +1,32 @@
<?php
namespace Filament\Forms\Components\Contracts;
use BackedEnum;
use Filament\Schemas\Components\Contracts\HasAffixActions;
use Illuminate\Contracts\Support\Htmlable;
interface HasAffixes extends HasAffixActions
{
public function getPrefixLabel(): string | Htmlable | null;
public function getPrefixIcon(): string | BackedEnum | Htmlable | null;
/**
* @return string | array<string> | null
*/
public function getPrefixIconColor(): string | array | null;
public function getSuffixLabel(): string | Htmlable | null;
public function getSuffixIcon(): string | BackedEnum | Htmlable | null;
/**
* @return string | array<string> | null
*/
public function getSuffixIconColor(): string | array | null;
public function isPrefixInline(): bool;
public function isSuffixInline(): bool;
}

View file

@ -0,0 +1,11 @@
<?php
namespace Filament\Forms\Components\Contracts;
interface HasNestedRecursiveValidationRules
{
/**
* @return array<mixed>
*/
public function getNestedRecursiveValidationRules(): array;
}

View file

@ -0,0 +1,21 @@
<?php
namespace Filament\Forms\Components\Contracts;
interface HasValidationRules
{
/**
* @param array<string, string> $attributes
*/
public function dehydrateValidationAttributes(array &$attributes): void;
/**
* @param array<string, array<string, string>> $messages
*/
public function dehydrateValidationMessages(array &$messages): void;
/**
* @param array<string, array<mixed>> $rules
*/
public function dehydrateValidationRules(array &$rules): void;
}

View file

@ -0,0 +1,11 @@
<?php
namespace Filament\Forms\Components;
class DatePicker extends DateTimePicker
{
public function hasTime(): bool
{
return false;
}
}

View file

@ -0,0 +1,826 @@
<?php
namespace Filament\Forms\Components;
use BackedEnum;
use Carbon\CarbonInterface;
use Carbon\Exceptions\InvalidFormatException;
use Closure;
use DateTime;
use Filament\Actions\Action;
use Filament\Schemas\Components\StateCasts\Contracts\StateCast;
use Filament\Schemas\Components\StateCasts\DateTimeStateCast;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Concerns\HasExtraAlpineAttributes;
use Filament\Support\Enums\VerticalAlignment;
use Filament\Support\Facades\FilamentAsset;
use Filament\Support\Facades\FilamentTimezone;
use Filament\Support\Icons\Heroicon;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\Support\Carbon;
use Illuminate\Support\Js;
use Illuminate\View\ComponentAttributeBag;
class DateTimePicker extends Field implements Contracts\HasAffixes, HasEmbeddedView
{
use Concerns\CanBeNative;
use Concerns\CanBeReadOnly;
use Concerns\HasAffixes;
use Concerns\HasDatalistOptions;
use Concerns\HasExtraInputAttributes;
use Concerns\HasPlaceholder;
use Concerns\HasStep;
use HasExtraAlpineAttributes;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.date-time-picker';
protected string | Closure | null $displayFormat = null;
/**
* @var array<array<mixed> | Closure>
*/
protected array $extraTriggerAttributes = [];
protected ?int $firstDayOfWeek = null;
protected string | Closure | null $format = null;
protected bool | Closure $hasDate = true;
protected bool | Closure $hasSeconds = true;
protected bool | Closure $hasTime = true;
protected bool | Closure $shouldCloseOnDateSelection = false;
protected CarbonInterface | string | Closure | null $maxDate = null;
protected CarbonInterface | string | Closure | null $minDate = null;
protected CarbonInterface | string | Closure | null $defaultFocusedDate = null;
protected string | Closure | null $timezone = null;
protected string | Closure | null $locale = null;
/**
* @var array<DateTime | string> | Closure
*/
protected array | Closure $disabledDates = [];
protected string | Closure $defaultDateDisplayFormat = 'M j, Y';
protected string | Closure $defaultDateTimeDisplayFormat = 'M j, Y H:i';
protected string | Closure $defaultDateTimeWithSecondsDisplayFormat = 'M j, Y H:i:s';
protected string | Closure $defaultTimeDisplayFormat = 'H:i';
protected string | Closure $defaultTimeWithSecondsDisplayFormat = 'H:i:s';
protected int | Closure | null $hoursStep = null;
protected int | Closure | null $minutesStep = null;
protected int | Closure | null $secondsStep = null;
protected function setUp(): void
{
parent::setUp();
$this->rule(
'date',
static fn (DateTimePicker $component): bool => $component->hasDate(),
);
}
public function toEmbeddedHtml(): string
{
$datalistOptions = $this->getDatalistOptions();
$disabledDates = $this->getDisabledDates();
$extraAlpineAttributes = $this->getExtraAlpineAttributes();
$extraAttributeBag = $this->getExtraAttributeBag();
$extraInputAttributeBag = $this->getExtraInputAttributeBag();
$hasDate = $this->hasDate();
$hasTime = $this->hasTime();
$hasSeconds = $this->hasSeconds();
$id = $this->getId();
$isDisabled = $this->isDisabled();
$isAutofocused = $this->isAutofocused();
$isPrefixInline = $this->isPrefixInline();
$isSuffixInline = $this->isSuffixInline();
$maxDate = $this->getMaxDate();
$minDate = $this->getMinDate();
$defaultFocusedDate = $this->getDefaultFocusedDate();
$prefixActions = $this->getPrefixActions();
$prefixIcon = $this->getPrefixIcon();
$prefixIconColor = $this->getPrefixIconColor();
$prefixLabel = $this->getPrefixLabel();
$suffixActions = $this->getSuffixActions();
$suffixIcon = $this->getSuffixIcon();
$suffixIconColor = $this->getSuffixIconColor();
$suffixLabel = $this->getSuffixLabel();
$statePath = $this->getStatePath();
$placeholder = $this->getPlaceholder();
$isReadOnly = $this->isReadOnly();
$isRequired = $this->isRequired();
$step = $this->getStep();
$type = $this->getType();
$livewireKey = $this->getLivewireKey();
$isNative = $this->isNative();
// Mirror the snapshot Blade: the input's inline prefix/suffix classes
// are computed against the unfiltered prefix/suffix actions, while the
// wrapper Blade filtered actions before computing `$hasPrefix` /
// `$hasSuffix` for the prefix/suffix div rendering.
$hasInlinePrefix = count($prefixActions) || $prefixIcon || filled($prefixLabel);
$hasInlineSuffix = count($suffixActions) || $suffixIcon || filled($suffixLabel);
// Filter visible prefix/suffix actions
$prefixActions = array_filter(
$prefixActions,
static fn (Action $action): bool => $action->isVisible(),
);
$suffixActions = array_filter(
$suffixActions,
static fn (Action $action): bool => $action->isVisible(),
);
$hasPrefix = count($prefixActions) || $prefixIcon || filled($prefixLabel);
$hasSuffix = count($suffixActions) || $suffixIcon || filled($suffixLabel);
$wrapperAttributes = $extraAttributeBag
->merge([
'x-on:focus-input.stop' => "\$el.querySelector('input:not([type=hidden])')?.focus()",
], escape: false)
->class(['fi-fo-date-time-picker']);
ob_start(); ?>
<?php if ($isNative) { ?>
<input
<?= $extraInputAttributeBag
->merge($extraAlpineAttributes, escape: false)
->merge([
'autofocus' => $isAutofocused,
'disabled' => $isDisabled,
'id' => $id,
'list' => $datalistOptions ? $id . '-list' : null,
'max' => $hasTime ? $maxDate : ($maxDate ? Carbon::parse($maxDate)->toDateString() : null),
'min' => $hasTime ? $minDate : ($minDate ? Carbon::parse($minDate)->toDateString() : null),
'placeholder' => filled($placeholder) ? e($placeholder) : null,
'readonly' => $isReadOnly,
'required' => $isRequired,
'step' => $step,
'type' => $type,
$this->applyStateBindingModifiers('wire:model') => $statePath,
'x-data' => count($extraAlpineAttributes) ? '{}' : null,
], escape: false)
->class([
'fi-input',
'fi-input-has-inline-prefix' => $isPrefixInline && $hasInlinePrefix,
'fi-input-has-inline-suffix' => $isSuffixInline && $hasInlineSuffix,
])
->toHtml() ?>
/>
<?php } else { ?>
<div
x-load
x-load-src="<?= e(FilamentAsset::getAlpineComponentSrc('date-time-picker', 'filament/forms')) ?>"
x-data="dateTimePickerFormComponent({
defaultFocusedDate: <?= Js::from($defaultFocusedDate) ?>,
displayFormat: <?= Js::from(convert_date_format($this->getDisplayFormat())->to('day.js')) ?>,
firstDayOfWeek: <?= $this->getFirstDayOfWeek() ?>,
isAutofocused: <?= Js::from($isAutofocused) ?>,
locale: <?= Js::from($this->getLocale()) ?>,
shouldCloseOnDateSelection: <?= Js::from($this->shouldCloseOnDateSelection()) ?>,
state: $wire.<?= $this->applyStateBindingModifiers("\$entangle('{$statePath}')") ?>,
})"
wire:ignore
wire:key="<?= e($livewireKey) ?>.<?= substr(md5(serialize([$disabledDates, $isDisabled, $isReadOnly, $maxDate, $minDate, $hasDate, $hasTime, $hasSeconds])), 0, 64) ?>"
x-on:keydown.esc="isOpen() && $event.stopPropagation()"
<?= $this->getExtraAlpineAttributeBag()->toHtml() ?>
>
<input x-ref="maxDate" type="hidden" value="<?= e($maxDate) ?>" />
<input x-ref="minDate" type="hidden" value="<?= e($minDate) ?>" />
<input x-ref="disabledDates" type="hidden" value="<?= e(json_encode($disabledDates)) ?>" />
<button
x-ref="button"
x-on:click="togglePanelVisibility()"
x-on:keydown.enter.prevent.stop="if (! $el.disabled) { isOpen() ? selectDate() : togglePanelVisibility() }"
x-on:keydown.arrow-left.prevent.stop="if (! $el.disabled) focusPreviousDay()"
x-on:keydown.arrow-right.prevent.stop="if (! $el.disabled) focusNextDay()"
x-on:keydown.arrow-up.prevent.stop="if (! $el.disabled) focusPreviousWeek()"
x-on:keydown.arrow-down.prevent.stop="if (! $el.disabled) focusNextWeek()"
x-on:keydown.backspace.prevent.stop="if (! $el.disabled) clearState()"
x-on:keydown.clear.prevent.stop="if (! $el.disabled) clearState()"
x-on:keydown.delete.prevent.stop="if (! $el.disabled) clearState()"
aria-label="<?= e($placeholder) ?>"
type="button"
tabindex="-1"
<?php if ($isDisabled || $isReadOnly) { ?> disabled <?php } ?>
<?= $this->getExtraTriggerAttributeBag()->class(['fi-fo-date-time-picker-trigger'])->toHtml() ?>
>
<input
<?php if ($isDisabled) { ?> disabled <?php } ?>
readonly
placeholder="<?= e($placeholder) ?>"
wire:key="<?= e($livewireKey) ?>.display-text"
x-model="displayText"
<?php if ($id) { ?> id="<?= e($id) ?>" <?php } ?>
class="fi-fo-date-time-picker-display-text-input"
/>
</button>
<div
x-ref="panel"
x-cloak
x-float.placement.bottom-start.offset.flip.shift="{ offset: 8 }"
wire:ignore
wire:key="<?= e($livewireKey) ?>.panel"
class="fi-fo-date-time-picker-panel"
>
<?php if ($hasDate) { ?>
<div class="fi-fo-date-time-picker-panel-header">
<select aria-label="<?= e(__('filament-forms::components.date_time_picker.month_select.label')) ?>" x-model="focusedMonth" class="fi-fo-date-time-picker-month-select">
<template x-for="(month, index) in months">
<option x-bind:value="index" x-text="month"></option>
</template>
</select>
<input type="number" inputmode="numeric" aria-label="<?= e(__('filament-forms::components.date_time_picker.year_input.label')) ?>" x-model.debounce="focusedYear" class="fi-fo-date-time-picker-year-input" />
</div>
<div class="fi-fo-date-time-picker-calendar-header">
<template x-for="(day, index) in dayLabels" x-bind:key="index">
<div x-text="day" class="fi-fo-date-time-picker-calendar-header-day"></div>
</template>
</div>
<div role="grid" class="fi-fo-date-time-picker-calendar">
<template x-for="day in emptyDaysInFocusedMonth" x-bind:key="day">
<div></div>
</template>
<template x-for="day in daysInFocusedMonth" x-bind:key="day">
<div
x-text="day"
x-on:click="dayIsDisabled(day) || selectDate(day)"
x-on:mouseenter="setFocusedDay(day)"
role="option"
x-bind:aria-selected="focusedDate.date() === day"
x-bind:class="{
'fi-fo-date-time-picker-calendar-day-today': dayIsToday(day),
'fi-focused': focusedDate.date() === day,
'fi-selected': dayIsSelected(day),
'fi-disabled': dayIsDisabled(day),
}"
class="fi-fo-date-time-picker-calendar-day"
></div>
</template>
</div>
<?php } ?>
<?php if ($hasTime) { ?>
<div class="fi-fo-date-time-picker-time-inputs">
<input max="23" min="0" step="<?= $this->getHoursStep() ?>" type="number" inputmode="numeric" aria-label="<?= e(__('filament-forms::components.date_time_picker.hour_input.label')) ?>" x-on:blur="checkTimeInputValidity" x-on:invalid="timeInputInvalid" x-model.debounce="hour" />
<span class="fi-fo-date-time-picker-time-input-separator">:</span>
<input max="59" min="0" step="<?= $this->getMinutesStep() ?>" type="number" inputmode="numeric" aria-label="<?= e(__('filament-forms::components.date_time_picker.minute_input.label')) ?>" x-on:blur="checkTimeInputValidity" x-on:invalid="timeInputInvalid" x-model.debounce="minute" />
<?php if ($hasSeconds) { ?>
<span class="fi-fo-date-time-picker-time-input-separator">:</span>
<input max="59" min="0" step="<?= $this->getSecondsStep() ?>" type="number" inputmode="numeric" aria-label="<?= e(__('filament-forms::components.date_time_picker.second_input.label')) ?>" x-on:blur="checkTimeInputValidity" x-on:invalid="timeInputInvalid" x-model.debounce="second" />
<?php } ?>
</div>
<?php } ?>
</div>
</div>
<?php } ?>
<?php if ($datalistOptions) { ?>
<datalist id="<?= e($id) ?>-list">
<?php foreach ($datalistOptions as $option) { ?>
<option value="<?= e($option) ?>" />
<?php } ?>
</datalist>
<?php } ?>
<?php $slotHtml = ob_get_clean();
return $this->wrapEmbeddedHtml(
$this->wrapInputHtml(
$slotHtml,
attributes: $wrapperAttributes,
),
inlineLabelVerticalAlignment: VerticalAlignment::Center,
);
}
/**
* @return array<StateCast>
*/
public function getDefaultStateCasts(): array
{
return [
...parent::getDefaultStateCasts(),
app(DateTimeStateCast::class, [
'format' => $this->getFormat(),
'internalFormat' => $this->getInternalFormat(),
'timezone' => $this->getTimezone(),
]),
];
}
public function getInternalFormat(): string
{
if (! $this->isNative()) {
return 'Y-m-d H:i:s';
}
if (! $this->hasTime()) {
return 'Y-m-d';
}
if (! $this->hasDate()) {
return $this->hasSeconds() ? 'H:i:s' : 'H:i';
}
return $this->hasSeconds() ? 'Y-m-d H:i:s' : 'Y-m-d H:i';
}
public function displayFormat(string | Closure | null $format): static
{
$this->displayFormat = $format;
return $this;
}
/**
* @param array<mixed> | Closure $attributes
*/
public function extraTriggerAttributes(array | Closure $attributes, bool $merge = false): static
{
// Security: Attribute values are not escaped when rendered. Never
// pass unsanitized user input as attribute names or values.
if ($merge) {
if (($attributes instanceof Closure) && in_array($attributes, $this->extraTriggerAttributes, strict: true)) {
return $this;
}
$this->extraTriggerAttributes[] = $attributes;
} else {
$this->extraTriggerAttributes = [$attributes];
}
return $this;
}
public function firstDayOfWeek(?int $day): static
{
if ($day < 0 || $day > 7) {
$day = null;
}
$this->firstDayOfWeek = $day;
return $this;
}
public function format(string | Closure | null $format): static
{
$this->format = $format;
return $this;
}
/**
* @deprecated Use `suffixIcon(Heroicon::Calendar)` instead.
*/
public function icon(string | BackedEnum | bool | null $icon = null): static
{
if ($icon === false) {
return $this;
}
return $this->suffixIcon($icon ?? Heroicon::Calendar, isInline: true);
}
public function maxDate(CarbonInterface | string | Closure | null $date): static
{
$this->maxDate = $date;
$this->rule(static function (DateTimePicker $component) {
return "before_or_equal:{$component->getMaxDate()}";
}, static fn (DateTimePicker $component): bool => (bool) $component->getMaxDate());
return $this;
}
public function minDate(CarbonInterface | string | Closure | null $date): static
{
$this->minDate = $date;
$this->rule(static function (DateTimePicker $component) {
return "after_or_equal:{$component->getMinDate()}";
}, static fn (DateTimePicker $component): bool => (bool) $component->getMinDate());
return $this;
}
public function defaultFocusedDate(CarbonInterface | string | Closure | null $date): static
{
$this->defaultFocusedDate = $date;
return $this;
}
/**
* @param array<DateTime | string> | Closure $dates
*/
public function disabledDates(array | Closure $dates): static
{
$this->disabledDates = $dates;
return $this;
}
public function resetFirstDayOfWeek(): static
{
$this->firstDayOfWeek(null);
return $this;
}
public function hoursStep(int | Closure | null $hoursStep): static
{
$this->hoursStep = $hoursStep;
return $this;
}
public function minutesStep(int | Closure | null $minutesStep): static
{
$this->minutesStep = $minutesStep;
return $this;
}
public function secondsStep(int | Closure | null $secondsStep): static
{
$this->secondsStep = $secondsStep;
return $this;
}
public function timezone(string | Closure | null $timezone): static
{
$this->timezone = $timezone;
return $this;
}
public function locale(string | Closure | null $locale): static
{
$this->locale = $locale;
return $this;
}
public function weekStartsOnMonday(): static
{
$this->firstDayOfWeek(1);
return $this;
}
public function weekStartsOnSunday(): static
{
$this->firstDayOfWeek(7);
return $this;
}
public function date(bool | Closure $condition = true): static
{
$this->hasDate = $condition;
return $this;
}
public function seconds(bool | Closure $condition = true): static
{
$this->hasSeconds = $condition;
return $this;
}
public function time(bool | Closure $condition = true): static
{
$this->hasTime = $condition;
return $this;
}
/**
* @deprecated Use `date()` instead.
*/
public function withoutDate(bool | Closure $condition = true): static
{
$this->date(fn (DateTimePicker $component): bool => ! $component->evaluate($condition));
return $this;
}
/**
* @deprecated Use `seconds()` instead.
*/
public function withoutSeconds(bool | Closure $condition = true): static
{
$this->seconds(fn (DateTimePicker $component): bool => ! $component->evaluate($condition));
return $this;
}
/**
* @deprecated Use `time()` instead.
*/
public function withoutTime(bool | Closure $condition = true): static
{
$this->time(fn (DateTimePicker $component): bool => ! $component->evaluate($condition));
return $this;
}
public function closeOnDateSelection(bool | Closure $condition = true): static
{
$this->shouldCloseOnDateSelection = $condition;
return $this;
}
public function getDisplayFormat(): string
{
$format = $this->evaluate($this->displayFormat);
if ($format) {
return $format;
}
if (! $this->hasTime()) {
return $this->getDefaultDateDisplayFormat();
}
if (! $this->hasDate()) {
return $this->hasSeconds() ?
$this->getDefaultTimeWithSecondsDisplayFormat() :
$this->getDefaultTimeDisplayFormat();
}
return $this->hasSeconds() ?
$this->getDefaultDateTimeWithSecondsDisplayFormat() :
$this->getDefaultDateTimeDisplayFormat();
}
public function defaultDateDisplayFormat(string | Closure $format): static
{
$this->defaultDateDisplayFormat = $format;
return $this;
}
public function defaultDateTimeDisplayFormat(string | Closure $format): static
{
$this->defaultDateTimeDisplayFormat = $format;
return $this;
}
public function defaultDateTimeWithSecondsDisplayFormat(string | Closure $format): static
{
$this->defaultDateTimeWithSecondsDisplayFormat = $format;
return $this;
}
public function defaultTimeDisplayFormat(string | Closure $format): static
{
$this->defaultTimeDisplayFormat = $format;
return $this;
}
public function defaultTimeWithSecondsDisplayFormat(string | Closure $format): static
{
$this->defaultTimeWithSecondsDisplayFormat = $format;
return $this;
}
public function getDefaultDateDisplayFormat(): string
{
return $this->evaluate($this->defaultDateDisplayFormat);
}
public function getDefaultDateTimeDisplayFormat(): string
{
return $this->evaluate($this->defaultDateTimeDisplayFormat);
}
public function getDefaultDateTimeWithSecondsDisplayFormat(): string
{
return $this->evaluate($this->defaultDateTimeWithSecondsDisplayFormat);
}
public function getDefaultTimeDisplayFormat(): string
{
return $this->evaluate($this->defaultTimeDisplayFormat);
}
public function getDefaultTimeWithSecondsDisplayFormat(): string
{
return $this->evaluate($this->defaultTimeWithSecondsDisplayFormat);
}
/**
* @return array<mixed>
*/
public function getExtraTriggerAttributes(): array
{
$temporaryAttributeBag = new FilamentComponentAttributeBag;
foreach ($this->extraTriggerAttributes as $extraTriggerAttributes) {
$temporaryAttributeBag = $temporaryAttributeBag->merge($this->evaluate($extraTriggerAttributes), escape: false);
}
return $temporaryAttributeBag->getAttributes();
}
public function getExtraTriggerAttributeBag(): ComponentAttributeBag
{
return new FilamentComponentAttributeBag($this->getExtraTriggerAttributes());
}
public function getFirstDayOfWeek(): int
{
return $this->firstDayOfWeek ?? 1;
}
public function getFormat(): string
{
$format = $this->evaluate($this->format);
if ($format) {
return $format;
}
$format = $this->hasDate() ? 'Y-m-d' : '';
if (! $this->hasTime()) {
return $format;
}
$format = $format ? "{$format} H:i" : 'H:i';
if (! $this->hasSeconds()) {
return $format;
}
return "{$format}:s";
}
public function getMaxDate(): ?string
{
return $this->evaluate($this->maxDate);
}
public function getMinDate(): ?string
{
return $this->evaluate($this->minDate);
}
public function getDefaultFocusedDate(): ?string
{
$defaultFocusedDate = $this->evaluate($this->defaultFocusedDate);
if (filled($defaultFocusedDate)) {
if (! $defaultFocusedDate instanceof CarbonInterface) {
try {
$defaultFocusedDate = Carbon::createFromFormat($this->getFormat(), (string) $defaultFocusedDate, config('app.timezone'));
} catch (InvalidFormatException $exception) {
try {
$defaultFocusedDate = Carbon::parse($defaultFocusedDate, config('app.timezone'));
} catch (InvalidFormatException $exception) {
return null;
}
}
}
$defaultFocusedDate = $defaultFocusedDate->setTimezone($this->getTimezone());
}
return $defaultFocusedDate;
}
/**
* @return array<DateTime | string>
*/
public function getDisabledDates(): array
{
return $this->evaluate($this->disabledDates);
}
public function getTimezone(): string
{
return $this->evaluate($this->timezone) ?? ($this->hasTime() ? FilamentTimezone::get() : config('app.timezone'));
}
public function getLocale(): string
{
return $this->evaluate($this->locale) ?? config('app.locale');
}
public function hasDate(): bool
{
return (bool) $this->evaluate($this->hasDate);
}
public function hasSeconds(): bool
{
return (bool) $this->evaluate($this->hasSeconds);
}
public function hasTime(): bool
{
return (bool) $this->evaluate($this->hasTime);
}
public function getHoursStep(): int
{
return $this->evaluate($this->hoursStep) ?? 1;
}
public function getMinutesStep(): int
{
return $this->evaluate($this->minutesStep) ?? 1;
}
public function getSecondsStep(): int
{
return $this->evaluate($this->secondsStep) ?? 1;
}
public function shouldCloseOnDateSelection(): bool
{
return (bool) $this->evaluate($this->shouldCloseOnDateSelection);
}
public function getStep(): int | float | string | null
{
$step = $this->evaluate($this->step);
if (filled($step)) {
return $step;
}
if (! $this->hasTime()) {
return null;
}
$secondsStep = $this->getSecondsStep();
if ($secondsStep > 1) {
return $secondsStep;
}
$minutesStep = $this->getMinutesStep();
if ($minutesStep > 1) {
return $minutesStep * 60;
}
$hoursStep = $this->getHoursStep();
if ($hoursStep > 1) {
return $hoursStep * 3600;
}
if (! $this->hasSeconds()) {
return null;
}
return 1;
}
public function getType(): string
{
if (! $this->hasDate()) {
return 'time';
}
if (! $this->hasTime()) {
return 'date';
}
return 'datetime-local';
}
}

View file

@ -0,0 +1,743 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Actions\Action;
use Filament\Actions\ActionGroup;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Concerns\HasLabel;
use Filament\Schemas\Components\Concerns\HasName;
use Filament\Schemas\Components\StateCasts\Contracts\StateCast;
use Filament\Schemas\Components\StateCasts\EnumStateCast;
use Filament\Schemas\Schema;
use Filament\Support\Components\ViewComponent;
use Filament\Support\Enums\Size;
use Filament\Support\Enums\VerticalAlignment;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Filament\Support\View\Components\InputComponent\WrapperComponent\IconComponent;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
use Illuminate\Support\MessageBag;
use Illuminate\Support\Str;
use Illuminate\Support\ViewErrorBag;
use Illuminate\View\ComponentAttributeBag;
use Illuminate\View\ComponentSlot;
use InvalidArgumentException;
use function Filament\Support\generate_icon_html;
use function Filament\Support\generate_loading_indicator_html;
class Field extends Component implements Contracts\HasValidationRules
{
use Concerns\CanBeAutofocused;
use Concerns\CanBeMarkedAsRequired;
use Concerns\CanBeValidated;
use Concerns\HasEnum;
use Concerns\HasExtraFieldWrapperAttributes;
use Concerns\HasHelperText;
use Concerns\HasHint;
use HasLabel {
getLabel as getBaseLabel;
}
use HasName;
protected string $viewIdentifier = 'field';
const ABOVE_LABEL_SCHEMA_KEY = 'above_label';
const BELOW_LABEL_SCHEMA_KEY = 'below_label';
const BEFORE_LABEL_SCHEMA_KEY = 'before_label';
const AFTER_LABEL_SCHEMA_KEY = 'after_label';
const ABOVE_CONTENT_SCHEMA_KEY = 'above_content';
const BELOW_CONTENT_SCHEMA_KEY = 'below_content';
const BEFORE_CONTENT_SCHEMA_KEY = 'before_content';
const AFTER_CONTENT_SCHEMA_KEY = 'after_content';
const ABOVE_ERROR_MESSAGE_SCHEMA_KEY = 'above_error_message';
const BELOW_ERROR_MESSAGE_SCHEMA_KEY = 'below_error_message';
final public function __construct(string $name)
{
$this->name($name);
$this->statePath($name);
}
public static function make(?string $name = null): static
{
$fieldClass = static::class;
$name ??= static::getDefaultName();
if ($name === null) {
throw new InvalidArgumentException("Field of class [$fieldClass] must have a unique name, passed to the [make()] method.");
}
$static = app($fieldClass, ['name' => $name]);
$static->configure();
return $static;
}
protected function setUp(): void
{
parent::setUp();
$this->setUpHint();
}
public static function getDefaultName(): ?string
{
return null;
}
/**
* @return array<StateCast>
*/
public function getDefaultStateCasts(): array
{
$casts = parent::getDefaultStateCasts();
if ($enumStateCast = $this->getEnumDefaultStateCast()) {
$casts[] = $enumStateCast;
}
return $casts;
}
public function getEnumDefaultStateCast(): ?StateCast
{
$enum = $this->getEnum();
if (blank($enum)) {
return null;
}
return app(
EnumStateCast::class,
['enum' => $enum],
);
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function aboveLabel(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::ABOVE_LABEL_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function belowLabel(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::BELOW_LABEL_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function beforeLabel(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::BEFORE_LABEL_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function afterLabel(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::AFTER_LABEL_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function aboveContent(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::ABOVE_CONTENT_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function belowContent(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::BELOW_CONTENT_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function beforeContent(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::BEFORE_CONTENT_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function afterContent(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::AFTER_CONTENT_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function aboveErrorMessage(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::ABOVE_ERROR_MESSAGE_SCHEMA_KEY);
return $this;
}
/**
* @param array<Component | Action | ActionGroup | string | Htmlable> | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components
*/
public function belowErrorMessage(array | Schema | Component | Action | ActionGroup | string | Htmlable | Closure | null $components): static
{
$this->childComponents($components, static::BELOW_ERROR_MESSAGE_SCHEMA_KEY);
return $this;
}
protected function makeChildSchema(string $key): Schema
{
$schema = parent::makeChildSchema($key);
if (in_array($key, [static::AFTER_LABEL_SCHEMA_KEY, static::AFTER_CONTENT_SCHEMA_KEY])) {
$schema->alignEnd();
}
return $schema;
}
protected function configureChildSchema(Schema $schema, string $key): Schema
{
$schema = parent::configureChildSchema($schema, $key);
if (in_array($key, [
static::ABOVE_LABEL_SCHEMA_KEY,
static::BELOW_LABEL_SCHEMA_KEY,
static::BEFORE_LABEL_SCHEMA_KEY,
static::AFTER_LABEL_SCHEMA_KEY,
static::ABOVE_CONTENT_SCHEMA_KEY,
static::BELOW_CONTENT_SCHEMA_KEY,
static::BEFORE_CONTENT_SCHEMA_KEY,
static::AFTER_CONTENT_SCHEMA_KEY,
static::ABOVE_ERROR_MESSAGE_SCHEMA_KEY,
static::BELOW_ERROR_MESSAGE_SCHEMA_KEY,
])) {
$schema
->inline()
->embeddedInParentComponent()
->modifyActionsUsing(fn (Action $action) => $action
->defaultSize(Size::Small)
->defaultView(Action::LINK_VIEW))
->modifyActionGroupsUsing(fn (ActionGroup $actionGroup) => $actionGroup->defaultSize(Size::Small));
}
return $schema;
}
public function hasErrorForPath(?string $statePath): bool
{
if (blank($statePath)) {
return false;
}
$errors = view()->shared('errors');
if (! $errors instanceof ViewErrorBag) {
return false;
}
return $errors->has($statePath);
}
/**
* @internal This method is not part of the public API and should not be used. Its parameters may change at any time without notice.
*
* @param array<string, mixed> $extraWrapperAttributes
*/
public function wrapEmbeddedHtml(
string $html,
array $extraWrapperAttributes = [],
?VerticalAlignment $inlineLabelVerticalAlignment = null,
string | Htmlable | null $labelPrefix = null,
string | Htmlable | null $labelSuffix = null,
string $labelTag = 'label',
): string {
$statePath = $this->getStatePath();
$hasNestedRecursiveValidationRules = $this instanceof Contracts\HasNestedRecursiveValidationRules;
/** @var MessageBag $errors */
$errors = view()->shared('errors') instanceof ViewErrorBag
? view()->shared('errors')->getBag('default')
: new MessageBag;
$hasError = filled($statePath) && ($errors->has($statePath) || ($hasNestedRecursiveValidationRules && $errors->has("{$statePath}.*")));
$errorMessage = null;
$errorMessages = null;
if ($hasError) {
if ($this->shouldShowAllValidationMessages()) {
$errorMessages = $errors->has($statePath)
? $errors->get($statePath)
: ($hasNestedRecursiveValidationRules ? Arr::flatten($errors->get("{$statePath}.*")) : []);
if (count($errorMessages) === 1) {
$errorMessage = Arr::first($errorMessages);
$errorMessages = [];
}
} else {
$errorMessage = $errors->has($statePath)
? $errors->first($statePath)
: ($hasNestedRecursiveValidationRules ? $errors->first("{$statePath}.*") : null);
}
}
$fieldWrapperView = $this->getFieldWrapperView();
$isDefaultFieldWrapperView = $fieldWrapperView === 'filament-forms::field-wrapper';
if (
(! $isDefaultFieldWrapperView)
|| ViewComponent::hasPublishedEmbeddedViewOverride('filament-forms::components.field-wrapper')
) {
$absoluteView = $isDefaultFieldWrapperView
? 'filament-forms::components.field-wrapper'
: (string) (str($fieldWrapperView)->contains('::')
? str($fieldWrapperView)->replaceFirst('::', '::components.')
: str("components.{$fieldWrapperView}"));
if (view()->exists($absoluteView)) {
return view($absoluteView, [
'field' => $this,
'slot' => new ComponentSlot($html),
'labelPrefix' => $labelPrefix,
'labelSuffix' => $labelSuffix,
'inlineLabelVerticalAlignment' => $inlineLabelVerticalAlignment ?? VerticalAlignment::Start,
'labelTag' => $labelTag,
'attributes' => (new FilamentComponentAttributeBag)->merge($extraWrapperAttributes, escape: false),
'hasErrors' => $hasError,
'errorMessage' => $errorMessage,
'errorMessages' => $errorMessages,
])->toHtml();
}
return $this->renderWrapperBladeComponent(
$fieldWrapperView,
new ComponentSlot($html),
(new FilamentComponentAttributeBag([
'field' => $this,
'label-prefix' => $labelPrefix,
'label-suffix' => $labelSuffix,
'inline-label-vertical-alignment' => $inlineLabelVerticalAlignment ?? VerticalAlignment::Start,
'label-tag' => $labelTag,
'has-errors' => $hasError,
'error-message' => $errorMessage,
'error-messages' => $errorMessages,
]))->merge($extraWrapperAttributes, escape: false),
);
}
$hasInlineLabel = $this->hasInlineLabel();
$id = $this->getId();
$isDisabled = $this->isDisabled();
$label = $this->getLabel();
$labelSrOnly = $this->isLabelHidden();
$required = $this->isMarkedAsRequired();
$aboveLabelSchema = $this->getChildSchema(static::ABOVE_LABEL_SCHEMA_KEY)?->toHtmlString();
$belowLabelSchema = $this->getChildSchema(static::BELOW_LABEL_SCHEMA_KEY)?->toHtmlString();
$beforeLabelSchema = $this->getChildSchema(static::BEFORE_LABEL_SCHEMA_KEY)?->toHtmlString();
$afterLabelSchema = $this->getChildSchema(static::AFTER_LABEL_SCHEMA_KEY)?->toHtmlString();
$aboveContentSchema = $this->getChildSchema(static::ABOVE_CONTENT_SCHEMA_KEY)?->toHtmlString();
$belowContentSchema = $this->getChildSchema(static::BELOW_CONTENT_SCHEMA_KEY)?->toHtmlString();
$beforeContentSchema = $this->getChildSchema(static::BEFORE_CONTENT_SCHEMA_KEY)?->toHtmlString();
$afterContentSchema = $this->getChildSchema(static::AFTER_CONTENT_SCHEMA_KEY)?->toHtmlString();
$aboveErrorMessageSchema = $this->getChildSchema(static::ABOVE_ERROR_MESSAGE_SCHEMA_KEY)?->toHtmlString();
$belowErrorMessageSchema = $this->getChildSchema(static::BELOW_ERROR_MESSAGE_SCHEMA_KEY)?->toHtmlString();
$areHtmlErrorMessagesAllowed = $this->areHtmlValidationMessagesAllowed();
$wrapperAttributes = (new FilamentComponentAttributeBag)
->merge($extraWrapperAttributes, escape: false)
->merge($this->getExtraFieldWrapperAttributes(), escape: false)
->class([
'fi-fo-field',
'fi-fo-field-has-inline-label' => $hasInlineLabel,
]);
$inlineLabelVerticalAlignment ??= VerticalAlignment::Start;
ob_start(); ?>
<div data-field-wrapper <?= $wrapperAttributes->toHtml() ?>>
<?php if (filled($label) && $labelSrOnly) { ?>
<<?= $labelTag ?>
<?php if ($labelTag === 'label') { ?>
for="<?= e($id) ?>"
<?php } else { ?>
id="<?= e($id) ?>-label"
<?php } ?>
class="fi-fo-field-label fi-sr-only"
>
<?= e($label) ?>
</<?= $labelTag ?>>
<?php } ?>
<?php if ((filled($label) && (! $labelSrOnly)) || $hasInlineLabel || $aboveLabelSchema || $belowLabelSchema || $beforeLabelSchema || $afterLabelSchema || $labelPrefix || $labelSuffix) { ?>
<div
<?= (new FilamentComponentAttributeBag)->class([
'fi-fo-field-label-col',
"fi-vertical-align-{$inlineLabelVerticalAlignment->value}" => $hasInlineLabel,
])->toHtml() ?>
>
<?= $aboveLabelSchema?->toHtml() ?>
<div
<?= (new FilamentComponentAttributeBag)->class([
'fi-fo-field-label-ctn',
($label instanceof ComponentSlot) ? $label->attributes->get('class') : null,
])->toHtml() ?>
>
<?= $beforeLabelSchema?->toHtml() ?>
<?php if ((filled($label) && (! $labelSrOnly)) || $labelPrefix || $labelSuffix) { ?>
<<?= $labelTag ?>
<?php if ($labelTag === 'label') { ?>
for="<?= e($id) ?>"
<?php } else { ?>
id="<?= e($id) ?>-label"
<?php } ?>
class="fi-fo-field-label"
>
<?= e($labelPrefix) ?>
<?php if (filled($label) && (! $labelSrOnly)) { ?>
<span class="fi-fo-field-label-content">
<?= e($label) ?><?php if ($required && (! $isDisabled)) { ?><sup class="fi-fo-field-label-required-mark">*</sup>
<?php } ?>
</span>
<?php } ?>
<?= e($labelSuffix) ?>
</<?= $labelTag ?>>
<?php } ?>
<?= $afterLabelSchema?->toHtml() ?>
</div>
<?= $belowLabelSchema?->toHtml() ?>
</div>
<?php } ?>
<?php if (filled($html) || $hasError || $aboveContentSchema || $belowContentSchema || $beforeContentSchema || $afterContentSchema || $aboveErrorMessageSchema || $belowErrorMessageSchema) { ?>
<div class="fi-fo-field-content-col">
<?= $aboveContentSchema?->toHtml() ?>
<?php if ($beforeContentSchema || $afterContentSchema) { ?>
<div class="fi-fo-field-content-ctn">
<?= $beforeContentSchema?->toHtml() ?>
<div class="fi-fo-field-content">
<?= $html ?>
</div>
<?= $afterContentSchema?->toHtml() ?>
</div>
<?php } else { ?>
<?= $html ?>
<?php } ?>
<?= $belowContentSchema?->toHtml() ?>
<?php if ($hasError) { ?>
<?= $aboveErrorMessageSchema?->toHtml() ?>
<?php if (filled($errorMessages)) { ?>
<ul data-validation-error class="fi-fo-field-wrp-error-list">
<?php foreach ($errorMessages as $errorMsg) { ?>
<li class="fi-fo-field-wrp-error-message">
<?php if ($areHtmlErrorMessagesAllowed) { ?>
<?= $errorMsg ?>
<?php } else { ?>
<?= e($errorMsg) ?>
<?php } ?>
</li>
<?php } ?>
</ul>
<?php } elseif ($areHtmlErrorMessagesAllowed) { ?>
<div data-validation-error class="fi-fo-field-wrp-error-message">
<?= $errorMessage ?>
</div>
<?php } else { ?>
<p data-validation-error class="fi-fo-field-wrp-error-message">
<?= e($errorMessage) ?>
</p>
<?php } ?>
<?= $belowErrorMessageSchema?->toHtml() ?>
<?php } ?>
</div>
<?php } ?>
</div>
<?php return ob_get_clean();
}
/**
* @internal This method is not part of the public API and should not be used. Its parameters may change at any time without notice.
*/
protected function wrapInputHtml(
string $html,
?string $alpineDisabled = null,
?string $alpineValid = null,
?ComponentAttributeBag $attributes = null,
): string {
$attributes ??= new FilamentComponentAttributeBag;
$hasAffixes = $this instanceof Contracts\HasAffixes;
$prefix = $hasAffixes ? $this->getPrefixLabel() : null;
$prefixActions = $hasAffixes ? array_filter(
$this->getPrefixActions(),
static fn (Action $prefixAction): bool => $prefixAction->isVisible(),
) : [];
$prefixIcon = $hasAffixes ? $this->getPrefixIcon() : null;
$prefixIconColor = ($hasAffixes ? $this->getPrefixIconColor() : null) ?? 'gray';
$suffix = $hasAffixes ? $this->getSuffixLabel() : null;
$suffixActions = $hasAffixes ? array_filter(
$this->getSuffixActions(),
static fn (Action $suffixAction): bool => $suffixAction->isVisible(),
) : [];
$suffixIcon = $hasAffixes ? $this->getSuffixIcon() : null;
$suffixIconColor = ($hasAffixes ? $this->getSuffixIconColor() : null) ?? 'gray';
$hasPrefix = count($prefixActions) || $prefixIcon || filled($prefix);
$hasSuffix = count($suffixActions) || $suffixIcon || filled($suffix);
$hasInlinePrefix = $hasAffixes && $hasPrefix && $this->isPrefixInline();
$hasInlineSuffix = $hasAffixes && $hasSuffix && $this->isSuffixInline();
$isDisabled = $this->isDisabled();
$isValid = ! $this->hasErrorForPath($this->getStatePath());
$hasAlpineDisabledClasses = filled($alpineDisabled);
$hasAlpineValidClasses = filled($alpineValid);
$hasAlpineClasses = $hasAlpineDisabledClasses || $hasAlpineValidClasses;
$wireTarget = $attributes->whereStartsWith(['wire:target'])->first();
$hasLoadingIndicator = filled($wireTarget);
$loadingIndicatorTarget = $hasLoadingIndicator ? html_entity_decode((string) $wireTarget, ENT_QUOTES) : null;
$loadingDelay = config('filament.livewire_loading_delay', 'default');
$hasFocusInputListener = $attributes->has('x-on:focus-input.stop');
$canClickPrefixAffix = $hasFocusInputListener && ($prefixIcon || filled($prefix));
$canClickSuffixAffix = $hasFocusInputListener && ($suffixIcon || filled($suffix));
$wrapperAttributes = $attributes
->except(['wire:target', 'tabindex'])
->class([
'fi-input-wrp',
'fi-disabled' => (! $hasAlpineClasses) && $isDisabled,
'fi-invalid' => (! $hasAlpineClasses) && (! $isValid),
]);
if ($hasAlpineClasses) {
$alpineClassParts = [];
if ($hasAlpineDisabledClasses) {
$alpineClassParts[] = "'fi-disabled': {$alpineDisabled}";
}
if ($hasAlpineValidClasses) {
$alpineClassParts[] = "'fi-invalid': ! ({$alpineValid})";
}
$wrapperAttributes = $wrapperAttributes->merge([
'x-bind:class' => '{ ' . implode(', ', $alpineClassParts) . ' }',
], escape: false);
}
ob_start(); ?>
<div <?= $wrapperAttributes->toHtml() ?>>
<?php if ($hasPrefix || $hasLoadingIndicator) {
$prefixDivAttributes = (new FilamentComponentAttributeBag)->class([
'fi-input-wrp-prefix',
'fi-input-wrp-prefix-has-content' => $hasPrefix,
'fi-inline' => $hasInlinePrefix,
'fi-input-wrp-prefix-has-label' => filled($prefix),
]);
if (! $hasPrefix) {
$prefixDivAttributes = $prefixDivAttributes->merge([
'wire:loading.delay.' . $loadingDelay . '.flex' => true,
'wire:target' => $loadingIndicatorTarget,
// Forces the loading indicator to hide once the request completes.
'wire:key' => Str::random(),
], escape: false);
}
if ($canClickPrefixAffix) {
$prefixDivAttributes = $prefixDivAttributes->merge([
'x-on:click' => '$dispatch(\'focus-input\')',
], escape: false);
}
?>
<div <?= $prefixDivAttributes->toHtml() ?>>
<?php if (count($prefixActions)) { ?>
<div
class="fi-input-wrp-actions"
<?php if ($canClickPrefixAffix) { ?>x-on:click.stop<?php } ?>
>
<?php foreach ($prefixActions as $prefixAction) { ?>
<?= $prefixAction->toHtml() ?>
<?php } ?>
</div>
<?php } ?>
<?= generate_icon_html(
$prefixIcon,
attributes: (new FilamentComponentAttributeBag)
->merge([
'wire:loading.remove.delay.' . $loadingDelay => $hasLoadingIndicator,
'wire:target' => $hasLoadingIndicator ? $loadingIndicatorTarget : false,
], escape: false)
->color(IconComponent::class, $prefixIconColor),
)?->toHtml() ?>
<?php if ($hasLoadingIndicator) { ?>
<?= generate_loading_indicator_html((new FilamentComponentAttributeBag([
'wire:loading.delay.' . $loadingDelay => $hasPrefix,
'wire:target' => $hasPrefix ? $loadingIndicatorTarget : null,
]))->color(IconComponent::class, 'gray'))->toHtml() ?>
<?php } ?>
<?php if (filled($prefix)) { ?>
<span class="fi-input-wrp-label">
<?= e($prefix) ?>
</span>
<?php } ?>
</div>
<?php } ?>
<?php
$contentCtnAttributes = (new FilamentComponentAttributeBag)->class([
'fi-input-wrp-content-ctn',
'fi-input-wrp-content-ctn-ps' => $hasLoadingIndicator && (! $hasPrefix) && $hasInlinePrefix,
]);
if ($hasLoadingIndicator && (! $hasPrefix)) {
$contentCtnAttributes = $contentCtnAttributes->merge([
'wire:target' => $loadingIndicatorTarget,
'wire:loading.delay.' . $loadingDelay . '.class.remove' => $hasInlinePrefix ? 'ps-3' : false,
], escape: false);
}
?>
<div <?= $contentCtnAttributes->toHtml() ?>>
<?= $html ?>
</div>
<?php if ($hasSuffix) {
$suffixDivAttributes = (new FilamentComponentAttributeBag)->class([
'fi-input-wrp-suffix',
'fi-inline' => $hasInlineSuffix,
'fi-input-wrp-suffix-has-label' => filled($suffix),
]);
if ($canClickSuffixAffix) {
$suffixDivAttributes = $suffixDivAttributes->merge([
'x-on:click' => '$dispatch(\'focus-input\')',
], escape: false);
}
?>
<div <?= $suffixDivAttributes->toHtml() ?>>
<?php if (filled($suffix)) { ?>
<span class="fi-input-wrp-label">
<?= e($suffix) ?>
</span>
<?php } ?>
<?= generate_icon_html(
$suffixIcon,
attributes: (new FilamentComponentAttributeBag)
->merge([
'wire:loading.remove.delay.' . $loadingDelay => $hasLoadingIndicator,
'wire:target' => $hasLoadingIndicator ? $loadingIndicatorTarget : false,
], escape: false)
->color(IconComponent::class, $suffixIconColor),
)?->toHtml() ?>
<?php if (count($suffixActions)) { ?>
<div
class="fi-input-wrp-actions"
<?php if ($canClickSuffixAffix) { ?>x-on:click.stop<?php } ?>
>
<?php foreach ($suffixActions as $suffixAction) { ?>
<?= $suffixAction->toHtml() ?>
<?php } ?>
</div>
<?php } ?>
</div>
<?php } ?>
</div>
<?php return ob_get_clean();
}
public function hasNullableBooleanState(): bool
{
return false;
}
public function getLabel(): string | Htmlable | null
{
if (filled($label = $this->getBaseLabel())) {
return $label;
}
return $this->getDefaultLabel();
}
public function getDefaultLabel(): string
{
$label = (string) str($this->getName())
->afterLast('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
return $this->shouldTranslateLabel ? __($label) : $label;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,32 @@
<?php
namespace Filament\Forms\Components;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
class Hidden extends Field implements HasEmbeddedView
{
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.hidden';
protected function setUp(): void
{
parent::setUp();
$this->columnSpan(['default' => 'hidden']);
}
public function toEmbeddedHtml(): string
{
$attributes = (new FilamentComponentAttributeBag)
->merge([
'id' => $this->getId(),
'type' => 'hidden',
$this->applyStateBindingModifiers('wire:model') => $this->getStatePath(),
], escape: false)
->merge($this->getExtraAttributes(), escape: false)
->class(['fi-fo-hidden']);
return '<input ' . $attributes->toHtml() . ' />';
}
}

View file

@ -0,0 +1,533 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Actions\Action;
use Filament\Forms\View\FormsIconAlias;
use Filament\Schemas\Components\StateCasts\KeyValueStateCast;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Concerns\HasExtraAlpineAttributes;
use Filament\Support\Concerns\HasReorderAnimationDuration;
use Filament\Support\Enums\Size;
use Filament\Support\Facades\FilamentAsset;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
class KeyValue extends Field implements HasEmbeddedView
{
use HasExtraAlpineAttributes;
use HasReorderAnimationDuration;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.key-value';
protected string | Closure | null $addActionLabel = null;
protected string | Closure | null $deleteActionLabel = null;
protected string | Closure | null $reorderActionLabel = null;
protected bool | Closure $isAddable = true;
protected bool | Closure $isDeletable = true;
protected bool | Closure $canEditKeys = true;
protected bool | Closure $canEditValues = true;
protected string | Closure | null $keyLabel = null;
protected string | Closure | null $valueLabel = null;
protected string | Closure | null $keyPlaceholder = null;
protected string | Closure | null $valuePlaceholder = null;
protected bool | Closure $isReorderable = false;
protected ?Closure $modifyAddActionUsing = null;
protected ?Closure $modifyDeleteActionUsing = null;
protected ?Closure $modifyReorderActionUsing = null;
protected function setUp(): void
{
parent::setUp();
$this->default([]);
$this->registerActions([
fn (KeyValue $component): Action => $component->getAddAction(),
fn (KeyValue $component): Action => $component->getDeleteAction(),
fn (KeyValue $component): Action => $component->getReorderAction(),
]);
}
public function getAddAction(): Action
{
$action = Action::make($this->getAddActionName())
->label(fn (KeyValue $component) => $component->getAddActionLabel())
->color('gray')
->livewireClickHandlerEnabled(false)
->link()
->visible(fn (): bool => $this->isAddable());
if ($this->modifyAddActionUsing) {
$action = $this->evaluate($this->modifyAddActionUsing, [
'action' => $action,
]) ?? $action;
}
return $action;
}
public function addAction(?Closure $callback): static
{
$this->modifyAddActionUsing = $callback;
return $this;
}
public function getAddActionName(): string
{
return 'add';
}
public function getDeleteAction(): Action
{
$action = Action::make($this->getDeleteActionName())
->label(__('filament-forms::components.key_value.actions.delete.label'))
->icon(FilamentIcon::resolve(FormsIconAlias::COMPONENTS_KEY_VALUE_ACTIONS_DELETE) ?? Heroicon::Trash)
->color('danger')
->livewireClickHandlerEnabled(false)
->iconButton()
->size(Size::Small)
->visible(fn (): bool => $this->isDeletable());
if ($this->modifyDeleteActionUsing) {
$action = $this->evaluate($this->modifyDeleteActionUsing, [
'action' => $action,
]) ?? $action;
}
return $action;
}
public function deleteAction(?Closure $callback): static
{
$this->modifyDeleteActionUsing = $callback;
return $this;
}
public function getDeleteActionName(): string
{
return 'delete';
}
public function getReorderAction(): Action
{
$action = Action::make($this->getReorderActionName())
->label(__('filament-forms::components.key_value.actions.reorder.label'))
->icon(FilamentIcon::resolve(FormsIconAlias::COMPONENTS_KEY_VALUE_ACTIONS_REORDER) ?? Heroicon::ArrowsUpDown)
->color('gray')
->livewireClickHandlerEnabled(false)
->iconButton()
->size(Size::Small)
->visible(fn (): bool => $this->isReorderable());
if ($this->modifyReorderActionUsing) {
$action = $this->evaluate($this->modifyReorderActionUsing, [
'action' => $action,
]) ?? $action;
}
return $action;
}
public function reorderAction(?Closure $callback): static
{
$this->modifyReorderActionUsing = $callback;
return $this;
}
public function getReorderActionName(): string
{
return 'reorder';
}
public function addActionLabel(string | Closure | null $label): static
{
$this->addActionLabel = $label;
return $this;
}
public function deleteActionLabel(string | Closure | null $label): static
{
$this->deleteActionLabel = $label;
return $this;
}
public function reorderActionLabel(string | Closure | null $label): static
{
$this->reorderActionLabel = $label;
return $this;
}
/**
* @deprecated Use `addActionLabel()` instead.
*/
public function addButtonLabel(string | Closure | null $label): static
{
$this->addActionLabel($label);
return $this;
}
/**
* @deprecated Use `deleteActionLabel()` instead.
*/
public function deleteButtonLabel(string | Closure | null $label): static
{
$this->deleteActionLabel($label);
return $this;
}
/**
* @deprecated Use `reorderActionLabel()` instead.
*/
public function reorderButtonLabel(string | Closure | null $label): static
{
$this->reorderActionLabel($label);
return $this;
}
public function addable(bool | Closure $condition = true): static
{
$this->isAddable = $condition;
return $this;
}
public function deletable(bool | Closure $condition = true): static
{
$this->isDeletable = $condition;
return $this;
}
public function editableKeys(bool | Closure $condition = true): static
{
$this->canEditKeys = $condition;
return $this;
}
public function editableValues(bool | Closure $condition = true): static
{
$this->canEditValues = $condition;
return $this;
}
/**
* @deprecated Use `addable()` instead.
*/
public function disableAddingRows(bool | Closure $condition = true): static
{
$this->addable(fn (KeyValue $component): bool => ! $component->evaluate($condition));
return $this;
}
/**
* @deprecated Use `deletable()` instead.
*/
public function disableDeletingRows(bool | Closure $condition = true): static
{
$this->deletable(fn (KeyValue $component): bool => ! $component->evaluate($condition));
return $this;
}
/**
* @deprecated Use `editableKeys()` instead.
*/
public function disableEditingKeys(bool | Closure $condition = true): static
{
$this->editableKeys(fn (KeyValue $component): bool => ! $component->evaluate($condition));
return $this;
}
/**
* @deprecated Use `editableValues()` instead.
*/
public function disableEditingValues(bool | Closure $condition = true): static
{
$this->editableValues(fn (KeyValue $component): bool => ! $component->evaluate($condition));
return $this;
}
public function keyLabel(string | Closure | null $label): static
{
$this->keyLabel = $label;
return $this;
}
public function valueLabel(string | Closure | null $label): static
{
$this->valueLabel = $label;
return $this;
}
public function keyPlaceholder(string | Closure | null $placeholder): static
{
$this->keyPlaceholder = $placeholder;
return $this;
}
public function valuePlaceholder(string | Closure | null $placeholder): static
{
$this->valuePlaceholder = $placeholder;
return $this;
}
public function reorderable(bool | Closure $condition = true): static
{
$this->isReorderable = $condition;
return $this;
}
public function isAddable(): bool
{
return (bool) $this->evaluate($this->isAddable);
}
public function isDeletable(): bool
{
return (bool) $this->evaluate($this->isDeletable);
}
public function canEditKeys(): bool
{
return (bool) $this->evaluate($this->canEditKeys);
}
public function canEditValues(): bool
{
return (bool) $this->evaluate($this->canEditValues);
}
public function getAddActionLabel(): string
{
return $this->evaluate($this->addActionLabel) ?? __('filament-forms::components.key_value.actions.add.label');
}
public function getDeleteActionLabel(): string
{
return $this->evaluate($this->deleteActionLabel) ?? __('filament-forms::components.key_value.actions.delete.label');
}
public function getReorderActionLabel(): string
{
return $this->evaluate($this->reorderActionLabel) ?? __('filament-forms::components.key_value.actions.reorder.label');
}
public function getKeyLabel(): string
{
return $this->evaluate($this->keyLabel) ?? __('filament-forms::components.key_value.fields.key.label');
}
public function getValueLabel(): string
{
return $this->evaluate($this->valueLabel) ?? __('filament-forms::components.key_value.fields.value.label');
}
public function getKeyPlaceholder(): ?string
{
return $this->evaluate($this->keyPlaceholder);
}
public function getValuePlaceholder(): ?string
{
return $this->evaluate($this->valuePlaceholder);
}
public function isReorderable(): bool
{
return (bool) $this->evaluate($this->isReorderable);
}
public function toEmbeddedHtml(): string
{
$canEditKeys = $this->canEditKeys();
$canEditValues = $this->canEditValues();
$debounce = $this->getLiveDebounce();
$id = $this->getId();
$isAddable = $this->isAddable();
$isDeletable = $this->isDeletable();
$isDisabled = $this->isDisabled();
$isReorderable = $this->isReorderable();
$keyPlaceholder = $this->getKeyPlaceholder();
$livewireKey = $this->getLivewireKey();
$statePath = $this->getStatePath();
$valuePlaceholder = $this->getValuePlaceholder();
$wrapperAttributes = $this->getExtraAttributeBag()
->class(['fi-fo-key-value']);
$alpineDivAttributes = $this->getExtraAlpineAttributeBag()
->class(['fi-fo-key-value-table-ctn']);
ob_start(); ?>
<div
x-load
x-load-src="<?= e(FilamentAsset::getAlpineComponentSrc('key-value', 'filament/forms')) ?>"
x-data="keyValueFormComponent({
state: $wire.<?= $this->applyStateBindingModifiers("\$entangle('{$statePath}')") ?>,
})"
wire:ignore
wire:key="<?= e($livewireKey) ?>.<?= e(substr(md5(serialize([$isDisabled])), 0, 64)) ?>"
<?= $alpineDivAttributes->toHtml() ?>
>
<table aria-labelledby="<?= e($id) ?>-label" id="<?= e($id) ?>" class="fi-fo-key-value-table">
<thead>
<tr>
<?php if ($isReorderable && (! $isDisabled)) { ?>
<th
scope="col"
x-show="rows.length"
class="fi-has-action"
>
<span class="fi-sr-only"><?= e(__('filament-forms::components.key_value.columns.reorder.label')) ?></span>
</th>
<?php } ?>
<th scope="col">
<?= e($this->getKeyLabel()) ?>
</th>
<th scope="col">
<?= e($this->getValueLabel()) ?>
</th>
<?php if ($isDeletable && (! $isDisabled)) { ?>
<th
scope="col"
x-show="rows.length"
class="fi-has-action"
>
<span class="fi-sr-only"><?= e(__('filament-forms::components.key_value.columns.actions.label')) ?></span>
</th>
<?php } ?>
</tr>
</thead>
<tbody
<?php if ($isReorderable) { ?>
x-on:end.stop="reorderRows($event)"
x-sortable
data-sortable-animation-duration="<?= e($this->getReorderAnimationDuration()) ?>"
<?php } ?>
>
<template
x-bind:key="index"
x-for="(row, index) in rows"
>
<tr
<?php if ($isReorderable) { ?>
x-bind:x-sortable-item="row.key"
<?php } ?>
>
<?php if ($isReorderable && (! $isDisabled)) { ?>
<td class="fi-has-action">
<div
x-sortable-handle
class="fi-fo-key-value-table-row-sortable-handle"
>
<?= $this->getAction('reorder')->toHtml() ?>
</div>
</td>
<?php } ?>
<td>
<input
aria-label="<?= e($this->getKeyLabel()) ?>"
<?= ((! $canEditKeys) || $isDisabled) ? 'disabled' : '' ?>
placeholder="<?= e($keyPlaceholder) ?>"
type="text"
x-model="row.key"
x-on:input.debounce.<?= e($debounce ?? '500ms') ?>="updateState"
class="fi-input"
/>
</td>
<td>
<input
aria-label="<?= e($this->getValueLabel()) ?>"
<?= ((! $canEditValues) || $isDisabled) ? 'disabled' : '' ?>
placeholder="<?= e($valuePlaceholder) ?>"
type="text"
x-model="row.value"
x-on:input.debounce.<?= e($debounce ?? '500ms') ?>="updateState"
class="fi-input"
/>
</td>
<?php if ($isDeletable && (! $isDisabled)) { ?>
<td class="fi-has-action">
<div x-on:click="deleteRow(index)">
<?= $this->getAction('delete')->toHtml() ?>
</div>
</td>
<?php } ?>
</tr>
</template>
</tbody>
</table>
<?php if ($isAddable && (! $isDisabled)) { ?>
<div
x-on:click="addRow"
class="fi-fo-key-value-add-action-ctn"
>
<?= $this->getAction('add')->toHtml() ?>
</div>
<?php } ?>
</div>
<?php $slotHtml = ob_get_clean();
return $this->wrapEmbeddedHtml(
$this->wrapInputHtml(
$slotHtml,
attributes: $wrapperAttributes,
),
extraWrapperAttributes: ['class' => 'fi-fo-key-value-wrp'],
labelTag: 'div',
);
}
public function getDefaultStateCasts(): array
{
return [
...parent::getDefaultStateCasts(),
app(KeyValueStateCast::class),
];
}
}

View file

@ -0,0 +1,107 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Livewire\Livewire;
class LivewireField extends Field implements HasEmbeddedView
{
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.livewire-field';
protected bool | Closure $isLazy = false;
/**
* @var array<string, mixed> | Closure
*/
protected array | Closure $data = [];
protected string | Closure $component;
public function component(string | Closure $component): static
{
$this->component = $component;
return $this;
}
public function getComponent(): string
{
return $this->evaluate($this->component);
}
public function lazy(bool | Closure $condition = true): static
{
$this->isLazy = $condition;
return $this;
}
public function isLazy(): bool
{
return (bool) $this->evaluate($this->isLazy);
}
/**
* @param array<string, mixed> | Closure $data
*/
public function data(array | Closure $data): static
{
$this->data = $data;
return $this;
}
/**
* @return array<string, mixed>
*/
public function getData(): array
{
return $this->evaluate($this->data);
}
/**
* @return array<string, mixed>
*/
public function getComponentProperties(): array
{
$properties = [
'record' => $this->getRecord(),
$this->applyStateBindingModifiers('wire:model') => $this->getStatePath(),
];
if ($this->isLazy()) {
$properties['lazy'] = true;
}
return [
...$properties,
...$this->getData(),
];
}
public function toEmbeddedHtml(): string
{
$extraAttributes = $this->getExtraAttributes();
$id = $this->getId();
$hasWrapper = filled($id) || filled($extraAttributes);
$livewireHtml = Livewire::mount($this->getComponent(), $this->getComponentProperties(), $this->getLivewireKey());
if ($hasWrapper) {
$attributes = (new FilamentComponentAttributeBag)
->merge([
'aria-labelledby' => filled($id) ? "{$id}-label" : null,
'id' => $id,
'role' => filled($id) ? 'group' : null,
], escape: false)
->merge($extraAttributes, escape: false);
$livewireHtml = '<div ' . $attributes->toHtml() . '>' . $livewireHtml . '</div>';
}
return $this->wrapEmbeddedHtml($livewireHtml, labelTag: filled($id) ? 'div' : 'label');
}
}

View file

@ -0,0 +1,181 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Concerns\CanConfigureCommonMark;
use Filament\Support\Concerns\HasExtraAlpineAttributes;
use Filament\Support\Facades\FilamentAsset;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Illuminate\Support\Js;
use LogicException;
class MarkdownEditor extends Field implements Contracts\CanBeLengthConstrained, HasEmbeddedView
{
// Security: Like the rich editor, the markdown editor sends raw content
// to the backend. When rendering in Blade views, always sanitize with
// `sanitizeHtml()` and `markdown()` together. Never use `{!! !!}`
// with unsanitized content.
use CanConfigureCommonMark;
use Concerns\CanBeLengthConstrained;
use Concerns\HasFileAttachments;
use Concerns\HasMaxHeight;
use Concerns\HasMinHeight;
use Concerns\HasPlaceholder;
use Concerns\InteractsWithToolbarButtons;
use HasExtraAlpineAttributes;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.markdown-editor';
/**
* @return array<string | array<string>>
*/
public function getDefaultToolbarButtons(): array
{
return [
['bold', 'italic', 'strike', 'link'],
['heading'],
['blockquote', 'codeBlock', 'bulletList', 'orderedList'],
[
'table',
...($this->hasFileAttachments(default: true) ? ['attachFiles'] : []),
],
['undo', 'redo'],
];
}
public function getFileAttachmentsDiskName(): string
{
$name = $this->evaluate($this->fileAttachmentsDiskName);
if (filled($name)) {
return $name;
}
$defaultName = config('filament.default_filesystem_disk');
return ($defaultName === 'local') ? 'public' : $defaultName;
}
public function fileAttachmentsVisibility(string | Closure | null $visibility): static
{
throw new LogicException('The visibility of file attachments for markdown content is always `public`, since generating temporary file upload URLs is not supported in static content.');
}
public function getFileAttachmentsVisibility(): string
{
return 'public';
}
public function hasFileAttachmentsByDefault(): bool
{
return $this->hasToolbarButton('attachFiles');
}
public function toEmbeddedHtml(): string
{
$id = $this->getId();
$isDisabled = $this->isDisabled();
$statePath = $this->getStatePath();
$minHeight = $this->getMinHeight();
$maxHeight = $this->getMaxHeight();
if ($isDisabled) {
$wrapperAttributes = (new FilamentComponentAttributeBag)
->merge([
'aria-labelledby' => "{$id}-label",
'id' => $id,
'role' => 'group',
'tabindex' => filled($maxHeight) ? '0' : null,
], escape: false)
->style(array_filter([
filled($minHeight) ? "--min-height: {$minHeight}" : null,
filled($maxHeight) ? "--max-height: {$maxHeight}" : null,
]))
->class(['fi-fo-markdown-editor', 'fi-disabled', 'fi-prose']);
ob_start(); ?>
<div <?= $wrapperAttributes->toHtml() ?>>
<?= str($this->getState())->markdown($this->getCommonMarkOptions(), $this->getCommonMarkExtensions())->sanitizeHtml() ?>
</div>
<?php return $this->wrapEmbeddedHtml(ob_get_clean(), labelTag: 'div');
}
$key = $this->getKey();
$label = $this->getLabel();
$fileAttachmentsMaxSize = $this->getFileAttachmentsMaxSize();
$fileAttachmentsAcceptedFileTypes = $this->getFileAttachmentsAcceptedFileTypes();
$wrapperAttributes = $this->getExtraAttributeBag()
->class(['fi-fo-markdown-editor']);
ob_start(); ?>
<div
aria-labelledby="<?= e($id) ?>-label"
id="<?= e($id) ?>"
role="group"
x-load
x-load-src="<?= e(FilamentAsset::getAlpineComponentSrc('markdown-editor', 'filament/forms')) ?>"
x-data="markdownEditorFormComponent({
canAttachFiles: <?= Js::from($this->hasFileAttachments()) ?>,
isLiveDebounced: <?= Js::from($this->isLiveDebounced()) ?>,
isLiveOnBlur: <?= Js::from($this->isLiveOnBlur()) ?>,
label: <?= Js::from($label) ?>,
liveDebounce: <?= Js::from($this->getNormalizedLiveDebounce()) ?>,
maxHeight: <?= Js::from($maxHeight) ?>,
minHeight: <?= Js::from($minHeight) ?>,
placeholder: <?= Js::from($this->getPlaceholder()) ?>,
state: $wire.<?= $this->applyStateBindingModifiers("\$entangle('{$statePath}')", isOptimisticallyLive: false) ?>,
toolbarButtons: <?= Js::from($this->getToolbarButtons()) ?>,
translations: <?= Js::from(__('filament-forms::components.markdown_editor')) ?>,
uploadFileAttachmentUsing: async (file, onSuccess, onError) => {
const acceptedTypes = <?= Js::from($fileAttachmentsAcceptedFileTypes) ?>
if (acceptedTypes && ! acceptedTypes.includes(file.type)) {
return onError(<?= Js::from($fileAttachmentsAcceptedFileTypes ? __('filament-forms::components.markdown_editor.file_attachments_accepted_file_types_message', ['values' => implode(', ', $fileAttachmentsAcceptedFileTypes)]) : null) ?>)
}
const maxSize = <?= Js::from($fileAttachmentsMaxSize) ?>
if (maxSize && file.size > +maxSize * 1024) {
return onError(<?= Js::from($fileAttachmentsMaxSize ? trans_choice('filament-forms::components.markdown_editor.file_attachments_max_size_message', $fileAttachmentsMaxSize, ['max' => $fileAttachmentsMaxSize]) : null) ?>)
}
$wire.upload(`componentFileAttachments.<?= e($statePath) ?>`, file, () => {
$wire
.callSchemaComponentMethod(
<?= Js::from($key) ?>,
'saveUploadedFileAttachmentAndGetUrl',
)
.then((url) => {
if (! url) {
return onError()
}
onSuccess(url)
})
})
},
})"
wire:ignore
<?= $this->getExtraAlpineAttributeBag()->toHtml() ?>
>
<textarea x-ref="editor" x-cloak></textarea>
</div>
<?php $slotHtml = ob_get_clean();
return $this->wrapEmbeddedHtml(
$this->wrapInputHtml(
$slotHtml,
attributes: $wrapperAttributes,
),
labelTag: 'div',
);
}
}

View file

@ -0,0 +1,993 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Actions\Action;
use Filament\Forms\View\FormsIconAlias;
use Filament\Schemas\Components\StateCasts\Contracts\StateCast;
use Filament\Schemas\Components\StateCasts\OptionsArrayStateCast;
use Filament\Schemas\Components\StateCasts\OptionStateCast;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Enums\IconPosition;
use Filament\Support\Facades\FilamentIcon;
use Filament\Support\Icons\Heroicon;
use Filament\Support\Services\RelationshipJoiner;
use Filament\Support\View\ComponentAttributeBag as FilamentComponentAttributeBag;
use Filament\Support\View\Components\BadgeComponent;
use Illuminate\Contracts\Support\Arrayable;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
use Illuminate\Database\Eloquent\Relations\HasOneOrManyThrough;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use LogicException;
use Znck\Eloquent\Relations\BelongsToThrough;
class ModalTableSelect extends Field implements HasEmbeddedView
{
use Concerns\CanLimitItemsLength;
use Concerns\HasPivotData;
use Concerns\HasPlaceholder;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.modal-table-select';
protected ?Model $cachedSelectedRecord = null;
protected bool | Closure $isMultiple = false;
protected ?Closure $getOptionLabelUsing;
protected ?Closure $getSelectedRecordUsing = null;
protected ?Closure $getOptionLabelsUsing;
protected string | Closure | null $relationshipTitleAttribute = null;
protected ?Closure $getOptionLabelFromRecordUsing = null;
protected string | Closure | null $relationship = null;
protected ?Closure $modifyRelationshipQueryUsing = null;
protected string | Closure | null $tableConfiguration = null;
protected ?Closure $modifyTableSelectUsing = null;
protected ?Closure $modifySelectActionUsing = null;
protected bool | Closure | null $hasBadges = null;
protected string | Closure | null $badgeColor = null;
/**
* @var array<mixed> | Closure
*/
protected array | Closure $tableArguments = [];
protected function setUp(): void
{
parent::setUp();
$this->registerActions([
fn (ModalTableSelect $component): Action => $component->getSelectAction(),
]);
}
public function tableSelect(?Closure $callback): static
{
$this->modifyTableSelectUsing = $callback;
return $this;
}
public function selectAction(?Closure $callback): static
{
$this->modifySelectActionUsing = $callback;
return $this;
}
/**
* @param array<mixed> | Closure $arguments
*/
public function tableArguments(array | Closure $arguments): static
{
$this->tableArguments = $arguments;
return $this;
}
public function getSelectAction(): Action
{
$action = Action::make('select')
->label(__('filament-forms::components.modal_table_select.actions.select.label'))
->slideOver()
->modalHeading($this->getLabel())
->modalSubmitActionLabel(__('filament-forms::components.modal_table_select.actions.select.actions.select.label'))
->icon(FilamentIcon::resolve(FormsIconAlias::COMPONENTS_MODAL_TABLE_SELECT_ACTIONS_SELECT) ?? Heroicon::PencilSquare)
->iconPosition(IconPosition::After)
->fillForm(['selection' => $this->getState()])
->schema([$this->getTableSelect()])
->action(fn (array $data) => $this->state($data['selection'])->callAfterStateUpdated());
if ($this->isMultiple() || blank($this->getState())) {
$action->link();
} else {
$action->iconButton();
}
if ($this->modifySelectActionUsing) {
$action = $this->evaluate($this->modifySelectActionUsing, [
'action' => $action,
]) ?? $action;
}
return $action;
}
public function getTableSelect(): TableSelect
{
$select = TableSelect::make('selection')
->label($this->getLabel())
->hiddenLabel()
->tableConfiguration($this->getTableConfiguration())
->relationshipName($this->getRelationshipName())
->multiple($this->isMultiple())
->maxItems($this->getMaxItems())
->tableArguments($this->getTableArguments());
if ($this->modifyTableSelectUsing) {
$select = $this->evaluate(
$this->modifyTableSelectUsing,
namedInjections: [
'select' => $select,
'tableSelect' => $select,
],
typedInjections: [
TableSelect::class => $select,
],
) ?? $select;
}
return $select;
}
public function getOptionLabelUsing(?Closure $callback): static
{
$this->getOptionLabelUsing = $callback;
return $this;
}
public function getSelectedRecordUsing(?Closure $callback): static
{
$this->getSelectedRecordUsing = $callback;
return $this;
}
public function getOptionLabelsUsing(?Closure $callback): static
{
$this->getOptionLabelsUsing = $callback;
return $this;
}
public function multiple(bool | Closure $condition = true): static
{
$this->isMultiple = $condition;
return $this;
}
public function getOptionLabel(bool $withDefault = true): string | Htmlable | null
{
$state = null;
$label = $this->evaluate($this->getOptionLabelUsing, [
'value' => function () use (&$state): mixed {
return $state = $this->getState();
},
]);
if ($withDefault) {
$label ??= ($state ?? $this->getState());
}
return $label;
}
/**
* @return array<string | Htmlable>
*/
public function getOptionLabels(bool $withDefaults = true): array
{
$labels = $this->evaluate($this->getOptionLabelsUsing, [
'values' => fn (): array => $this->getState(),
]);
if ($labels instanceof Arrayable) {
$labels = $labels->toArray();
}
foreach ($labels as $value => $label) {
if (filled($label)) {
continue;
}
if ($withDefaults) {
$labels[$value] = $value;
continue;
}
unset($labels[$value]);
}
return $labels;
}
public function isMultiple(): bool
{
return (bool) $this->evaluate($this->isMultiple);
}
public function relationship(string | Closure | null $name = null, string | Closure | null $titleAttribute = null, ?Closure $modifyQueryUsing = null, bool $ignoreRecord = false): static
{
$this->relationship = $name ?? $this->getName();
$this->relationshipTitleAttribute = $titleAttribute;
$this->modifyRelationshipQueryUsing = $modifyQueryUsing;
$this->loadStateFromRelationshipsUsing(static function (ModalTableSelect $component): void {
$component->fillStateFromRelationship();
});
$this->getOptionLabelUsing(static function (ModalTableSelect $component) {
$record = $component->getSelectedRecord();
if (! $record) {
return null;
}
if ($component->hasOptionLabelFromRecordUsingCallback()) {
return $component->getOptionLabelFromRecord($record);
}
$relationshipTitleAttribute = $component->getRelationshipTitleAttribute();
if (str_contains($relationshipTitleAttribute, '->')) {
$relationshipTitleAttribute = str_replace('->', '.', $relationshipTitleAttribute);
}
return data_get($record, $relationshipTitleAttribute);
});
$this->getSelectedRecordUsing(static function (ModalTableSelect $component, $state): ?Model {
return $component->getSelectedRecordFromRelationship($state);
});
$this->getOptionLabelsUsing(static function (ModalTableSelect $component, array $values): array {
return $component->getOptionLabelsFromRelationship($values);
});
$this->saveRelationshipsUsing(static function (ModalTableSelect $component): void {
$component->saveStateToRelationship();
});
$this->dehydrated(fn (ModalTableSelect $component): bool => (! $component->isMultiple()) && $component->isSaved());
return $this;
}
public function getSelectedRecordFromRelationship(mixed $state): ?Model
{
$relationship = $this->getRelationship();
if (
(! $this->modifyRelationshipQueryUsing) &&
($relationship instanceof BelongsTo)
) {
$record = $this->getRecord();
if (
($record instanceof Model) &&
$record->relationLoaded($this->getRelationshipName())
) {
$relatedRecord = $record->getRelationValue($this->getRelationshipName());
if (
($relatedRecord instanceof Model) &&
((string) $relatedRecord->getAttribute($relationship->getOwnerKeyName()) === (string) $state)
) {
return $relatedRecord;
}
}
}
$relationship = Relation::noConstraints(fn () => $this->getRelationship());
$relationshipQuery = app(RelationshipJoiner::class)->prepareQueryForNoConstraints($relationship);
$relationshipQuery->where($this->getQualifiedRelatedKeyNameForRelationship($relationship), $state);
if ($this->modifyRelationshipQueryUsing) {
$relationshipQuery = $this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $relationshipQuery,
'search' => null,
]) ?? $relationshipQuery;
}
return $relationshipQuery->first();
}
/**
* @param array<string | int> $values
* @return array<string | int, string>
*/
public function getOptionLabelsFromRelationship(array $values): array
{
$relationship = $this->getRelationship();
$record = $this->getRecord();
$relationshipName = $this->getRelationshipName();
if (
(! $this->modifyRelationshipQueryUsing) &&
($record instanceof Model) &&
$record->relationLoaded($relationshipName) &&
(
($relationship instanceof BelongsToMany) ||
($relationship instanceof HasOneOrMany)
)
) {
$relatedRecords = $record->getRelationValue($relationshipName);
if ($relatedRecords instanceof Collection) {
$relatedKeyName = ($relationship instanceof BelongsToMany)
? $relationship->getRelatedKeyName()
: $relationship->getRelated()->getKeyName();
$loadedKeys = $relatedRecords->pluck($relatedKeyName)->map(fn ($key) => (string) $key)->all();
$requestedKeys = array_map(fn ($value) => (string) $value, $values);
if (empty(array_diff($requestedKeys, $loadedKeys))) {
$relationshipTitleAttribute = $this->getRelationshipTitleAttribute();
if (str_contains($relationshipTitleAttribute, '->')) {
$relationshipTitleAttribute = str_replace('->', '.', $relationshipTitleAttribute);
}
$filteredRecords = $relatedRecords->filter(
fn (Model $relatedRecord): bool => in_array(
(string) $relatedRecord->getAttribute($relatedKeyName),
$requestedKeys,
strict: true,
),
);
if ($this->hasOptionLabelFromRecordUsingCallback()) {
return $filteredRecords
->mapWithKeys(fn (Model $relatedRecord) => [
$relatedRecord->getAttribute($relatedKeyName) => $this->getOptionLabelFromRecord($relatedRecord),
])
->toArray();
}
return $filteredRecords
->pluck($relationshipTitleAttribute, $relatedKeyName)
->toArray();
}
}
}
$relationship = Relation::noConstraints(fn () => $this->getRelationship());
$relationshipQuery = app(RelationshipJoiner::class)->prepareQueryForNoConstraints($relationship);
$qualifiedRelatedKeyName = $this->getQualifiedRelatedKeyNameForRelationship($relationship);
$relationshipQuery->whereIn($qualifiedRelatedKeyName, $values);
if ($this->modifyRelationshipQueryUsing) {
$relationshipQuery = $this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $relationshipQuery,
'search' => null,
]) ?? $relationshipQuery;
}
if ($this->hasOptionLabelFromRecordUsingCallback()) {
return $relationshipQuery
->get()
->mapWithKeys(fn (Model $record) => [
$record->{Str::afterLast($qualifiedRelatedKeyName, '.')} => $this->getOptionLabelFromRecord($record),
])
->toArray();
}
$relationshipTitleAttribute = $this->getRelationshipTitleAttribute();
if (str_contains($relationshipTitleAttribute, '->')) {
if (! str_contains($relationshipTitleAttribute, ' as ')) {
$relationshipTitleAttribute .= " as {$relationshipTitleAttribute}";
}
} else {
$relationshipTitleAttribute = $relationshipQuery->qualifyColumn($relationshipTitleAttribute);
}
return $relationshipQuery
->pluck($relationshipTitleAttribute, $qualifiedRelatedKeyName)
->toArray();
}
public function fillStateFromRelationship(): void
{
if (filled($this->getState())) {
return;
}
$relationship = $this->getRelationship();
$relationshipName = $this->getRelationshipName();
if (
(! $this->modifyRelationshipQueryUsing) &&
(! str_contains($relationshipName, '.')) &&
($record = $this->getRecord()) instanceof Model &&
$record->relationLoaded($relationshipName)
) {
$relatedRecords = $record->getRelationValue($relationshipName);
if (
($relationship instanceof BelongsToMany) ||
($relationship instanceof HasOneOrManyThrough)
) {
$this->state(
$relatedRecords
->pluck(($relationship instanceof BelongsToMany) ? $relationship->getRelatedKeyName() : $relationship->getRelated()->getKeyName())
->map(static fn ($key): string => strval($key))
->all(),
);
return;
}
if ($relationship instanceof BelongsToThrough) {
$this->state(
$relatedRecords?->getAttribute(
$relationship->getRelated()->getKeyName(),
),
);
return;
}
if ($relationship instanceof HasMany) {
$this->state(
$relatedRecords
->pluck($relationship->getLocalKeyName())
->map(static fn ($key): string => strval($key))
->all(),
);
return;
}
if ($relationship instanceof HasOne) {
$this->state(
$relatedRecords?->getAttribute(
$relationship->getLocalKeyName(),
),
);
return;
}
/** @var BelongsTo $relationship */
$this->state(
$relatedRecords?->getAttribute(
$relationship->getOwnerKeyName(),
),
);
return;
}
if (
($relationship instanceof BelongsToMany) ||
($relationship instanceof HasOneOrManyThrough)
) {
if ($this->modifyRelationshipQueryUsing) {
$this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $relationship->getQuery(),
]);
}
/** @var Collection $relatedRecords */
$relatedRecords = $relationship->getResults();
$this->state(
// Cast the related keys to a string, otherwise
// JavaScript can't handle deselection.
//
// https://github.com/filamentphp/filament/issues/1111
$relatedRecords
->pluck(($relationship instanceof BelongsToMany) ? $relationship->getRelatedKeyName() : $relationship->getRelated()->getKeyName())
->map(static fn ($key): string => strval($key))
->all(),
);
return;
}
if ($relationship instanceof BelongsToThrough) {
/** @var ?Model $relatedModel */
$relatedModel = $relationship->getResults();
$this->state(
$relatedModel?->getAttribute(
$relationship->getRelated()->getKeyName(),
),
);
return;
}
if ($relationship instanceof HasMany) {
/** @var Collection $relatedRecords */
$relatedRecords = $relationship->getResults();
$this->state(
// Cast the related keys to a string, otherwise
// JavaScript can't handle deselection.
//
// https://github.com/filamentphp/filament/issues/1111
$relatedRecords
->pluck($relationship->getLocalKeyName())
->map(static fn ($key): string => strval($key))
->all(),
);
return;
}
if ($relationship instanceof HasOne) {
$relatedModel = $relationship->getResults();
$this->state(
$relatedModel?->getAttribute(
$relationship->getLocalKeyName(),
),
);
return;
}
/** @var BelongsTo $relationship */
$relatedModel = $relationship->getResults();
$this->state(
$relatedModel?->getAttribute(
$relationship->getOwnerKeyName(),
),
);
}
public function saveStateToRelationship(): void
{
$relationship = $this->getRelationship();
$record = $this->getRecord();
$relationshipName = $this->getRelationshipName();
$state = $this->getState();
if (($relationship instanceof HasOne) || ($relationship instanceof HasMany)) {
$query = $relationship->getQuery();
if ($this->modifyRelationshipQueryUsing) {
$this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $query,
'search' => null,
]);
}
$query->update([
$relationship->getForeignKeyName() => null,
]);
if (! empty($state)) {
$relationship::noConstraints(function () use ($record, $state): void {
$relationship = $this->getRelationship();
$query = $relationship->getQuery()->whereIn($relationship->getLocalKeyName(), Arr::wrap($state));
if ($this->modifyRelationshipQueryUsing) {
$this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $query,
'search' => null,
]);
}
$query->update([
$relationship->getForeignKeyName() => $record->getAttribute($relationship->getLocalKeyName()),
]);
});
}
$record->unsetRelation($relationshipName);
return;
}
if (
($relationship instanceof HasOneOrMany) ||
($relationship instanceof HasOneOrManyThrough) ||
($relationship instanceof BelongsToThrough)
) {
return;
}
if (! $relationship instanceof BelongsToMany) {
// Security: If the model is new and the foreign key is already
// filled, don't overwrite it — the key may have been set by
// authorization logic or event listeners before save.
if (
$record->wasRecentlyCreated &&
filled($record->getAttributeValue($relationship->getForeignKeyName()))
) {
return;
}
$relationship->associate($state);
$record->wasRecentlyCreated && $record->save();
return;
}
if ($this->modifyRelationshipQueryUsing) {
$this->evaluate($this->modifyRelationshipQueryUsing, [
'query' => $relationship->getQuery(),
'search' => null,
]);
}
/** @var Collection $relatedRecords */
$relatedRecords = $relationship->getResults();
$state = Arr::wrap($state ?? []);
$recordsToDetach = array_diff(
$relatedRecords
->pluck($relationship->getRelatedKeyName())
->map(static fn ($key): string => strval($key))
->all(),
$state,
);
if (count($recordsToDetach) > 0) {
$relationship->detach($recordsToDetach);
}
$pivotData = $this->getPivotData();
if ($pivotData === []) {
$relationship->sync($state, detaching: false);
$record->unsetRelation($relationshipName);
return;
}
$relationship->syncWithPivotValues($state, $pivotData, detaching: false);
$record->unsetRelation($relationshipName);
}
public function getOptionLabelFromRecordUsing(?Closure $callback): static
{
$this->getOptionLabelFromRecordUsing = $callback;
return $this;
}
public function hasOptionLabelFromRecordUsingCallback(): bool
{
return $this->getOptionLabelFromRecordUsing !== null;
}
public function getOptionLabelFromRecord(Model $record): string | Htmlable
{
return $this->evaluate(
$this->getOptionLabelFromRecordUsing,
namedInjections: [
'record' => $record,
],
typedInjections: [
Model::class => $record,
$record::class => $record,
],
);
}
public function getRelationshipTitleAttribute(): ?string
{
return $this->evaluate($this->relationshipTitleAttribute);
}
public function getLabel(): string | Htmlable | null
{
if ($this->label === null && $this->hasRelationship()) {
$label = (string) str($this->getRelationshipName())
->before('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
return ($this->shouldTranslateLabel) ? __($label) : $label;
}
return parent::getLabel();
}
public function getRelationship(): BelongsTo | BelongsToMany | HasOneOrMany | HasOneOrManyThrough | BelongsToThrough | null
{
if (! $this->hasRelationship()) {
return null;
}
$record = $this->getModelInstance();
$relationship = null;
$relationshipName = $this->getRelationshipName();
foreach (explode('.', $relationshipName) as $nestedRelationshipName) {
if ($record->hasAttribute($nestedRelationshipName)) {
$relationship = null;
break;
}
if (! $record->isRelation($nestedRelationshipName)) {
$relationship = null;
break;
}
$relationship = $record->{$nestedRelationshipName}();
$record = $relationship->getRelated();
}
if (! $relationship) {
throw new LogicException("The relationship [{$relationshipName}] does not exist on the model [{$this->getModel()}].");
}
return $relationship;
}
public function getRelationshipName(): ?string
{
return $this->evaluate($this->relationship);
}
public function getSelectedRecord(): ?Model
{
if ($this->cachedSelectedRecord) {
return $this->cachedSelectedRecord;
}
if (blank($this->getState())) {
return null;
}
return $this->cachedSelectedRecord = $this->evaluate($this->getSelectedRecordUsing);
}
public function hasRelationship(): bool
{
return filled($this->getRelationshipName());
}
protected function getQualifiedRelatedKeyNameForRelationship(Relation $relationship): string
{
if ($relationship instanceof BelongsToMany) {
return $relationship->getQualifiedRelatedKeyName();
}
if ($relationship instanceof HasOneOrManyThrough) {
return $relationship->getQualifiedForeignKeyName();
}
if (
($relationship instanceof HasOneOrMany) ||
($relationship instanceof BelongsToThrough)
) {
return $relationship->getRelated()->getQualifiedKeyName();
}
/** @var BelongsTo $relationship */
return $relationship->getQualifiedOwnerKeyName();
}
/**
* @return ?array<string>
*/
public function getInValidationRuleValues(): ?array
{
$values = parent::getInValidationRuleValues();
if ($values !== null) {
return $values;
}
$state = $this->getState();
if (blank($state)) {
return null;
}
if ($this->isMultiple()) {
return array_keys($this->getOptionLabels(withDefaults: false));
}
return blank($this->getOptionLabel(withDefault: false)) ? [] : null;
}
public function hasInValidationOnMultipleValues(): bool
{
return $this->isMultiple();
}
public function tableConfiguration(string | Closure $tableConfiguration): static
{
$this->tableConfiguration = $tableConfiguration;
return $this;
}
public function getTableConfiguration(): string
{
return $this->evaluate($this->tableConfiguration) ?? throw new LogicException('The [tableConfiguration()] method must be set when using a [TableSelect] component.');
}
/**
* @return array<mixed>
*/
public function getTableArguments(): array
{
return $this->evaluate($this->tableArguments) ?? [];
}
public function badge(bool | Closure | null $condition = true): static
{
$this->hasBadges = $condition;
return $this;
}
public function hasBadges(): bool
{
return $this->evaluate($this->hasBadges) ?? $this->isMultiple();
}
public function badgeColor(string | Closure | null $color): static
{
$this->badgeColor = $color;
return $this;
}
public function getBadgeColor(): ?string
{
return $this->evaluate($this->badgeColor);
}
/**
* @return array<StateCast>
*/
public function getDefaultStateCasts(): array
{
if ($this->hasCustomStateCasts()) {
return parent::getDefaultStateCasts();
}
if ($this->isMultiple()) {
return [app(OptionsArrayStateCast::class)];
}
return [app(OptionStateCast::class, ['isNullable' => true])];
}
public function toEmbeddedHtml(): string
{
$extraAttributes = $this->getExtraAttributes();
$id = $this->getId();
$isDisabled = $this->isDisabled();
$isMultiple = $this->isMultiple();
$hasBadges = $this->hasBadges();
$badgeColor = $this->getBadgeColor();
$optionLabel = $isMultiple ? null : $this->getOptionLabel();
$optionLabels = $isMultiple ? $this->getOptionLabels() : [];
$placeholder = $this->getPlaceholder();
$attributes = (new FilamentComponentAttributeBag)
->merge([
'aria-labelledby' => "{$id}-label",
'id' => $id,
'role' => 'group',
], escape: false)
->merge($extraAttributes, escape: false)
->class([
'fi-fo-modal-table-select',
'fi-fo-modal-table-select-disabled' => $isDisabled,
'fi-fo-modal-table-select-multiple' => $isMultiple,
]);
ob_start(); ?>
<div <?= $attributes->toHtml() ?>>
<?php if (((! $isMultiple) && filled($optionLabel)) || ($isMultiple && filled($optionLabels))) { ?>
<?php if ($isMultiple && $hasBadges) { ?>
<div class="fi-fo-modal-table-select-badges-ctn">
<?php foreach ($optionLabels as $loopOptionLabel) { ?>
<?= $this->generateBadgeHtml($loopOptionLabel, $badgeColor) ?>
<?php } ?>
</div>
<?php } else { ?>
<div>
<?php if ($hasBadges) { ?>
<?= $this->generateBadgeHtml($optionLabel, $badgeColor) ?>
<?php } elseif ($isMultiple) { ?>
<?php $isLastOption = false; ?>
<?php $optionLabelKeys = array_keys($optionLabels); ?>
<?php $optionLabelLastKey = end($optionLabelKeys); ?>
<?php foreach ($optionLabels as $optionLabelKey => $loopOptionLabel) { ?>
<?= e($loopOptionLabel) . (($optionLabelKey === $optionLabelLastKey) ? '' : ', ') ?>
<?php } ?>
<?php } else { ?>
<?= e($optionLabel) ?>
<?php } ?>
</div>
<?php } ?>
<?php } elseif (filled($placeholder)) { ?>
<div class="fi-fo-modal-table-select-placeholder">
<?= e($placeholder) ?>
</div>
<?php } ?>
<?php if (! $isDisabled) { ?>
<div>
<?= $this->getAction('select')->toHtml() ?>
</div>
<?php } ?>
</div>
<?php return $this->wrapEmbeddedHtml(ob_get_clean(), labelTag: 'div');
}
protected function generateBadgeHtml(string | Htmlable $label, ?string $color): string
{
$attributes = (new FilamentComponentAttributeBag)
->class([
'fi-badge',
'fi-size-md',
])
->color(BadgeComponent::class, $color ?? 'primary');
ob_start(); ?>
<span <?= $attributes->toHtml() ?>>
<span class="fi-badge-label-ctn">
<span class="fi-badge-label">
<?= e($label) ?>
</span>
</span>
</span>
<?php return ob_get_clean();
}
}

View file

@ -0,0 +1,298 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Forms\Components\MorphToSelect\Type;
use Filament\Schemas\Components\Component;
use Filament\Schemas\Components\Concerns\HasLabel;
use Filament\Schemas\Components\Concerns\HasName;
use Filament\Schemas\Components\Utilities\Get;
use Filament\Schemas\Components\Utilities\Set;
use Filament\Support\Concerns\CanBeContained;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use InvalidArgumentException;
use LogicException;
class MorphToSelect extends Component
{
use CanBeContained;
use Concerns\CanAllowHtml;
use Concerns\CanBeMarkedAsRequired;
use Concerns\CanBeNative;
use Concerns\CanBePreloaded;
use Concerns\CanBeSearchable;
use Concerns\HasLoadingMessage;
use HasLabel {
getLabel as getBaseLabel;
}
use HasName;
protected string $view = 'filament-schemas::components.fieldset';
protected bool | Closure $isRequired = false;
protected int | Closure $optionsLimit = 50;
/**
* @var array<Type> | Closure
*/
protected array | Closure $types = [];
protected ?Closure $modifyTypeSelectUsing = null;
protected ?Closure $modifyKeySelectUsing = null;
protected bool | Closure $hasTypeSelectToggleButtons = false;
final public function __construct(string $name)
{
$this->name($name);
}
public static function make(?string $name = null): static
{
$morphToSelectClass = static::class;
$name ??= static::getDefaultName();
if (blank($name)) {
throw new InvalidArgumentException("MorphToSelect of class [$morphToSelectClass] must have a unique name, passed to the [make()] method.");
}
$static = app($morphToSelectClass, ['name' => $name]);
$static->configure();
return $static;
}
protected function setUp(): void
{
parent::setUp();
$this->schema(function (MorphToSelect $component): array {
$relationship = $component->getRelationship();
$typeColumn = $relationship->getMorphType();
$keyColumn = $relationship->getForeignKeyName();
$types = $component->getTypes();
$isRequired = $component->isRequired();
$selectedTypeKey = $component->getRawState()[$typeColumn] ?? null;
$selectedType = $selectedTypeKey ? ($component->getTypes()[$selectedTypeKey] ?? null) : null;
$typeSelect = $component->hasTypeSelectToggleButtons()
? ToggleButtons::make($typeColumn)
->label($component->getLabel())
->hiddenLabel()
->options(array_map(
static fn (Type $type): string => $type->getLabel(),
$types,
))
->inline()
->required($isRequired)
->live()
->afterStateUpdated(function (Set $set) use ($component, $keyColumn): void {
$set($keyColumn, null);
$component->callAfterStateUpdatedForChildComponent();
})
: Select::make($typeColumn)
->label($component->getLabel())
->hiddenLabel()
->options(array_map(
static fn (Type $type): string => $type->getLabel(),
$types,
))
->native($component->isNative())
->required($isRequired)
->live()
->afterStateUpdated(function (Set $set) use ($component, $keyColumn): void {
$set($keyColumn, null);
$component->callAfterStateUpdatedForChildComponent();
});
$keySelect = Select::make($keyColumn)
->label(fn (Get $get): ?string => ($types[$get($typeColumn) ?? ''] ?? null)?->getLabel())
->hiddenLabel()
->options(fn (Select $component, Get $get): ?array => $component->evaluate(($types[$get($typeColumn) ?? ''] ?? null)?->getOptionsUsing))
->dynamicOptions(fn (Select $component): ?bool => $component->isPreloaded() ? null : false)
->getSearchResultsUsing(fn (Select $component, Get $get, $search): ?array => $component->evaluate(($types[$get($typeColumn) ?? ''] ?? null)?->getSearchResultsUsing, ['search' => $search]))
->getOptionLabelUsing(fn (Select $component, Get $get, $value): ?string => $component->evaluate(($types[$get($typeColumn) ?? ''] ?? null)?->getOptionLabelUsing, ['value' => $value]))
->native($component->isNative())
->required(fn (Get $get): bool => filled(($types[$get($typeColumn) ?? ''] ?? null)))
->hidden(fn (Get $get): bool => blank(($types[$get($typeColumn) ?? ''] ?? null)))
->dehydratedWhenHidden()
->searchable($component->isSearchable())
->searchDebounce($component->getSearchDebounce())
->searchPrompt($component->getSearchPrompt())
->searchingMessage($component->getSearchingMessage())
->noOptionsMessage($component->getNoOptionsMessage())
->noSearchResultsMessage($component->getNoSearchResultsMessage())
->loadingMessage($component->getLoadingMessage())
->allowHtml($component->isHtmlAllowed())
->optionsLimit($component->getOptionsLimit())
->preload($component->isPreloaded())
->when(
$component->isLive(),
fn (Select $select) => $select->live(onBlur: $component->isLiveOnBlur()),
)
->afterStateUpdated(function () use ($component): void {
$component->callAfterStateUpdatedForChildComponent();
})
->actionSchemaModel(fn (Get $get): ?string => ($types[$get($typeColumn) ?? ''] ?? null)?->getModel());
if ($callback = $component->getModifyTypeSelectUsingCallback()) {
$typeSelect = $component->evaluate($callback, [
'select' => $typeSelect,
'toggleButtons' => $typeSelect,
]) ?? $typeSelect;
}
if ($callback = $component->getModifyKeySelectUsingCallback()) {
$keySelect = $component->evaluate($callback, [
'select' => $keySelect,
]) ?? $keySelect;
}
if ($callback = $selectedType?->getModifyKeySelectUsingCallback()) {
$keySelect = $component->evaluate($callback, [
'select' => $keySelect,
]) ?? $keySelect;
}
return [$typeSelect, $keySelect];
});
}
public static function getDefaultName(): ?string
{
return null;
}
public function modifyTypeSelectUsing(?Closure $callback): static
{
$this->modifyTypeSelectUsing = $callback;
return $this;
}
public function modifyKeySelectUsing(?Closure $callback): static
{
$this->modifyKeySelectUsing = $callback;
return $this;
}
public function getModifyTypeSelectUsingCallback(): ?Closure
{
return $this->modifyTypeSelectUsing;
}
public function getModifyKeySelectUsingCallback(): ?Closure
{
return $this->modifyKeySelectUsing;
}
public function typeSelectToggleButtons(bool | Closure $condition = true): static
{
$this->hasTypeSelectToggleButtons = $condition;
return $this;
}
public function hasTypeSelectToggleButtons(): bool
{
return (bool) $this->evaluate($this->hasTypeSelectToggleButtons);
}
public function optionsLimit(int | Closure $limit): static
{
$this->optionsLimit = $limit;
return $this;
}
public function required(bool | Closure $condition = true): static
{
$this->isRequired = $condition;
return $this;
}
/**
* @param array<Type> | Closure $types
*/
public function types(array | Closure $types): static
{
$this->types = $types;
return $this;
}
public function getRelationship(): MorphTo
{
$record = $this->getModelInstance();
$relationshipName = $this->getName();
if ($record->hasAttribute($relationshipName) || (! $record->isRelation($relationshipName))) {
throw new LogicException("The relationship [{$relationshipName}] does not exist on the model [{$this->getModel()}].");
}
return $record->{$relationshipName}();
}
/**
* @return array<string, Type>
*/
public function getTypes(): array
{
$types = [];
foreach ($this->evaluate($this->types) as $type) {
$types[$type->getAlias()] = $type;
}
return $types;
}
public function isRequired(): bool
{
return (bool) $this->evaluate($this->isRequired);
}
public function getOptionsLimit(): int
{
return $this->evaluate($this->optionsLimit);
}
public function getLabel(): string | Htmlable | null
{
if (filled($label = $this->getBaseLabel())) {
return $label;
}
$label = (string) str($this->getName())
->afterLast('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
return $this->shouldTranslateLabel ? __($label) : $label;
}
public function callAfterStateUpdatedForChildComponent(bool $shouldBubbleToParents = true): static
{
return parent::callAfterStateUpdated($shouldBubbleToParents);
}
public function callAfterStateUpdated(bool $shouldBubbleToParents = true): static
{
if ($shouldBubbleToParents) {
$this->getContainer()->getParentComponent()?->callAfterStateUpdated();
}
return $this;
}
}

View file

@ -0,0 +1,375 @@
<?php
namespace Filament\Forms\Components\MorphToSelect;
use Closure;
use Filament\Forms\Components\Select;
use Illuminate\Database\Connection;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
use LogicException;
use function Filament\Support\generate_search_column_expression;
use function Filament\Support\generate_search_term_expression;
use function Filament\Support\get_model_label;
class Type
{
protected ?string $label = null;
public Closure $getOptionLabelUsing;
public Closure $getSearchResultsUsing;
public Closure $getOptionsUsing;
public ?Closure $modifyKeySelectUsing = null;
protected ?Closure $modifyOptionsQueryUsing = null;
/**
* @var array<string> | null
*/
protected ?array $searchColumns = null;
protected ?string $titleAttribute = null;
protected ?Closure $getOptionLabelFromRecordUsing = null;
protected int $optionsLimit = 50;
/**
* @var class-string<Model>
*/
protected string $model;
protected ?bool $isSearchForcedCaseInsensitive = null;
/**
* @param class-string<Model> $model
*/
final public function __construct(string $model)
{
$this->model($model);
$this->setUp();
}
/**
* @param class-string<Model> $model
*/
public static function make(string $model): static
{
return app(static::class, ['model' => $model]);
}
protected function setUp(): void
{
$this->getSearchResultsUsing(function (Select $component, ?string $search): array {
$query = $this->getModel()::query();
if ($this->modifyOptionsQueryUsing) {
$query = $component->evaluate($this->modifyOptionsQueryUsing, [
'query' => $query,
]) ?? $query;
}
/** @var Connection $databaseConnection */
$databaseConnection = $query->getConnection();
$isForcedCaseInsensitive = $this->isSearchForcedCaseInsensitive();
$isFirst = true;
$search = generate_search_term_expression($search, $isForcedCaseInsensitive, $databaseConnection);
$query->where(function (Builder $query) use ($isFirst, $isForcedCaseInsensitive, $databaseConnection, $search): Builder {
foreach ($this->getSearchColumns() as $searchColumn) {
$whereClause = $isFirst ? 'where' : 'orWhere';
$query->{$whereClause}(
generate_search_column_expression($searchColumn, $isForcedCaseInsensitive, $databaseConnection),
'like',
"%{$search}%",
);
$isFirst = false;
}
return $query;
});
$baseQuery = $query->getQuery();
if (isset($baseQuery->limit)) {
$component->optionsLimit($baseQuery->limit);
} else {
$query->limit($component->getOptionsLimit());
}
$keyName = $query->getModel()->getKeyName();
$qualifiedKeyName = $query->getModel()->getQualifiedKeyName();
if ($this->hasOptionLabelFromRecordUsingCallback()) {
return $query
->get()
->mapWithKeys(fn (Model $record) => [
$record->{$keyName} => $this->getOptionLabelFromRecord($record),
])
->toArray();
}
$titleAttribute = $this->getTitleAttribute();
// Qualify the column names so they are not ambiguous when the query has been
// modified to include a join (for example, through `modifyOptionsQueryUsing()`).
$qualifiedTitleAttribute = str_contains($titleAttribute, '->')
? $titleAttribute
: $query->qualifyColumn($titleAttribute);
if (empty($query->getQuery()->orders)) {
$query->orderBy($qualifiedTitleAttribute);
}
return $query
->pluck($qualifiedTitleAttribute, $qualifiedKeyName)
->toArray();
});
$this->getOptionsUsing(function (Select $component): ?array {
if (($component->isSearchable()) && ! $component->isPreloaded()) {
return null;
}
$query = $this->getModel()::query();
if ($this->modifyOptionsQueryUsing) {
$query = $component->evaluate($this->modifyOptionsQueryUsing, [
'query' => $query,
]) ?? $query;
}
$baseQuery = $query->getQuery();
if (isset($baseQuery->limit)) {
$component->optionsLimit($baseQuery->limit);
} elseif ($component->isSearchable() && filled($this->getSearchColumns())) {
$query->limit($component->getOptionsLimit());
}
$keyName = $query->getModel()->getKeyName();
$qualifiedKeyName = $query->getModel()->getQualifiedKeyName();
if ($this->hasOptionLabelFromRecordUsingCallback()) {
return $query
->get()
->mapWithKeys(fn (Model $record) => [
$record->{$keyName} => $this->getOptionLabelFromRecord($record),
])
->toArray();
}
$titleAttribute = $this->getTitleAttribute();
// Qualify the column names so they are not ambiguous when the query has been
// modified to include a join (for example, through `modifyOptionsQueryUsing()`).
$qualifiedTitleAttribute = str_contains($titleAttribute, '->')
? $titleAttribute
: $query->qualifyColumn($titleAttribute);
if (empty($query->getQuery()->orders)) {
$query->orderBy($qualifiedTitleAttribute);
}
return $query
->pluck($qualifiedTitleAttribute, $qualifiedKeyName)
->toArray();
});
$this->getOptionLabelUsing(function (Select $component, $value) {
$query = $this->getModel()::query();
// Qualify the key name so it is not ambiguous when the query has been modified to
// include a join (for example, through `modifyOptionsQueryUsing()`).
$query->where($query->getModel()->getQualifiedKeyName(), $value);
if ($this->modifyOptionsQueryUsing) {
$query = $component->evaluate($this->modifyOptionsQueryUsing, [
'query' => $query,
]) ?? $query;
}
$record = $query->first();
if (! $record) {
return null;
}
if ($this->hasOptionLabelFromRecordUsingCallback()) {
return $this->getOptionLabelFromRecord($record);
}
$titleAttribute = $this->getTitleAttribute();
if (str_contains($titleAttribute, '->')) {
$titleAttribute = str_replace('->', '.', $titleAttribute);
}
return data_get($record, $titleAttribute);
});
}
/**
* @param class-string<Model> $model
*/
public function model(string $model): static
{
$this->model = $model;
return $this;
}
public function label(?string $label): static
{
$this->label = $label;
return $this;
}
public function titleAttribute(?string $name): static
{
$this->titleAttribute = $name;
return $this;
}
/**
* @deprecated Use `titleAttribute()` instead.
*/
public function titleColumnName(?string $name): static
{
$this->titleAttribute($name);
return $this;
}
/**
* @param array<string> | null $columns
*/
public function searchColumns(?array $columns): static
{
$this->searchColumns = $columns;
return $this;
}
public function modifyKeySelectUsing(?Closure $callback): static
{
$this->modifyKeySelectUsing = $callback;
return $this;
}
public function modifyOptionsQueryUsing(?Closure $callback): static
{
$this->modifyOptionsQueryUsing = $callback;
return $this;
}
public function getOptionsUsing(Closure $callback): static
{
$this->getOptionsUsing = $callback;
return $this;
}
public function getSearchResultsUsing(Closure $callback): static
{
$this->getSearchResultsUsing = $callback;
return $this;
}
public function getOptionLabelUsing(Closure $callback): static
{
$this->getOptionLabelUsing = $callback;
return $this;
}
public function getOptionLabelFromRecordUsing(?Closure $callback): static
{
$this->getOptionLabelFromRecordUsing = $callback;
return $this;
}
public function getOptionLabelFromRecord(Model $record): string
{
return ($this->getOptionLabelFromRecordUsing)($record);
}
public function hasOptionLabelFromRecordUsingCallback(): bool
{
return $this->getOptionLabelFromRecordUsing !== null;
}
public function getModifyKeySelectUsingCallback(): ?Closure
{
return $this->modifyKeySelectUsing;
}
/**
* @return class-string<Model>
*/
public function getModel(): string
{
return $this->model;
}
public function getLabel(): string
{
return $this->label ?? Str::ucfirst(get_model_label($this->getModel()));
}
public function getAlias(): string
{
return app($this->getModel())->getMorphClass();
}
/**
* @return array<string>
*/
public function getSearchColumns(): ?array
{
return $this->searchColumns ?? [$this->getTitleAttribute()];
}
public function getTitleAttribute(): string
{
if (blank($this->titleAttribute)) {
throw new LogicException("MorphToSelect type [{$this->getModel()}] must have a [titleAttribute()] set.");
}
return $this->titleAttribute;
}
public function getOptionsLimit(): int
{
return $this->optionsLimit;
}
public function forceSearchCaseInsensitive(?bool $condition = true): static
{
$this->isSearchForcedCaseInsensitive = $condition;
return $this;
}
public function isSearchForcedCaseInsensitive(): ?bool
{
return $this->isSearchForcedCaseInsensitive;
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace Filament\Forms\Components;
/**
* @deprecated Use `Select` with the `multiple()` method instead.
*/
class MultiSelect extends Select
{
public function isMultiple(): bool
{
return true;
}
}

View file

@ -0,0 +1,102 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Concerns\HasExtraAlpineAttributes;
class OneTimeCodeInput extends Field implements HasEmbeddedView
{
use Concerns\CanBeReadOnly;
use Concerns\HasExtraInputAttributes;
use Concerns\HasPlaceholder;
use HasExtraAlpineAttributes;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.one-time-code-input';
protected int | Closure $length = 6;
protected function setUp(): void
{
parent::setUp();
$this->rule('numeric'); // Integer validation does not allow leading zeros.
$this->rule(static fn (OneTimeCodeInput $component): string => "digits:{$component->getLength()}");
}
public function length(int | Closure $length): static
{
$this->length = $length;
return $this;
}
public function getLength(): int
{
return $this->evaluate($this->length);
}
public function toEmbeddedHtml(): string
{
$length = $this->getLength();
$entangle = $this->applyStateBindingModifiers("\$entangle('{$this->getStatePath()}')");
$containerAttributes = $this->getExtraAttributeBag()
->merge($this->getExtraAlpineAttributes(), escape: false)
->class(['fi-one-time-code-input-ctn']);
// The first input carries the `one-time-code` autocomplete so that browser and OS
// autofill targets it. The component then distributes the filled value across the
// remaining inputs.
$inputAttributes = $this->getExtraInputAttributeBag()
->merge([
'autofocus' => $this->isAutofocused(),
'disabled' => $this->isDisabled(),
'id' => $this->getId(),
'readonly' => $this->isReadOnly(),
'required' => $this->isRequired(),
], escape: false);
// The remaining inputs mirror the first input's resolved `disabled` and `readonly`
// state so that an `extraInputAttributes()` override applies to every digit.
$isDisabled = filter_var($inputAttributes->get('disabled'), FILTER_VALIDATE_BOOLEAN);
$isReadOnly = filter_var($inputAttributes->get('readonly'), FILTER_VALIDATE_BOOLEAN);
ob_start(); ?>
<div x-data="{ code: $wire.<?= $entangle ?>, }">
<div
x-data="filamentOneTimeCodeInput"
x-modelable="state"
x-model="code"
role="group"
<?= $containerAttributes->toHtml() ?>
>
<?php foreach (range(0, $length - 1) as $index) { ?>
<?php if ($index === 0) { ?>
<input
autocomplete="one-time-code"
inputmode="numeric"
type="text"
<?= $inputAttributes->class(['fi-one-time-code-input-digit'])->toHtml() ?>
/>
<?php } else { ?>
<input
aria-label="<?= e(__('filament::components/input/one-time-code.aria_label', ['position' => $index + 1, 'count' => $length])) ?>"
autocomplete="off"
inputmode="numeric"
type="text"
<?php if ($isDisabled) { ?> disabled <?php } ?>
<?php if ($isReadOnly) { ?> readonly <?php } ?>
class="fi-one-time-code-input-digit"
/>
<?php } ?>
<?php } ?>
</div>
</div>
<?php return $this->wrapEmbeddedHtml(ob_get_clean());
}
}

View file

@ -0,0 +1,23 @@
<?php
namespace Filament\Forms\Components;
use Filament\Infolists\Components\TextEntry;
/**
* @deprecated Use `TextEntry` with the `state()` method instead.
*/
class Placeholder extends TextEntry
{
public function content(mixed $content): static
{
$this->state($content);
return $this;
}
public function getContent(): mixed
{
return $this->getState();
}
}

View file

@ -0,0 +1,161 @@
<?php
namespace Filament\Forms\Components;
use Closure;
use Filament\Schemas\Components\StateCasts\BooleanStateCast;
use Filament\Schemas\Components\StateCasts\Contracts\StateCast;
use Filament\Schemas\Components\StateCasts\OptionStateCast;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Enums\GridDirection;
class Radio extends Field implements Contracts\CanDisableOptions, HasEmbeddedView
{
use Concerns\CanDisableOptions;
use Concerns\CanDisableOptionsWhenSelectedInSiblingRepeaterItems;
use Concerns\CanFixIndistinctState;
use Concerns\HasDescriptions;
use Concerns\HasExtraInputAttributes;
use Concerns\HasGridDirection;
use Concerns\HasOptions;
protected ?string $publishedViewOverrideCheckPath = 'filament-forms::components.radio';
protected bool | Closure $isInline = false;
public function boolean(?string $trueLabel = null, ?string $falseLabel = null): static
{
$this->options([
1 => $trueLabel ?? __('filament-forms::components.radio.boolean.true'),
0 => $falseLabel ?? __('filament-forms::components.radio.boolean.false'),
]);
$this->stateCast(app(BooleanStateCast::class, ['isStoredAsInt' => true]));
return $this;
}
public function inline(bool | Closure $condition = true): static
{
$this->isInline = $condition;
return $this;
}
public function isInline(): bool
{
return (bool) $this->evaluate($this->isInline);
}
public function toEmbeddedHtml(): string
{
$extraInputAttributeBag = $this->getExtraInputAttributeBag();
$gridDirection = $this->getGridDirection() ?? GridDirection::Column;
$id = $this->getId();
$isDisabled = $this->isDisabled();
$isInline = $this->isInline();
$statePath = $this->getStatePath();
$wireModelAttribute = $this->applyStateBindingModifiers('wire:model');
$isAutofocused = $this->isAutofocused();
$hasError = $this->hasErrorForPath($statePath);
$containerAttributes = $this->getExtraAttributeBag();
if (! $isInline) {
$containerAttributes = $containerAttributes->grid($this->getColumns(), $gridDirection);
}
$containerAttributes = $containerAttributes
->merge([
'aria-labelledby' => "{$id}-label",
'role' => 'radiogroup',
], escape: false)
->class([
'fi-fo-radio',
'fi-inline' => $isInline,
]);
ob_start(); ?>
<div <?= $containerAttributes->toHtml() ?>>
<?php $first = true; ?>
<?php foreach ($this->getOptions() as $value => $label) { ?>
<?php
$inputAttributes = $extraInputAttributeBag
->merge([
'autofocus' => $first && $isAutofocused,
'disabled' => $isDisabled || $this->isOptionDisabled($value, $label),
'id' => e($id . '-' . $value),
'name' => $id,
'value' => e($value),
$wireModelAttribute => $statePath,
], escape: false)
->class([
'fi-radio-input',
'fi-valid' => ! $hasError,
'fi-invalid' => $hasError,
]);
$first = false;
?>
<label class="fi-fo-radio-label">
<input type="radio" <?= $inputAttributes->toHtml() ?> />
<div class="fi-fo-radio-label-text">
<p><?= e($label) ?></p>
<?php if ($this->hasDescription($value)) { ?>
<p class="fi-fo-radio-label-description">
<?= e($this->getDescription($value)) ?>
</p>
<?php } ?>
</div>
</label>
<?php } ?>
</div>
<?php return $this->wrapEmbeddedHtml(ob_get_clean(), labelTag: 'div');
}
public function getDefaultState(): mixed
{
$state = parent::getDefaultState();
if (is_bool($state)) {
return $state ? 1 : 0;
}
return $state;
}
/**
* @return array<StateCast>
*/
public function getDefaultStateCasts(): array
{
if ($this->hasCustomStateCasts() || filled($this->getEnum())) {
return parent::getDefaultStateCasts();
}
return [app(OptionStateCast::class, ['isNullable' => true])];
}
/**
* @return ?array<string>
*/
public function getInValidationRuleValues(): ?array
{
$values = parent::getInValidationRuleValues();
if ($values !== null) {
return $values;
}
return array_keys($this->getEnabledOptions());
}
public function hasNullableBooleanState(): bool
{
return true;
}
}

View file

@ -0,0 +1,16 @@
<?php
namespace Filament\Forms\Components;
/**
* @deprecated Use `Repeater` with the `relationship()` method instead.
*/
class RelationshipRepeater extends Repeater
{
protected function setUp(): void
{
parent::setUp();
$this->relationship();
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,65 @@
<?php
namespace Filament\Forms\Components\Repeater;
use Closure;
use Filament\Support\Components\Component;
use Filament\Support\Concerns\CanWrapHeader;
use Filament\Support\Concerns\HasAlignment;
use Filament\Support\Concerns\HasVerticalAlignment;
use Filament\Support\Concerns\HasWidth;
use Illuminate\Contracts\Support\Htmlable;
class TableColumn extends Component
{
use CanWrapHeader;
use HasAlignment;
use HasVerticalAlignment;
use HasWidth;
protected string $evaluationIdentifier = 'column';
protected bool | Closure $isHeaderLabelHidden = false;
protected bool | Closure $isMarkedAsRequired = false;
public function __construct(protected string | Htmlable | Closure $label) {}
public static function make(string | Htmlable | Closure $label): static
{
$static = app(static::class, ['label' => $label]);
$static->configure();
return $static;
}
public function hiddenHeaderLabel(bool | Closure $condition = true): static
{
$this->isHeaderLabelHidden = $condition;
return $this;
}
public function getLabel(): string | Htmlable
{
return $this->evaluate($this->label);
}
public function isHeaderLabelHidden(): bool
{
return (bool) $this->evaluate($this->isHeaderLabelHidden);
}
public function markAsRequired(bool | Closure $condition = true): static
{
$this->isMarkedAsRequired = $condition;
return $this;
}
public function isMarkedAsRequired(): bool
{
return (bool) $this->evaluate($this->isMarkedAsRequired);
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,102 @@
<?php
namespace Filament\Forms\Components\RichEditor\Actions;
use Filament\Actions\Action;
use Filament\Forms\Components\FileUpload;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\EditorCommand;
use Filament\Forms\Components\TextInput;
use Filament\Support\Enums\Width;
use Illuminate\Support\Str;
use Livewire\Component;
class AttachFilesAction
{
public static function make(): Action
{
return Action::make('attachFiles')
->label(__('filament-forms::components.rich_editor.actions.attach_files.label'))
->modalHeading(__('filament-forms::components.rich_editor.actions.attach_files.modal.heading'))
->modalWidth(Width::Large)
->fillForm(fn (array $arguments): array => [
'alt' => $arguments['alt'] ?? null,
])
->schema(fn (array $arguments, RichEditor $component): array => [
FileUpload::make('file')
->label(filled($arguments['src'] ?? null)
? __('filament-forms::components.rich_editor.actions.attach_files.modal.form.file.label.existing')
: __('filament-forms::components.rich_editor.actions.attach_files.modal.form.file.label.new'))
->acceptedFileTypes($component->getFileAttachmentsAcceptedFileTypes())
->maxSize($component->getFileAttachmentsMaxSize())
->storeFiles(false)
->required(blank($arguments['src'] ?? null))
->hiddenLabel(blank($arguments['src'] ?? null)),
TextInput::make('alt')
->label(filled($arguments['src'] ?? null)
? __('filament-forms::components.rich_editor.actions.attach_files.modal.form.alt.label.existing')
: __('filament-forms::components.rich_editor.actions.attach_files.modal.form.alt.label.new'))
->maxLength(1000),
])
->action(function (array $arguments, array $data, RichEditor $component, Component $livewire): void {
if ($data['file'] ?? null) {
$id = (string) Str::orderedUuid();
data_set($livewire, "componentFileAttachments.{$component->getStatePath()}.{$id}", $data['file']);
$src = $component->getUploadedFileAttachmentTemporaryUrl($data['file']);
}
if (filled($arguments['src'] ?? null)) {
// Fixes an issue where the editor selection is sent as text instead of a node,
// which causes the image update to fail when though the image is selected.
if ($arguments['editorSelection']['type'] !== 'node') {
$arguments['editorSelection']['type'] = 'node';
$arguments['editorSelection']['anchor']--;
unset($arguments['editorSelection']['head']);
}
$id ??= $arguments['id'] ?? null;
$src ??= $arguments['src'];
$component->runCommands(
[
EditorCommand::make('updateAttributes', arguments: [
'image',
[
'alt' => $data['alt'] ?? null,
'id' => $id,
'src' => $src,
],
]),
],
editorSelection: $arguments['editorSelection'],
);
return;
}
if (blank($id ?? null)) {
return;
}
if (blank($src ?? null)) {
return;
}
$component->runCommands(
[
EditorCommand::make('insertContent', arguments: [[
'type' => 'image',
'attrs' => [
'alt' => $data['alt'] ?? null,
'id' => $id,
'src' => $src,
],
]]),
],
editorSelection: $arguments['editorSelection'],
);
});
}
}

View file

@ -0,0 +1,123 @@
<?php
namespace Filament\Forms\Components\RichEditor\Actions;
use Filament\Actions\Action;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\EditorCommand;
use Filament\Support\Enums\Width;
class CustomBlockAction
{
public const NAME = 'customBlock';
public static function make(): Action
{
return Action::make(static::NAME)
->fillForm(fn (array $arguments): ?array => $arguments['config'] ?? null)
->modalHeading(function (array $arguments, RichEditor $component): ?string {
$block = $component->getCustomBlock($arguments['id']);
if (blank($block)) {
return null;
}
return $block::getLabel();
})
->modalWidth(Width::Large)
->modalSubmitActionLabel(fn (array $arguments): ?string => match ($arguments['mode']) {
'insert' => __('filament-forms::components.rich_editor.actions.custom_block.modal.actions.insert.label'),
'edit' => __('filament-forms::components.rich_editor.actions.custom_block.modal.actions.save.label'),
default => null,
})
->bootUsing(function (Action $action, array $arguments, RichEditor $component) {
$block = $component->getCustomBlock($arguments['id']);
if (blank($block)) {
return;
}
return $block::configureEditorAction($action);
})
->action(function (array $arguments, array $data, RichEditor $component): void {
$block = $component->getCustomBlock($arguments['id']);
if (blank($block)) {
return;
}
$customBlockContent = [
'type' => 'customBlock',
'attrs' => [
'config' => $data,
'id' => $arguments['id'],
'label' => $block::getPreviewLabel($data),
'preview' => base64_encode($block::toPreviewHtml($data)),
'shouldApplyProseStylingToPreview' => $block::shouldApplyProseStylingToPreview($data),
],
];
// Insert at the dragged position
if (filled($arguments['dragPosition'] ?? null)) {
$component->runCommands(
[
EditorCommand::make(
'insertContentAt',
arguments: [
$arguments['dragPosition'],
$customBlockContent,
],
),
],
);
return;
}
// Insert after the currently selected node
if (
($arguments['editorSelection']['type'] === 'node') &&
(($arguments['mode'] ?? null) === 'insert')
) {
$component->runCommands(
[
EditorCommand::make(
'insertContentAt',
arguments: [
($arguments['editorSelection']['anchor'] ?? -1) + 1,
$customBlockContent,
],
),
],
);
return;
}
// Fixes an issue where the editor selection is sent as text instead of a node,
// which causes the block update to fail even though the block is selected.
if (
(($arguments['mode'] ?? null) === 'edit') &&
($arguments['editorSelection']['type'] !== 'node')
) {
$arguments['editorSelection']['type'] = 'node';
$arguments['editorSelection']['anchor']--;
unset($arguments['editorSelection']['head']);
}
// Insert at the current selection
$component->runCommands(
[
EditorCommand::make(
'insertContent',
arguments: [
$customBlockContent,
],
),
],
editorSelection: $arguments['editorSelection'],
);
});
}
}

View file

@ -0,0 +1,149 @@
<?php
namespace Filament\Forms\Components\RichEditor\Actions;
use Filament\Actions\Action;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\EditorCommand;
use Filament\Forms\Components\Select;
use Filament\Forms\Components\TextInput;
use Filament\Forms\Components\Toggle;
use Filament\Schemas\Components\Grid;
use Filament\Support\Enums\Width;
class GridAction
{
public static function make(): Action
{
return Action::make('grid')
->label(__('filament-forms::components.rich_editor.actions.grid.label'))
->modalHeading(__('filament-forms::components.rich_editor.actions.grid.modal.heading'))
->modalWidth(Width::Large)
->schema([
Grid::make()
->schema([
Select::make('preset')
->label(__('filament-forms::components.rich_editor.actions.grid.modal.form.preset.label'))
->placeholder(__('filament-forms::components.rich_editor.actions.grid.modal.form.preset.placeholder'))
->options([
'two' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.two'),
'three' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.three'),
'four' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.four'),
'five' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.five'),
'two_start_third' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.two_start_third'),
'two_end_third' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.two_end_third'),
'two_start_fourth' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.two_start_fourth'),
'two_end_fourth' => __('filament-forms::components.rich_editor.actions.grid.modal.form.preset.options.two_end_fourth'),
])
->afterStateUpdatedJs(<<<'JS'
Object.entries({
two: {
columns: 2,
isAsymmetric: false,
startSpan: null,
endSpan: null,
},
three: {
columns: 3,
isAsymmetric: false,
startSpan: null,
endSpan: null,
},
four: {
columns: 4,
isAsymmetric: false,
startSpan: null,
endSpan: null,
},
five: {
columns: 5,
isAsymmetric: false,
startSpan: null,
endSpan: null,
},
two_start_third: {
isAsymmetric: true,
startSpan: 1,
endSpan: 2,
},
two_end_third: {
isAsymmetric: true,
startSpan: 2,
endSpan: 1,
},
two_start_fourth: {
isAsymmetric: true,
startSpan: 1,
endSpan: 3,
},
two_end_fourth: {
isAsymmetric: true,
startSpan: 3,
endSpan: 1,
},
}[$state] ?? {}).forEach(([key, value]) => $set(key, value))
JS)
->dehydrated(false),
Select::make('fromBreakpoint')
->label(__('filament-forms::components.rich_editor.actions.grid.modal.form.from_breakpoint.label'))
->options([
'default' => __('filament-forms::components.rich_editor.actions.grid.modal.form.from_breakpoint.options.default'),
'sm' => __('filament-forms::components.rich_editor.actions.grid.modal.form.from_breakpoint.options.sm'),
'md' => __('filament-forms::components.rich_editor.actions.grid.modal.form.from_breakpoint.options.md'),
'lg' => __('filament-forms::components.rich_editor.actions.grid.modal.form.from_breakpoint.options.lg'),
'xl' => __('filament-forms::components.rich_editor.actions.grid.modal.form.from_breakpoint.options.xl'),
'2xl' => __('filament-forms::components.rich_editor.actions.grid.modal.form.from_breakpoint.options.2xl'),
])
->default('lg'),
Toggle::make('isAsymmetric')
->label(__('filament-forms::components.rich_editor.actions.grid.modal.form.is_asymmetric.label'))
->columnSpanFull(),
TextInput::make('columns')
->label(__('filament-forms::components.rich_editor.actions.grid.modal.form.columns.label'))
->integer()
->minValue(2)
->maxValue(12)
->default(2)
->hiddenJs(<<<'JS'
$get('isAsymmetric')
JS),
TextInput::make('startSpan')
->label(__('filament-forms::components.rich_editor.actions.grid.modal.form.start_span.label'))
->integer()
->minValue(1)
->maxValue(12)
->visibleJs(<<<'JS'
$get('isAsymmetric')
JS),
TextInput::make('endSpan')
->label(__('filament-forms::components.rich_editor.actions.grid.modal.form.end_span.label'))
->integer()
->minValue(1)
->maxValue(12)
->visibleJs(<<<'JS'
$get('isAsymmetric')
JS),
]),
])
->action(function (array $arguments, array $data, RichEditor $component): void {
if ($data['isAsymmetric'] ?? false) {
$columns = [(int) ($data['startSpan'] ?? 1), (int) ($data['endSpan'] ?? 1)];
} else {
$columns = array_fill(0, max(2, (int) ($data['columns'] ?? 2)), 1);
}
$component->runCommands(
[
EditorCommand::make(
'insertGrid',
arguments: [[
'fromBreakpoint' => $data['fromBreakpoint'] ?? 'lg',
'columns' => $columns,
]],
),
],
editorSelection: $arguments['editorSelection'],
);
});
}
}

View file

@ -0,0 +1,67 @@
<?php
namespace Filament\Forms\Components\RichEditor\Actions;
use Filament\Actions\Action;
use Filament\Forms\Components\Checkbox;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\EditorCommand;
use Filament\Forms\Components\TextInput;
use Filament\Support\Enums\Width;
class LinkAction
{
public static function make(): Action
{
return Action::make('link')
->label(__('filament-forms::components.rich_editor.actions.link.label'))
->modalHeading(__('filament-forms::components.rich_editor.actions.link.modal.heading'))
->modalWidth(Width::Large)
->fillForm(fn (array $arguments): array => [
'url' => $arguments['url'] ?? null,
'shouldOpenInNewTab' => $arguments['shouldOpenInNewTab'] ?? false,
])
->schema([
TextInput::make('url')
->label(__('filament-forms::components.rich_editor.actions.link.modal.form.url.label'))
->inputMode('url'),
Checkbox::make('shouldOpenInNewTab')
->label(__('filament-forms::components.rich_editor.actions.link.modal.form.should_open_in_new_tab.label')),
])
->action(function (array $arguments, array $data, RichEditor $component): void {
$isSingleCharacterSelection = ($arguments['editorSelection']['head'] ?? null) === ($arguments['editorSelection']['anchor'] ?? null);
if (blank($data['url'] ?? null)) {
$component->runCommands(
[
...($isSingleCharacterSelection ? [EditorCommand::make(
'extendMarkRange',
arguments: ['link'],
)] : []),
EditorCommand::make('unsetLink'),
],
editorSelection: $arguments['editorSelection'],
);
return;
}
$component->runCommands(
[
...($isSingleCharacterSelection ? [EditorCommand::make(
'extendMarkRange',
arguments: ['link'],
)] : []),
EditorCommand::make(
'setLink',
arguments: [[
'href' => $data['url'],
'target' => $data['shouldOpenInNewTab'] ? '_blank' : null,
]],
),
],
editorSelection: $arguments['editorSelection'],
);
});
}
}

View file

@ -0,0 +1,90 @@
<?php
namespace Filament\Forms\Components\RichEditor\Actions;
use Filament\Actions\Action;
use Filament\Forms\Components\ColorPicker;
use Filament\Forms\Components\RichEditor;
use Filament\Forms\Components\RichEditor\EditorCommand;
use Filament\Forms\Components\RichEditor\TextColor;
use Filament\Forms\Components\Select;
use Filament\Support\Enums\Width;
use Illuminate\Support\Arr;
class TextColorAction
{
public static function make(): Action
{
return Action::make('textColor')
->label(__('filament-forms::components.rich_editor.actions.text_color.label'))
->modalHeading(__('filament-forms::components.rich_editor.actions.text_color.modal.heading'))
->modalWidth(Width::Large)
->fillForm(fn (array $arguments, RichEditor $component): ?array => filled($arguments['color'] ?? null) ? [
'color' => array_key_exists($arguments['color'], $options = $component->getTextColors()) ? $arguments['color'] : null,
'customColor' => $component->hasCustomTextColors() && (! array_key_exists($arguments['color'], $options)) ? $arguments['color'] : null,
] : null)
->schema(function (RichEditor $component) {
$options = Arr::mapWithKeys(
$component->getTextColors(),
fn (TextColor $color, string $name): array => [$name => <<<HTML
<div class="fi-fo-rich-editor-text-color-select-option">
<div class="fi-fo-rich-editor-text-color-select-option-preview" style="--color: {$color->getColor()}; --dark-color: {$color->getDarkColor()}"></div>
<div>{$color->getSafeLabelHtml()}</div>
</div>
HTML],
);
return [
Select::make('color')
->label(__('filament-forms::components.rich_editor.actions.text_color.modal.form.color.label'))
->options($options)
->allowHtml()
->native(false)
->visible(filled($options)),
ColorPicker::make('customColor')
->label(__('filament-forms::components.rich_editor.actions.text_color.modal.form.custom_color.label'))
->visibleJs(<<<'JS'
! $get('color')
JS)
->visible($component->hasCustomTextColors()),
];
})
->action(function (array $arguments, array $data, RichEditor $component): void {
$isSingleCharacterSelection = ($arguments['editorSelection']['head'] ?? null) === ($arguments['editorSelection']['anchor'] ?? null);
$color = $data['color'] ?? $data['customColor'] ?? null;
if (blank($color)) {
$component->runCommands(
[
...($isSingleCharacterSelection ? [EditorCommand::make(
'extendMarkRange',
arguments: ['textColor'],
)] : []),
EditorCommand::make('unsetTextColor'),
],
editorSelection: $arguments['editorSelection'],
);
return;
}
$component->runCommands(
[
...($isSingleCharacterSelection ? [EditorCommand::make(
'extendMarkRange',
arguments: ['link'],
)] : []),
EditorCommand::make(
'setTextColor',
arguments: [[
'color' => $color,
]],
),
],
editorSelection: $arguments['editorSelection'],
);
});
}
}

View file

@ -0,0 +1,35 @@
<?php
namespace Filament\Forms\Components\RichEditor;
use Illuminate\Contracts\Support\Arrayable;
class EditorCommand implements Arrayable
{
/**
* @param array<mixed> $arguments
*/
public function __construct(
public readonly string $name,
public readonly array $arguments = [],
) {}
/**
* @param array<mixed> $arguments
*/
public static function make(string $name, array $arguments = []): static
{
return app(static::class, ['name' => $name, 'arguments' => $arguments]);
}
/**
* @return array{name: string, arguments: array<mixed>}
*/
public function toArray(): array
{
return [
'name' => $this->name,
'arguments' => $this->arguments,
];
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Filament\Forms\Components\RichEditor\FileAttachmentProviders\Contracts;
use Filament\Forms\Components\RichEditor\RichContentAttribute;
use Livewire\Features\SupportFileUploads\TemporaryUploadedFile;
interface FileAttachmentProvider
{
public function attribute(RichContentAttribute $attribute): static;
public function getFileAttachmentUrl(mixed $file): ?string;
public function saveUploadedFileAttachment(TemporaryUploadedFile $file): mixed;
public function getDefaultFileAttachmentVisibility(): ?string;
public function isExistingRecordRequiredToSaveNewFileAttachments(): bool;
/**
* @param array<mixed> $exceptIds
*/
public function cleanUpFileAttachments(array $exceptIds): void;
}

View file

@ -0,0 +1,259 @@
<?php
namespace Filament\Forms\Components\RichEditor;
use Closure;
use Illuminate\Support\Arr;
class MentionProvider
{
protected ?Closure $getSearchResultsUsing = null;
/**
* @var array<string> | Closure
*/
protected array | Closure $items = [];
/**
* @var array<string, mixed>|Closure|null
*/
protected array | Closure | null $extraAttributes = null;
protected ?Closure $getLabelsUsing = null;
protected ?Closure $getUrlUsing = null;
protected ?string $noItemsMessage = null;
protected ?string $noSearchResultsMessage = null;
protected ?string $searchingMessage = null;
protected ?string $searchPrompt = null;
final public function __construct(
protected string $char,
) {}
public static function make(string $char): static
{
return app(static::class, ['char' => $char]);
}
public function getSearchResultsUsing(?Closure $callback): static
{
$this->getSearchResultsUsing = $callback;
return $this;
}
/**
* @param array<string> | Closure $items
*/
public function items(array | Closure $items): static
{
$this->items = $items;
return $this;
}
/**
* @param Closure(array<string>): array<string, string> $callback
*/
public function getLabelsUsing(?Closure $callback): static
{
$this->getLabelsUsing = $callback;
return $this;
}
/**
* @param Closure(string $id, string $label): ?string $callback
*/
public function url(?Closure $callback): static
{
// Security: If this URL is derived from user input, validate it
// to prevent XSS via `javascript:` protocol URLs rendered
// in `href` attributes.
$this->getUrlUsing = $callback;
return $this;
}
/**
* @param array<string, mixed>|Closure(): array<string, mixed> $attributes
*/
public function extraAttributes(array | Closure $attributes): static
{
// Security: Attribute values are not escaped when rendered. Never
// pass unsanitized user input as attribute names or values.
$this->extraAttributes = $attributes;
return $this;
}
public function noItemsMessage(?string $message): static
{
$this->noItemsMessage = $message;
return $this;
}
public function noSearchResultsMessage(?string $message): static
{
$this->noSearchResultsMessage = $message;
return $this;
}
public function searchingMessage(?string $message): static
{
$this->searchingMessage = $message;
return $this;
}
public function searchPrompt(?string $message): static
{
$this->searchPrompt = $message;
return $this;
}
public function getChar(): string
{
return $this->char;
}
/**
* @return array<string, mixed>
*/
public function getExtraAttributes(): array
{
$attributes = $this->extraAttributes;
if ($attributes instanceof Closure) {
$attributes = $attributes();
}
return is_array($attributes) ? $attributes : [];
}
public function getNoItemsMessage(): string
{
return $this->noItemsMessage ?? __('filament-forms::components.rich_editor.mentions.no_options_message');
}
public function getNoSearchResultsMessage(): string
{
return $this->noSearchResultsMessage ?? __('filament-forms::components.rich_editor.mentions.no_search_results_message');
}
public function getSearchingMessage(): string
{
return $this->searchingMessage ?? __('filament-forms::components.rich_editor.mentions.searching_message');
}
public function getSearchPrompt(): string
{
return $this->searchPrompt ?? __('filament-forms::components.rich_editor.mentions.search_prompt');
}
public function getUrl(string $id, string $label): ?string
{
if (! ($this->getUrlUsing instanceof Closure)) {
return null;
}
return ($this->getUrlUsing)($id, $label);
}
public function hasUrl(): bool
{
return $this->getUrlUsing instanceof Closure;
}
/**
* @param array<string> $ids
* @return array<string, string>
*/
public function getLabels(array $ids): array
{
if ($this->getLabelsUsing instanceof Closure) {
$labels = ($this->getLabelsUsing)($ids);
} else {
$labels = Arr::only($this->getItems(), $ids);
}
$result = [];
foreach ($labels as $id => $label) {
$result[(string) $id] = (string) $label;
}
return $result;
}
public function hasSearchResultsUsing(): bool
{
return $this->getSearchResultsUsing instanceof Closure;
}
public function hasItems(): bool
{
return filled($this->items);
}
/**
* @return array<string, string>
*/
public function getItems(): array
{
$items = $this->items;
if ($items instanceof Closure) {
$items = $items();
}
$normalized = [];
foreach ($items as $id => $label) {
$normalized[(string) $id] = (string) $label;
}
return $normalized;
}
/**
* @return array<string, string>
*/
public function getSearchResults(string $search): array
{
if ($this->getSearchResultsUsing instanceof Closure) {
$results = ($this->getSearchResultsUsing)($search) ?? [];
} else {
$items = $this->getItems();
if (blank($search)) {
$results = $items;
} else {
$searchLower = strtolower($search);
$results = array_filter(
$items,
static fn (string $label): bool => str_contains(strtolower($label), $searchLower),
);
}
}
$normalized = [];
foreach ($results as $id => $label) {
$normalized[(string) $id] = (string) $label;
}
return $normalized;
}
}

View file

@ -0,0 +1,50 @@
<?php
namespace Filament\Forms\Components\RichEditor\Models\Concerns;
use Filament\Forms\Components\RichEditor\RichContentAttribute;
trait InteractsWithRichContent /** @phpstan-ignore trait.unused */
{
/**
* @var array<string, RichContentAttribute>
*/
protected array $richContentAttributes;
/**
* @return array<string, RichContentAttribute>
*/
public function getRichContentAttributes(): array
{
if (! isset($this->richContentAttributes)) {
$this->setUpRichContent();
$this->richContentAttributes ??= [];
}
return $this->richContentAttributes;
}
protected function setUpRichContent(): void {}
public function registerRichContent(string $name): RichContentAttribute
{
return $this->richContentAttributes[$name] = RichContentAttribute::make($this, $name);
}
public function renderRichContent(string $attribute): string
{
$attribute = $this->getRichContentAttribute($attribute) ?? RichContentAttribute::make($this, $attribute);
return $attribute->toHtml();
}
public function getRichContentAttribute(string $attribute): ?RichContentAttribute
{
return $this->getRichContentAttributes()[$attribute] ?? null;
}
public function hasRichContentAttribute(string $attribute): bool
{
return array_key_exists($attribute, $this->getRichContentAttributes());
}
}

View file

@ -0,0 +1,14 @@
<?php
namespace Filament\Forms\Components\RichEditor\Models\Contracts;
use Filament\Forms\Components\RichEditor\RichContentAttribute;
interface HasRichContent
{
public function getRichContentAttribute(string $attribute): ?RichContentAttribute;
public function renderRichContent(string $attribute): string;
public function hasRichContentAttribute(string $attribute): bool;
}

View file

@ -0,0 +1,10 @@
<?php
namespace Filament\Forms\Components\RichEditor\Plugins\Contracts;
use Filament\Forms\Components\RichEditor\FileAttachmentProviders\Contracts\FileAttachmentProvider;
interface HasFileAttachmentProvider
{
public function getFileAttachmentProvider(): ?FileAttachmentProvider;
}

View file

@ -0,0 +1,16 @@
<?php
namespace Filament\Forms\Components\RichEditor\Plugins\Contracts;
interface HasToolbarButtons
{
/**
* @return array<string | array<string | array<string>>>
*/
public function getEnabledToolbarButtons(): array;
/**
* @return array<string>
*/
public function getDisabledToolbarButtons(): array;
}

View file

@ -0,0 +1,30 @@
<?php
namespace Filament\Forms\Components\RichEditor\Plugins\Contracts;
use Filament\Actions\Action;
use Filament\Forms\Components\RichEditor\RichEditorTool;
use Tiptap\Core\Extension;
interface RichContentPlugin
{
/**
* @return array<Extension>
*/
public function getTipTapPhpExtensions(): array;
/**
* @return array<string>
*/
public function getTipTapJsExtensions(): array;
/**
* @return array<RichEditorTool>
*/
public function getEditorTools(): array;
/**
* @return array<Action>
*/
public function getEditorActions(): array;
}

View file

@ -0,0 +1,323 @@
<?php
namespace Filament\Forms\Components\RichEditor;
use Closure;
use Filament\Forms\Components\RichEditor\FileAttachmentProviders\Contracts\FileAttachmentProvider;
use Filament\Forms\Components\RichEditor\Plugins\Contracts\HasFileAttachmentProvider;
use Filament\Forms\Components\RichEditor\Plugins\Contracts\RichContentPlugin;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;
class RichContentAttribute implements Htmlable
{
protected ?string $fileAttachmentsDiskName = null;
protected ?string $fileAttachmentsVisibility = null;
/**
* @var array<RichContentPlugin>
*/
protected array $plugins = [];
protected ?FileAttachmentProvider $fileAttachmentProvider = null;
/**
* @var ?array<string, mixed>
*/
protected ?array $mergeTags = null;
/**
* @var ?array<string, string>
*/
protected ?array $mergeTagLabels = null;
/**
* @var ?array<MentionProvider>
*/
protected ?array $mentionProviders = null;
/**
* @var ?array<class-string<RichContentCustomBlock> | array<int | string, mixed> | Closure>
*/
protected ?array $customBlocks = null;
protected bool $isJson = false;
/**
* @var ?array<string, string | TextColor>
*/
protected ?array $textColors = null;
protected bool $hasCustomTextColors = false;
public function __construct(protected Model $model, protected string $name) {}
public static function make(Model $model, string $name): static
{
return app(static::class, ['model' => $model, 'name' => $name]);
}
public function fileAttachmentsDisk(?string $name): static
{
$this->fileAttachmentsDiskName = $name;
return $this;
}
public function fileAttachmentsVisibility(?string $visibility): static
{
$this->fileAttachmentsVisibility = $visibility;
return $this;
}
public function getFileAttachmentsDiskName(): ?string
{
return $this->fileAttachmentsDiskName;
}
public function getFileAttachmentsVisibility(): ?string
{
return $this->fileAttachmentsVisibility ?? $this->getFileAttachmentProvider()?->getDefaultFileAttachmentVisibility();
}
/**
* @param array<RichContentPlugin> $plugins
*/
public function plugins(array $plugins): static
{
$this->plugins = [
...$this->plugins,
...$plugins,
];
return $this;
}
/**
* @return array<RichContentPlugin>
*/
public function getPlugins(): array
{
return $this->plugins;
}
public function fileAttachmentProvider(?FileAttachmentProvider $provider): static
{
$this->fileAttachmentProvider = $provider?->attribute($this);
return $this;
}
public function getFileAttachmentProvider(): ?FileAttachmentProvider
{
if ($this->fileAttachmentProvider) {
return $this->fileAttachmentProvider;
}
foreach ($this->getPlugins() as $plugin) {
if ($plugin instanceof HasFileAttachmentProvider) {
$provider = $plugin->getFileAttachmentProvider();
if ($provider) {
return $this->fileAttachmentProvider = $provider->attribute($this);
}
}
}
return null;
}
public function getModel(): Model
{
return $this->model;
}
public function getName(): string
{
return $this->name;
}
public function toHtml(): string
{
$content = $this->model->getAttribute($this->name);
if (blank($content)) {
return '';
}
return $this->getRenderer()->toHtml();
}
public function toText(): string
{
$content = $this->model->getAttribute($this->name);
if (blank($content)) {
return '';
}
return $this->getRenderer()->toText();
}
public function getRenderer(): RichContentRenderer
{
return RichContentRenderer::make($this->model->getAttribute($this->name) ?? '')
->plugins($this->getPlugins())
->customBlocks($this->customBlocks)
->mergeTags($this->mergeTags)
->mentions($this->mentionProviders)
->fileAttachmentsDisk($this->getFileAttachmentsDiskName())
->fileAttachmentsVisibility($this->getFileAttachmentsVisibility())
->fileAttachmentProvider($this->getFileAttachmentProvider())
->textColors($this->getTextColors());
}
/**
* @param ?array<string, mixed> $tags
*/
public function mergeTags(?array $tags): static
{
$this->mergeTags = $tags;
return $this;
}
/**
* @param ?array<string, string> $labels
*/
public function mergeTagLabels(?array $labels): static
{
$this->mergeTagLabels = $labels;
return $this;
}
/**
* @return ?array<string, string>
*/
public function getMergeTags(): ?array
{
if (blank($this->mergeTags) && blank($this->mergeTagLabels)) {
return null;
}
return [
...array_combine(array_keys($this->mergeTags ?? []), array_keys($this->mergeTags ?? [])),
...($this->mergeTagLabels ?? []),
];
}
/**
* @param ?array<MentionProvider> $providers
*/
public function mentions(?array $providers): static
{
$this->mentionProviders = $providers;
return $this;
}
/**
* @return ?array<MentionProvider>
*/
public function getMentionProviders(): ?array
{
return $this->mentionProviders;
}
/**
* @param ?array<class-string<RichContentCustomBlock> | array<class-string<RichContentCustomBlock>> | array<string, mixed> | Closure> $blocks
*/
public function customBlocks(?array $blocks): static
{
$this->customBlocks = $blocks;
return $this;
}
/**
* @return ?array<class-string<RichContentCustomBlock>>
*/
public function getCustomBlocks(): ?array
{
if (blank($this->customBlocks)) {
return null;
}
$blocks = [];
foreach ($this->customBlocks as $key => $block) {
if (is_string($key) && is_a($key, RichContentCustomBlock::class, allow_string: true)) {
// Data association: `BlockClass::class => $data`
$blocks[] = $key;
} elseif (is_array($block)) {
// Group or ungrouped section: `'Label' => [...]` or `[...]`
foreach ($block as $innerKey => $innerValue) {
$blocks[] = is_string($innerKey) ? $innerKey : $innerValue;
}
} else {
$blocks[] = $block;
}
}
return $blocks;
}
/**
* @return array<class-string<RichContentCustomBlock> | array<class-string<RichContentCustomBlock>>>
*/
public function getCustomBlocksConfig(): array
{
return $this->customBlocks ?? [];
}
public function json(bool $condition = true): static
{
$this->isJson = $condition;
return $this;
}
public function isJson(): bool
{
return $this->isJson;
}
/**
* @param ?array<string, string | TextColor> $colors
*/
public function textColors(?array $colors): static
{
$this->textColors = $colors;
return $this;
}
/**
* @return array<string, string | TextColor>
*/
public function getTextColors(): array
{
$textColors = $this->textColors ?? TextColor::getDefaults();
return Arr::mapWithKeys(
$textColors,
fn (string | TextColor $color, string $name): array => [$name => ($color instanceof TextColor) ? $color : TextColor::make($color, $name)],
);
}
public function customTextColors(bool $condition = true): static
{
$this->hasCustomTextColors = $condition;
return $this;
}
public function hasCustomTextColors(): bool
{
return $this->hasCustomTextColors;
}
}

View file

@ -0,0 +1,56 @@
<?php
namespace Filament\Forms\Components\RichEditor;
use Filament\Actions\Action;
abstract class RichContentCustomBlock
{
abstract public static function getId(): string;
public static function getLabel(): string
{
return (string) str(static::getId())
->kebab()
->replace('-', ' ')
->ucwords();
}
/**
* @param array<string, mixed> $config
* @param array<string, mixed> $data
*/
public static function toHtml(array $config, array $data): ?string
{
return null;
}
/**
* @param array<string, mixed> $config
*/
public static function getPreviewLabel(array $config): string
{
return static::getLabel();
}
/**
* @param array<string, mixed> $config
*/
public static function toPreviewHtml(array $config): ?string
{
return null;
}
/**
* @param array<string, mixed> $config
*/
public static function shouldApplyProseStylingToPreview(array $config): bool
{
return false;
}
public static function configureEditorAction(Action $action): Action
{
return $action->modalHidden();
}
}

View file

@ -0,0 +1,749 @@
<?php
namespace Filament\Forms\Components\RichEditor;
use Closure;
use Filament\Forms\Components\RichEditor\FileAttachmentProviders\Contracts\FileAttachmentProvider;
use Filament\Forms\Components\RichEditor\Plugins\Contracts\HasFileAttachmentProvider;
use Filament\Forms\Components\RichEditor\Plugins\Contracts\RichContentPlugin;
use Filament\Forms\Components\RichEditor\TipTapExtensions\CustomBlockExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\DetailsContentExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\DetailsExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\DetailsSummaryExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\GridColumnExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\GridExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\ImageExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\LeadExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\MentionExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\MergeTagExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\RawHtmlMergeTagExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\RenderedCustomBlockExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\SmallExtension;
use Filament\Forms\Components\RichEditor\TipTapExtensions\TextColorExtension;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Support\Traits\Macroable;
use League\Flysystem\UnableToCheckFileExistence;
use Throwable;
use Tiptap\Core\Extension;
use Tiptap\Editor;
use Tiptap\Extensions\TextAlign;
use Tiptap\Marks\Bold;
use Tiptap\Marks\Code;
use Tiptap\Marks\Highlight;
use Tiptap\Marks\Italic;
use Tiptap\Marks\Link;
use Tiptap\Marks\Strike;
use Tiptap\Marks\Subscript;
use Tiptap\Marks\Superscript;
use Tiptap\Marks\Underline;
use Tiptap\Nodes\Blockquote;
use Tiptap\Nodes\BulletList;
use Tiptap\Nodes\CodeBlock;
use Tiptap\Nodes\Document;
use Tiptap\Nodes\HardBreak;
use Tiptap\Nodes\Heading;
use Tiptap\Nodes\HorizontalRule;
use Tiptap\Nodes\ListItem;
use Tiptap\Nodes\OrderedList;
use Tiptap\Nodes\Paragraph;
use Tiptap\Nodes\Table;
use Tiptap\Nodes\TableCell;
use Tiptap\Nodes\TableHeader;
use Tiptap\Nodes\TableRow;
use Tiptap\Nodes\Text;
class RichContentRenderer implements Htmlable
{
use Macroable;
/**
* @var string | array<string, mixed>
*/
protected string | array | null $content = null;
protected ?string $fileAttachmentsDiskName = null;
protected ?string $fileAttachmentsVisibility = null;
/**
* @var array<RichContentPlugin>
*/
protected array $plugins = [];
protected ?FileAttachmentProvider $fileAttachmentProvider = null;
/**
* @var ?array<string, mixed>
*/
protected ?array $mergeTags = null;
/**
* @var ?array<class-string<RichContentCustomBlock> | array<string, mixed> | Closure>
*/
protected ?array $customBlocks = null;
/**
* @var ?array<MentionProvider>
*/
protected ?array $mentionProviders = null;
/**
* @var array<string, mixed>
*/
protected array $cachedMergeTagValues = [];
/**
* @var array<Closure>
*/
protected array $nodeProcessors = [];
/**
* @var ?array<string, string | TextColor>
*/
protected ?array $textColors = null;
/**
* @var ?array<string>
*/
protected ?array $linkProtocols = null;
/**
* @param string | array<string, mixed> | null $content
*/
public function __construct(string | array | null $content = null)
{
$this->content($content);
}
/**
* @param string | array<string, mixed> | null $content
*/
public static function make(string | array | null $content = null): static
{
return app(static::class, [
'content' => $content,
]);
}
/**
* @param string | array<string, mixed> | null $content
*/
public function content(string | array | null $content): static
{
$this->content = $content;
$this->cachedMergeTagValues = [];
return $this;
}
public function fileAttachmentsDisk(?string $name): static
{
$this->fileAttachmentsDiskName = $name;
return $this;
}
public function fileAttachmentsVisibility(?string $visibility): static
{
$this->fileAttachmentsVisibility = $visibility;
return $this;
}
public function getFileAttachmentUrl(mixed $file): ?string
{
// The `$file` value comes from a `data-id` attribute on an image node in
// client-submitted rich editor content, and is not authorized here before
// being passed to the filesystem. Applications whose disk stores files
// belonging to multiple users or records must supply a custom file
// attachment provider (or use the Spatie Media Library provider) that
// validates the id against records the current user is allowed to read.
// See the "Securing file attachment IDs" section of the rich editor
// documentation.
$fileAttachmentProvider = $this->getFileAttachmentProvider();
if ($fileAttachmentProvider) {
return $fileAttachmentProvider->getFileAttachmentUrl($file);
}
$disk = $this->fileAttachmentsDiskName ?? config('filament.default_filesystem_disk');
$visibility = $this->fileAttachmentsVisibility ?? ($disk === 'public' ? 'public' : 'private');
$storage = Storage::disk($disk);
try {
if (! $storage->exists($file)) {
return null;
}
} catch (UnableToCheckFileExistence $exception) {
return null;
}
if ($visibility === 'private') {
try {
return $storage->temporaryUrl(
$file,
now()->addMinutes(config('filament.temporary_file_url_expiry_minutes', 30))->endOfHour(),
);
} catch (Throwable $exception) {
// This driver does not support creating temporary URLs.
}
}
return $storage->url($file);
}
/**
* @param array<RichContentPlugin> $plugins
*/
public function plugins(array $plugins): static
{
$this->plugins = [
...$this->plugins,
...$plugins,
];
return $this;
}
protected function processCustomBlocks(Editor $editor): void
{
if (blank($this->customBlocks)) {
return;
}
$editor->descendants(function (object &$node): void {
if ($node->type !== 'customBlock') {
return;
}
if (blank($node->attrs->id ?? null)) {
return;
}
$nodeConfig = json_decode(json_encode($node->attrs->config ?? []), associative: true);
$node->type = 'renderedCustomBlock';
$node->html = $this->getCustomBlockHtml($node->attrs->id, $nodeConfig);
unset($node->attrs->config);
});
}
protected function processFileAttachments(Editor $editor): void
{
$editor->descendants(function (object &$node): void {
if ($node->type !== 'image') {
return;
}
if (blank($node->attrs->id ?? null)) {
return;
}
$node->attrs->src = $this->getFileAttachmentUrl($node->attrs->id);
});
}
protected function processMergeTags(Editor $editor): void
{
$editor->descendants(function (object &$node): void {
if ($node->type !== 'rawHtmlMergeTag') {
return;
}
$node->type = 'mergeTag';
unset($node->html);
});
if (blank($this->mergeTags)) {
return;
}
$editor->descendants(function (object &$node): void {
if ($node->type !== 'mergeTag') {
return;
}
if (blank($node->attrs->id ?? null)) {
return;
}
$value = $this->getMergeTagValue($node->attrs->id);
if ($value instanceof Htmlable) {
$node->type = 'rawHtmlMergeTag';
$node->html = $value->toHtml();
return;
}
$node->content = [
(object) [
'type' => 'text',
'text' => $value,
],
];
});
}
protected function flattenMergeTagsForText(Editor $editor): void
{
$editor->descendants(function (object &$node): void {
if (! isset($node->content) || ! is_array($node->content)) {
return;
}
$hasMergeTags = false;
foreach ($node->content as $child) {
if (in_array($child->type, ['mergeTag', 'rawHtmlMergeTag'])) {
$hasMergeTags = true;
break;
}
}
if (! $hasMergeTags) {
return;
}
$merged = [];
foreach ($node->content as $child) {
foreach ($this->resolveTextNodesFromMergeTag($child) as $textNode) {
$last = end($merged);
if ($last && $last->type === 'text' && $textNode->type === 'text') {
$last->text .= $textNode->text;
} else {
$merged[] = $textNode;
}
}
}
$node->content = $merged;
});
}
/**
* @return array<object>
*/
protected function resolveTextNodesFromMergeTag(object $node): array
{
if ($node->type === 'mergeTag') {
return $node->content ?? [];
}
if ($node->type === 'rawHtmlMergeTag') {
$text = trim(preg_replace('/\s+/', ' ', strip_tags($node->html ?? '')));
if ($text === '') {
return [];
}
return [
(object) [
'type' => 'text',
'text' => $text,
],
];
}
return [$node];
}
protected function processMentions(Editor $editor): void
{
if (blank($this->mentionProviders)) {
return;
}
$mentionsByChar = [];
$editor->descendants(function (object &$node) use (&$mentionsByChar): void {
if ($node->type !== 'mention') {
return;
}
$id = $node->attrs->id ?? null;
if (blank($id)) {
return;
}
$char = $node->attrs->char ?? '@';
$mentionsByChar[$char][] = (string) $id;
});
$labelsByChar = [];
foreach ($mentionsByChar as $char => $ids) {
$provider = $this->getMentionProvider($char);
if ($provider) {
$labelsByChar[$char] = $provider->getLabels(array_unique($ids));
}
}
$editor->descendants(function (object &$node) use ($labelsByChar): void {
if ($node->type !== 'mention') {
return;
}
$id = $node->attrs->id ?? null;
$char = $node->attrs->char ?? '@';
if (blank($id)) {
return;
}
$provider = $this->getMentionProvider($char);
if (! $provider) {
return;
}
$label = $labelsByChar[$char][(string) $id] ?? $node->attrs->label ?? (string) $id;
$node->attrs->label = $label;
$url = $provider->getUrl((string) $id, $label);
if ($url) {
$node->attrs->href = $url;
}
});
}
public function processNodesUsing(Closure $callback): static
{
$this->nodeProcessors[] = $callback;
return $this;
}
protected function processNodes(Editor $editor): void
{
foreach ($this->nodeProcessors as $processor) {
$editor->descendants($processor);
}
}
/**
* @return array<RichContentPlugin>
*/
public function getPlugins(): array
{
return $this->plugins;
}
/**
* @return array<Extension>
*/
public function getTipTapPhpExtensions(): array
{
return [
...array_reduce(
$this->getPlugins(),
fn (array $carry, RichContentPlugin $plugin): array => [
...$carry,
...$plugin->getTipTapPhpExtensions(),
],
initial: [],
),
app(Blockquote::class),
app(Bold::class),
app(BulletList::class),
app(Code::class),
app(CodeBlock::class),
app(CustomBlockExtension::class),
app(DetailsContentExtension::class),
app(DetailsExtension::class),
app(DetailsSummaryExtension::class),
app(Document::class),
app(GridColumnExtension::class),
app(GridExtension::class),
app(HardBreak::class),
app(Heading::class),
app(Highlight::class),
app(HorizontalRule::class),
app(Italic::class),
app(ImageExtension::class),
app(LeadExtension::class),
app(Link::class, [
'options' => [
'HTMLAttributes' => [],
'allowedProtocols' => $this->getLinkProtocols(),
],
]),
app(ListItem::class),
app(MentionExtension::class),
app(MergeTagExtension::class),
app(OrderedList::class),
app(Paragraph::class),
app(RawHtmlMergeTagExtension::class),
app(RenderedCustomBlockExtension::class),
app(SmallExtension::class),
app(TextColorExtension::class, [
'options' => [
'textColors' => $this->getTextColors(),
],
]),
app(Strike::class),
app(Subscript::class),
app(Superscript::class),
app(Table::class),
app(TableCell::class),
app(TableHeader::class),
app(TableRow::class),
app(Text::class),
app(TextAlign::class, [
'options' => [
'types' => ['heading', 'paragraph'],
'alignments' => ['start', 'center', 'end', 'justify'],
'defaultAlignment' => 'start',
],
]),
app(Underline::class),
];
}
/**
* @return array{extensions: array<Extension>}
*/
public function getTipTapPhpConfiguration(): array
{
return [
'extensions' => $this->getTipTapPhpExtensions(),
];
}
public function fileAttachmentProvider(?FileAttachmentProvider $provider): static
{
$this->fileAttachmentProvider = $provider;
return $this;
}
public function getFileAttachmentProvider(): ?FileAttachmentProvider
{
if ($this->fileAttachmentProvider) {
return $this->fileAttachmentProvider;
}
foreach ($this->plugins as $plugin) {
if ($plugin instanceof HasFileAttachmentProvider) {
$provider = $plugin->getFileAttachmentProvider();
if ($provider) {
return $this->fileAttachmentProvider = $provider;
}
}
}
return null;
}
public function getEditor(): Editor
{
$editor = app(Editor::class, ['configuration' => $this->getTipTapPhpConfiguration()]);
if (filled($this->content)) {
$editor->setContent($this->content);
}
return $editor;
}
public function toUnsafeHtml(): string
{
// Security: This method returns unsanitized HTML. Only use for
// internal processing — never render in Blade. Use `toHtml()`.
$editor = $this->getEditor();
$this->processCustomBlocks($editor);
$this->processFileAttachments($editor);
$this->processMergeTags($editor);
$this->processMentions($editor);
$this->processNodes($editor);
return $editor->getHTML();
}
public function toHtml(): string
{
// Security: Always use `toHtml()` (not `toUnsafeHtml()`) when
// rendering user-provided rich content. This applies
// Symfony's `HtmlSanitizer` to prevent XSS.
return Str::sanitizeHtml($this->toUnsafeHtml());
}
public function toText(): string
{
$editor = $this->getEditor();
$this->processMergeTags($editor);
$this->flattenMergeTagsForText($editor);
return $editor->getText();
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
if (empty($this->content)) {
return [];
}
$editor = $this->getEditor();
$this->processMergeTags($editor);
return json_decode($editor->getJSON(), true);
}
/**
* @param ?array<string, mixed> $tags
*/
public function mergeTags(?array $tags): static
{
$this->mergeTags = $tags;
$this->cachedMergeTagValues = [];
return $this;
}
public function getMergeTagValue(string $mergeTag): mixed
{
return $this->cachedMergeTagValues[$mergeTag] ??= value($this->mergeTags[$mergeTag] ?? null);
}
/**
* @param ?array<class-string<RichContentCustomBlock> | array<class-string<RichContentCustomBlock> | array<string, mixed> | Closure> | array<string, mixed> | Closure> $blocks
*/
public function customBlocks(?array $blocks): static
{
if ($blocks !== null) {
$flattened = [];
foreach ($blocks as $key => $value) {
if (is_string($key) && is_a($key, RichContentCustomBlock::class, allow_string: true)) {
// Data association: `BlockClass::class => $data`
$flattened[$key] = $value;
} elseif (is_array($value)) {
// Group or ungrouped section: `'Label' => [...]` or `[...]`
foreach ($value as $innerKey => $innerValue) {
if (is_string($innerKey)) {
$flattened[$innerKey] = $innerValue;
} else {
$flattened[] = $innerValue;
}
}
} else {
$flattened[] = $value;
}
}
$blocks = $flattened;
}
$this->customBlocks = $blocks;
return $this;
}
/**
* @param array<string, mixed> $config
*/
public function getCustomBlockHtml(string $id, array $config): ?string
{
foreach ($this->customBlocks as $key => $block) {
if (is_string($key) && ($key::getId() === $id)) {
return $key::toHtml($config, data: value($block) ?? []);
} elseif (is_string($block) && ($block::getId() === $id)) {
return $block::toHtml($config, data: []);
}
}
return null;
}
/**
* @param ?array<MentionProvider> $providers
*/
public function mentions(?array $providers): static
{
$this->mentionProviders = $providers;
return $this;
}
/**
* @return ?array<MentionProvider>
*/
public function getMentionProviders(): ?array
{
return $this->mentionProviders;
}
public function getMentionProvider(string $char): ?MentionProvider
{
if (blank($this->mentionProviders)) {
return null;
}
foreach ($this->mentionProviders as $provider) {
if ($provider->getChar() === $char) {
return $provider;
}
}
return $this->mentionProviders[0] ?? null;
}
/**
* @param ?array<string, string | TextColor> $colors
*/
public function textColors(?array $colors): static
{
$this->textColors = $colors;
return $this;
}
/**
* @return array<string, string | TextColor>
*/
public function getTextColors(): array
{
$textColors = $this->textColors ?? TextColor::getDefaults();
return Arr::mapWithKeys(
$textColors,
fn (string | TextColor $color, string $name): array => [$name => ($color instanceof TextColor) ? $color : TextColor::make($color, $name)],
);
}
/**
* @param ?array<string> $protocols
*/
public function linkProtocols(?array $protocols): static
{
$this->linkProtocols = $protocols;
return $this;
}
/**
* @return array<string>
*/
public function getLinkProtocols(): array
{
return $this->linkProtocols ?? app(Link::class)->options['allowedProtocols'];
}
}

View file

@ -0,0 +1,247 @@
<?php
namespace Filament\Forms\Components\RichEditor;
use Closure;
use Filament\Forms\Components\RichEditor;
use Filament\Schemas\Components\Concerns\HasLabel;
use Filament\Schemas\Components\Concerns\HasName;
use Filament\Support\Components\Contracts\HasEmbeddedView;
use Filament\Support\Components\ViewComponent;
use Filament\Support\Concerns\HasExtraAttributes;
use Filament\Support\Concerns\HasIcon;
use Illuminate\Contracts\Support\Htmlable;
use Illuminate\Support\Js;
use function Filament\Support\generate_icon_html;
class RichEditorTool extends ViewComponent implements HasEmbeddedView
{
use HasExtraAttributes;
use HasIcon;
use HasLabel {
getLabel as getBaseLabel;
}
use HasName;
/**
* @var array<string, mixed> | Closure
*/
protected array | Closure $activeOptions = [];
protected string | Closure | null $iconAlias = null;
protected string | Closure | null $activeKey = null;
protected string | Closure | null $jsHandler = null;
protected string | Closure | null $activeJsExpression = null;
protected bool | Closure $isDisabledWhenNotActive = false;
protected bool | Closure $hasActiveStyling = true;
protected bool | Closure $isToggle = false;
protected RichEditor $editor;
protected string $evaluationIdentifier = 'tool';
protected string $viewIdentifier = 'tool';
final public function __construct(string $name)
{
$this
->name($name)
->hiddenLabel();
}
public static function make(string $name): static
{
$static = app(static::class, ['name' => $name]);
$static->configure();
return $static;
}
public function editor(RichEditor $editor): static
{
$this->editor = $editor;
return $this;
}
public function getEditor(): RichEditor
{
return $this->editor;
}
/**
* @param array<string, mixed> | Closure $options
*/
public function activeOptions(array | Closure $options): static
{
$this->activeOptions = $options;
return $this;
}
/**
* @return array<string, mixed>
*/
public function getActiveOptions(): array
{
return $this->evaluate($this->activeOptions);
}
public function iconAlias(string | Closure | null $alias): static
{
$this->iconAlias = $alias;
return $this;
}
public function getIconAlias(): ?string
{
return $this->evaluate($this->iconAlias);
}
public function action(string | Closure | null $action = null, string | Closure | null $arguments = null): static
{
$this->jsHandler(fn (RichEditorTool $tool): string => '$wire.mountAction(\'' . ($tool->evaluate($action) ?? $tool->getName()) . '\', { editorSelection, ...' . ($tool->evaluate($arguments) ?? '{}') . ' }, ' . Js::from(['schemaComponent' => $tool->getEditor()->getKey()]) . ')');
return $this;
}
public function jsHandler(string | Closure | null $handler): static
{
$this->jsHandler = $handler;
return $this;
}
public function activeJsExpression(string | Closure | null $expression): static
{
$this->activeJsExpression = $expression;
return $this;
}
public function getJsHandler(): ?string
{
return $this->evaluate($this->jsHandler);
}
public function getActiveJsExpression(): ?string
{
return $this->evaluate($this->activeJsExpression);
}
public function activeKey(string | Closure | null $key): static
{
$this->activeKey = $key;
return $this;
}
public function getActiveKey(): string
{
return $this->evaluate($this->activeKey) ?? $this->getName();
}
public function getLabel(): string | Htmlable | null
{
if (filled($label = $this->getBaseLabel())) {
return $label;
}
$label = (string) str($this->getName())
->afterLast('.')
->kebab()
->replace(['-', '_'], ' ')
->ucfirst();
return $this->shouldTranslateLabel ? __($label) : $label;
}
public function disabledWhenNotActive(bool | Closure $condition = true): static
{
$this->isDisabledWhenNotActive = $condition;
return $this;
}
public function isDisabledWhenNotActive(): bool
{
return (bool) $this->evaluate($this->isDisabledWhenNotActive);
}
public function activeStyling(bool | Closure $condition = true): static
{
$this->hasActiveStyling = $condition;
return $this;
}
public function hasActiveStyling(): bool
{
return (bool) $this->evaluate($this->hasActiveStyling);
}
public function toggle(bool | Closure $condition = true): static
{
$this->isToggle = $condition;
return $this;
}
public function isToggle(): bool
{
return (bool) $this->evaluate($this->isToggle);
}
public function toEmbeddedHtml(): string
{
$activeJsExpression = $this->getActiveJsExpression();
if (filled($activeJsExpression)) {
$activeJsExpression = "editorUpdatedAt && ({$activeJsExpression})";
} else {
$activeJsExpression = 'editorUpdatedAt && $getEditor()?.isActive(' . Js::from($this->getActiveKey())->toHtml() . ', ' . Js::from($this->getActiveOptions())->toHtml() . ')';
}
$label = $this->getLabel();
$isLabelHidden = $this->isLabelHidden();
$attributes = $this->getExtraAttributeBag()
->merge([
'tabindex' => -1,
'type' => 'button',
'aria-label' => e($label),
'aria-pressed' => $this->isToggle() ? 'false' : null,
'x-bind:class' => '{ \'fi-active\': ' . ($this->hasActiveStyling() ? $activeJsExpression : 'false') . ' }',
// Guard against the pre-init `undefined` (the TipTap editor loads asynchronously): Alpine
// preserves a falsy `aria-pressed` rather than removing it, so coerce to a valid token.
'x-bind:aria-pressed' => $this->isToggle() ? '(' . $activeJsExpression . ') ? \'true\' : \'false\'' : null,
'x-bind:disabled' => $this->isDisabledWhenNotActive() ? '!(' . $activeJsExpression . ')' : null,
'x-on:click' => $this->getJsHandler(),
'x-tooltip' => (filled($label) && $isLabelHidden)
? '{ content: ' . Js::from($label) . ', theme: $store.theme }'
: null,
], escape: false)
->class([
'fi-fo-rich-editor-tool',
'fi-fo-rich-editor-tool-with-label' => ! $isLabelHidden,
]);
ob_start(); ?>
<button <?= $attributes->toHtml() ?>>
<?= generate_icon_html($this->getIcon(), alias: $this->getIconAlias())?->toHtml() ?? '' ?>
<?= $isLabelHidden ? null : '<span class="fi-fo-rich-editor-tool-label">' . e($label) . '</span>' ?>
</button>
<?php return ob_get_clean();
}
}

View file

@ -0,0 +1,209 @@
<?php
namespace Filament\Forms\Components\RichEditor\StateCasts;
use Filament\Forms\Components\RichEditor;
use Filament\Schemas\Components\StateCasts\Contracts\StateCast;
use Illuminate\Contracts\Support\Htmlable;
use Tiptap\Editor;
class RichEditorStateCast implements StateCast
{
public function __construct(
protected RichEditor $richEditor,
) {}
/**
* @return string | array<string, mixed>
*/
public function get(mixed $state): string | array
{
$editor = $this->richEditor->getTipTapEditor()
->setContent($state ?? [
'type' => 'doc',
'content' => [],
]);
if ($this->richEditor->getFileAttachmentsVisibility() === 'private') {
$editor->descendants(function (object &$node): void {
if ($node->type !== 'image') {
return;
}
if (blank($node->attrs->id ?? null)) {
return;
}
if (blank($node->attrs->src ?? null)) {
return;
}
$node->attrs->src = null;
});
}
if ($this->richEditor->getCustomBlocks()) {
$editor->descendants(function (object &$node): void {
if ($node->type !== 'customBlock') {
return;
}
unset($node->attrs->label);
unset($node->attrs->preview);
unset($node->attrs->shouldApplyProseStylingToPreview);
});
}
return $editor->{$this->richEditor->isJson() ? 'getDocument' : 'getHtml'}();
}
/**
* @return array<string, mixed>
*/
public function set(mixed $state): array
{
if ($state instanceof Htmlable) {
$state = $state->toHtml();
}
$shouldPreventTampering = $this->richEditor->shouldPreventFileAttachmentPathTampering();
$originalFileAttachmentPaths = $shouldPreventTampering ? $this->richEditor->getOriginalFileAttachmentPaths() : [];
$editor = $this->richEditor->getTipTapEditor()
->setContent($state ?? [
'type' => 'doc',
'content' => [
[
'type' => 'paragraph',
'content' => [],
],
],
])
->descendants(function (object &$node) use ($shouldPreventTampering, $originalFileAttachmentPaths): void {
if ($node->type !== 'image') {
return;
}
if (blank($node->attrs->id ?? null)) {
return;
}
if ($shouldPreventTampering && ! $this->richEditor->isFileAttachmentPathAuthorized($node->attrs->id, $originalFileAttachmentPaths)) {
$node->attrs->src = null;
return;
}
$node->attrs->src = $this->richEditor->getFileAttachmentUrl($node->attrs->id) ?? $this->richEditor->getFileAttachmentUrlFromAnotherRecord($node->attrs->id) ?? $node->attrs->src ?? null;
});
if ($this->richEditor->getCustomBlocks()) {
$editor->descendants(function (object &$node): void {
if ($node->type !== 'customBlock') {
return;
}
$block = $this->richEditor->getCustomBlock($node->attrs->id);
if (blank($block)) {
return;
}
$nodeConfig = json_decode(json_encode($node->attrs->config ?? []), associative: true);
$node->attrs->label = $block::getPreviewLabel($nodeConfig);
$node->attrs->preview = base64_encode($block::toPreviewHtml($nodeConfig));
$node->attrs->shouldApplyProseStylingToPreview = $block::shouldApplyProseStylingToPreview($nodeConfig);
});
}
$this->hydrateMentionLabels($editor);
$this->normalizeListItemContent($editor);
return $editor->getDocument();
}
/**
* https://github.com/filamentphp/filament/issues/19529
*/
protected function normalizeListItemContent(Editor $editor): void
{
$editor->descendants(function (object &$node): void {
if ($node->type !== 'listItem') {
return;
}
if (! isset($node->content) || ! is_array($node->content)) {
return;
}
$firstChild = $node->content[0] ?? null;
if (! $firstChild || $firstChild->type !== 'text') {
return;
}
$node->content = [(object) [
'type' => 'paragraph',
'content' => $node->content,
]];
});
}
protected function hydrateMentionLabels(Editor $editor): void
{
$mentionProviders = $this->richEditor->getMentionProviders();
if (blank($mentionProviders)) {
return;
}
$mentionsByChar = [];
$editor->descendants(function (object &$node) use (&$mentionsByChar): void {
if ($node->type !== 'mention') {
return;
}
$char = $node->attrs->char ?? '@';
$id = $node->attrs->id ?? null;
if (blank($id)) {
return;
}
$mentionsByChar[$char][] = (string) $id;
});
if (blank($mentionsByChar)) {
return;
}
$labelsByChar = [];
foreach ($mentionsByChar as $char => $ids) {
foreach ($mentionProviders as $provider) {
if ($provider->getChar() === $char) {
$labelsByChar[$char] = $provider->getLabels(array_unique($ids));
break;
}
}
}
$editor->descendants(function (object &$node) use ($labelsByChar): void {
if ($node->type !== 'mention') {
return;
}
$char = $node->attrs->char ?? '@';
$id = $node->attrs->id ?? null;
if (blank($id)) {
return;
}
$node->attrs->label = $labelsByChar[$char][(string) $id] ?? '';
});
}
}

Some files were not shown because too many files have changed in this diff Show more