Skip to content

Make bridge components #32

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

Merged
merged 7 commits into from
Mar 22, 2025
Merged
Show file tree
Hide file tree
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
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ To make a new Stimulus controller, run:
php artisan stimulus:make hello_controller
```

This should create the file for you using a scaffolding to get the controller ready for you. When using Vite, it will also regenerate the `resources/js/controllers/index.js` file to register your newly created Stimulus controller automatically.
This should create the controller for you. When using Vite, it will also regenerate the `resources/js/controllers/index.js` file to register your newly created Stimulus controller automatically.

There's also a hint comment on how you may use the controller in the DOM, something like this:

Expand All @@ -60,6 +60,28 @@ export default class extends Controller {
connect() {
}
}

### Making a new Hotwire Native Bridge Component

You may use the same `stimulus:make` command to generate a Hotwire Native Bridge component by passing the `--bridge=` option with the name of the native component. For instance, if you're working on a native Toast component, you may create it like:

```bash
php artisan stimulus:make bridge/toast_controller --bridge=toast
```

This should create a file for you using the bridge scaffolding. When using Vite, it will also generate the `resources/js/controllers/index.js` file to register your newly created Stimulus Bridge Component automatically.

Like regular Stimulus controllers, there's also a hint comment on how you may use the controller in the DOM:

```js
import { BridgeComponent, BridgeElement } from "@hotwired/hotwire-native-bridge"

