Last active
September 8, 2020 07:55
-
-
Save sasin91/edfdbb07cf0046fdcc38265992c7f610 to your computer and use it in GitHub Desktop.
Infer wired property from slot
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<code> | |
<?php | |
namespace App\View\Components; | |
use Illuminate\Support\Str; | |
use Illuminate\View\Component; | |
class FormField extends Component | |
{ | |
/** | |
* Get the view / contents that represent the component. | |
* | |
* @return \Illuminate\View\View|string | |
*/ | |
public function render() | |
{ | |
return view('components.form-field', [ | |
'extractWiredProperty' => static function ($htmlString): ?string { | |
$tokens = array_map( | |
'trim', | |
explode(PHP_EOL, (string)$htmlString) | |
); | |
$matches = preg_grep( | |
"#^wire:model.*\z#u", | |
$tokens | |
); | |
return Str::of(head($matches)) | |
->after('=') | |
->before(' '); | |
} | |
]); | |
} | |
} | |
</code> | |
<view> | |
@php($wiredProperty = $extractWiredProperty($slot)) | |
@if ($wiredProperty) | |
<div class="{{ $attributes['class'] }} @error($wiredProperty) border-red-300 text-red-900 placeholder-red-300 focus:border-red-300 focus:shadow-outline-red @enderror sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:pt-5"> | |
<label for="{{ $attributes['id'] }}" class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2"> | |
{{ $label ?? null }} | |
</label> | |
<div class="mt-1 sm:mt-0 sm:col-span-2"> | |
<div class="max-w-lg border-b border-orange-600"> | |
{{ $slot }} | |
</div> | |
@if (isset($helpText)) | |
<p class="mt-2 text-sm text-gray-500">{{ $helpText }}</p> | |
@endif | |
@error($wiredProperty) | |
<p class="mt-2 text-sm text-red-600">{{ $message }}</p> | |
@enderror | |
</div> | |
</div> | |
@else | |
<div class="{{ $attributes['class'] }} sm:grid sm:grid-cols-3 sm:gap-4 sm:items-start sm:pt-5"> | |
<label for="{{ $attributes['id'] }}" class="block text-sm font-medium leading-5 text-gray-700 sm:mt-px sm:pt-2"> | |
{{ $label ?? null }} | |
</label> | |
<div class="mt-1 sm:mt-0 sm:col-span-2"> | |
<div class="max-w-lg border-b border-orange-600"> | |
{{ $slot }} | |
</div> | |
@if (isset($helpText)) | |
<p class="mt-2 text-sm text-gray-500">{{ $helpText }}</p> | |
@endif | |
</div> | |
</div> | |
@endif | |
</view> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment