Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for lazy props in modals #18

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions src/Modal.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@
class Modal implements Responsable
{
protected string $baseURL;
protected array $props = [];

public function __construct(
protected string $component,
protected array|Arrayable $props = []
array|Arrayable $props
) {
$this->with($props);
}

public function baseRoute(string $name, mixed $parameters = [], bool $absolute = true): static
Expand All @@ -33,17 +35,21 @@ public function basePageRoute(string $name, mixed $parameters = [], bool $absolu
return $this->baseRoute($name, $parameters, $absolute);
}

public function with(array $props): static
public function with(array|Arrayable $props): static
{
$this->props = $props;
$this->props = $props instanceof Arrayable ? $props->toArray() : $props;

return $this;
}

public function render(): mixed
{
$flatProps = [];
foreach ($this->props as $key => $prop) {
$flatProps['modal.props.'.$key] = $prop;
}
/** @phpstan-ignore-next-line */
inertia()->share(['modal' => $this->component()]);
inertia()->share(['modal' => $this->component(), ...$flatProps]);
Comment on lines +47 to +52
Copy link

@pascalbaljet pascalbaljet Apr 5, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Manually looping over the props can be avoided by using the Arr::dot helper method:

inertia()->share(['modal' => $this->component(), ...Arr::dot($this->props, 'modal.props.')]);


// render background component on first visit
if (request()->header('X-Inertia') && request()->header('X-Inertia-Partial-Component')) {
Expand Down Expand Up @@ -100,8 +106,7 @@ protected function component(): array
'component' => $this->component,
'baseURL' => $this->baseURL,
'redirectURL' => $this->redirectURL(),
'props' => $this->props,
'key' => request()->header('X-Inertia-Modal-Key', Str::uuid()->toString()),
'key' => request()->header('X-Inertia-Modal-Key') ?? Str::uuid()->toString(),
'nonce' => Str::uuid()->toString(),
];
}
Expand Down