// Connects to data-controller="bridge--toast"
export default class extends BridgeComponent {
static component = "toast"

//
}
```

### Regenerate the Manifest
Expand Down
2 changes: 1 addition & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
"illuminate/contracts": "^11.0|^12.0"
},
"require-dev": {
"laravel/pint": "^1.0",
"laravel/pint": "^1.21",
"nunomaduro/collision": "^8.1|^9.0",
"orchestra/testbench": "^9.1|^10.0",
"phpunit/phpunit": "^10.5|^11.0"
Expand Down
22 changes: 22 additions & 0 deletions rector.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
<?php

declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\ValueObject\PhpVersion;

return RectorConfig::configure()
->withPaths([
__DIR__.'/src',
__DIR__.'/tests',
])
->withPreparedSets(
deadCode: true,
codeQuality: true,
typeDeclarations: true,
privatization: true,
earlyReturn: true,
)
->withAttributesSets()
->withPhpSets()
->withPhpVersion(PhpVersion::PHP_82);
6 changes: 3 additions & 3 deletions src/Commands/Concerns/InstallsForImportmap.php
Original file line number Diff line number Diff line change
Expand Up @@ -42,15 +42,15 @@ protected function publishJsFilesForImportmaps()
protected function registerImportmapPins()
{
$dependencies = collect($this->jsPackages())
->map(fn ($version, $package) => "{$package}@{$version}")
->map(fn ($version, $package): string => "{$package}@{$version}")
->values()
->all();

Process::forever()->run(array_merge([
$this->phpBinary(),
'artisan',
'importmap:pin',
], $dependencies), function ($_type, $output) {
], $dependencies), function ($_type, $output): void {
$this->output->write($output);
});

Expand All @@ -61,7 +61,7 @@ protected function registerImportmapPins()
'vendor:publish',
'--tag',
'stimulus-laravel-assets',
], function ($_type, $output) {
], function ($_type, $output): void {
$this->output->write($output);
});

Expand Down
64 changes: 31 additions & 33 deletions src/Commands/Concerns/InstallsForNode.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,33 @@
*/
trait InstallsForNode
{
/**
* @param bool $dev
* @return void
*/
protected static function updateNodePackages(callable $callback, $dev = true)
{
if (! File::exists(base_path('package.json'))) {
return;
}

$configurationKey = $dev ? 'devDependencies' : 'dependencies';

$packages = json_decode(File::get(base_path('package.json')), true);

$packages[$configurationKey] = $callback(
array_key_exists($configurationKey, $packages) ? $packages[$configurationKey] : [],
$configurationKey
);

ksort($packages[$configurationKey]);

File::put(
base_path('package.json'),
json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL
);
}

protected function installsForNode()
{
$this->publishJsFilesForNode();
Expand Down Expand Up @@ -47,38 +74,9 @@ protected function publishJsFilesForNode()

protected function updateNpmPackagesForNode()
{
$this->updateNodePackages(function ($packages) {
return array_merge(
$packages,
$this->jsPackages(),
);
});
}

/**
* @param bool $dev
* @return void
*/
protected static function updateNodePackages(callable $callback, $dev = true)
{
if (! File::exists(base_path('package.json'))) {
return;
}

$configurationKey = $dev ? 'devDependencies' : 'dependencies';

$packages = json_decode(File::get(base_path('package.json')), true);

$packages[$configurationKey] = $callback(
array_key_exists($configurationKey, $packages) ? $packages[$configurationKey] : [],
$configurationKey
);

ksort($packages[$configurationKey]);

File::put(
base_path('package.json'),
json_encode($packages, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT).PHP_EOL
);
$this->updateNodePackages(fn ($packages): array => array_merge(
$packages,
$this->jsPackages(),
));
}
}
16 changes: 8 additions & 8 deletions src/Commands/InstallCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ public function handle(): int
protected function jsPackages(): array
{
return array_merge(
['@hotwired/stimulus' => '^3.1.0'],
$this->hasOption('strada') ? ['@hotwired/strada' => '^1.0.0-beta1'] : [],
['@hotwired/stimulus' => '^3.2'],
$this->hasOption('strada') ? ['@hotwired/hotwire-native-bridge' => '^1.1'] : [],
);
}

Expand All @@ -68,11 +68,16 @@ protected function runCommands($commands)
}
}

$process->run(function ($type, $line) {
$process->run(function ($type, string $line): void {
$this->output->write(' '.$line);
});
}

protected function phpBinary(): string
{
return (new PhpExecutableFinder)->find(false) ?: 'php';
}

private function usingImportmaps(): bool
{
return File::exists($this->importmapsFile());
Expand All @@ -82,9 +87,4 @@ private function importmapsFile(): string
{
return base_path('routes/importmap.php');
}

protected function phpBinary()
{
return (new PhpExecutableFinder)->find(false) ?: 'php';
}
}
14 changes: 6 additions & 8 deletions src/Commands/MakeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,24 +9,22 @@

class MakeCommand extends Command
{
public $signature = 'stimulus:make {name : The Controller name}';
public $signature = 'stimulus:make {name : The Controller name} {--bridge= : The name of the bridge component to be created}';

public $description = 'Makes a new Stimulus Controller.';
public $description = 'Makes a new Stimulus Controller or Bridge Component.';

public function handle(StimulusGenerator $generator): int
{
$this->components->info('Making Stimulus Controller');
$this->components->info($this->option('bridge') ? 'Making a Stimulus Bridge Component' : 'Making Stimulus Controller');

$this->components->task('creating controller', function () use ($generator) {
$generator->create($this->argument('name'));
$this->components->task('creating file', function () use ($generator): true {
$generator->create($this->argument('name'), bridge: $this->option('bridge'));

return true;
});

if (! File::exists(base_path('routes/importmap.php'))) {
$this->components->task('regenerating manifest', function () {
return $this->callSilently(ManifestCommand::class);
});
$this->components->task('regenerating manifest', fn () => $this->callSilently(ManifestCommand::class));

if (file_exists(base_path('pnpm-lock.yaml'))) {
Process::forever()->path(base_path())->run(['pnpm', 'run', 'build']);
Expand Down
4 changes: 2 additions & 2 deletions src/Commands/ManifestCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ class ManifestCommand extends Command

public $description = 'Updates the manifest based on the existing Stimulus controllers.';

public function handle(Manifest $generator)
public function handle(Manifest $generator): int
{
$this->components->info('Regenerating Manifest');

$this->components->task('regenerating manifest', function () use ($generator) {
$this->components->task('regenerating manifest', function () use ($generator): true {
$manifest = $generator->generateFrom(config('stimulus-laravel.controllers_path'))->join(PHP_EOL);
$manifestFile = resource_path('js/controllers/index.js');

Expand Down
48 changes: 0 additions & 48 deletions src/Commands/StradaMakeCommand.php

This file was deleted.

2 changes: 1 addition & 1 deletion src/Features.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

class Features
{
public static function directives()
public static function directives(): string
{
return 'directives';
}
Expand Down
10 changes: 4 additions & 6 deletions src/Manifest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@ class Manifest
public function generateFrom(string $controllersPath): Collection
{
return collect(File::allFiles($controllersPath))
->filter(fn (SplFileInfo $file) => str_contains($file->getFilename(), '_controller'))
->filter(fn (SplFileInfo $file): bool => str_contains($file->getFilename(), '_controller'))
->values()
->map(function (SplFileInfo $file) use ($controllersPath) {
->map(function (SplFileInfo $file) use ($controllersPath): string {
$controllerPath = $this->relativePathFrom($file->getRealPath(), $controllersPath);
$modulePath = Str::of($controllerPath)->before('.')->replace(DIRECTORY_SEPARATOR, '/')->toString();
$controllerClassName = Str::of($modulePath)
Expand All @@ -23,9 +23,7 @@ public function generateFrom(string $controllersPath): Collection
->join('__');
$tagName = Str::of($modulePath)->before('_controller')->replace('_', '-')->replace('/', '--')->toString();

$join = function ($paths) {
return implode('/', $paths);
};
$join = (fn ($paths): string => implode('/', $paths));

return <<<JS

Expand All @@ -35,7 +33,7 @@ public function generateFrom(string $controllersPath): Collection
});
}

private function relativePathFrom(string $controllerPath, string $basePath)
private function relativePathFrom(string $controllerPath, string $basePath): string
{
return trim(str_replace($basePath, '', $controllerPath), DIRECTORY_SEPARATOR);
}
Expand Down
Loading
Loading