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 preload command #5

Merged
merged 4 commits into from
Nov 22, 2024
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
1 change: 1 addition & 0 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
"minimum-stability": "stable",
"require": {
"php": ">=8.1",
"illuminate/console": "^11|^10",
"illuminate/support": "^11|^10",
"guzzlehttp/guzzle": "^7"
},
Expand Down
1,190 changes: 155 additions & 1,035 deletions composer.lock

Large diffs are not rendered by default.

Binary file modified docs/bun.lockb
Binary file not shown.
33 changes: 33 additions & 0 deletions docs/commands/preload.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
---
title: 'Preload command'
sidebarTitle: 'Preload '
description: 'Preload all Unicon commands on deployment'
icon: 'terminal'
---

Unicon provides the `icons:preload` to preload all icons on deployment.

```bash
php artisan icons:preload
```

While Unicon will hapilly fetch icons on-demand, this command will ensure that
even the first render of an icon will be as fast as possible, because they will
be pulled from the cache instead of the Iconify API.

## Caveats

This command performs a recursive regex search on all the Blade files in your
application (excluding `node_modules` and `vendor`). This means that only icons
that are statically defined will be detected.

| Will be found ✅ | Will not be found ❌ |
| ------------- | ----------------- |
| `<x-icon name="noto:unicorn" />` | `<x-icon name="{{ $icon }}" />` |
| `<x-icon name="heroicons:clock" />` | `<x-icon :name="$name" />` |

<Tip>
Icons whose name is dynamically defined will have to be fetched on-demand
the very first time they are rendered, and subsequent renders will be cached
all the same.
</Tip>
4 changes: 4 additions & 0 deletions docs/mint.json
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@
"group": "Components",
"pages": ["components/blade-component", "components/helper-function"]
},
{
"group": "Commands",
"pages": ["commands/preload"]
},
{
"group": "Reference",
"pages": ["config-reference", "credits"]
Expand Down
115 changes: 115 additions & 0 deletions src/Commands/IconsPreloadCommand.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
<?php

declare(strict_types=1);

namespace Hedger\Unicon\Commands;

use Hedger\Unicon\IconRenderer;
use Illuminate\Console\Command;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;

class IconsPreloadCommand extends Command
{
/**
* The name and signature of the console command
*/
protected $signature = 'icons:preload';

/**
* The console command description
*/
protected $description = 'Preloads all Unicon icons';

public function __construct(
protected IconRenderer $renderer,
) {
parent::__construct();
}

/**
* Execute the console command
*/
public function handle(): int
{
$this->info('Looking for icons to preload in your Blade files...');

$this->findAllBladeFiles()
->flatMap(fn(string $file) => $this->findIconsInFile($file))
->unique()
->sort()
->each(fn(string $icon) => $this->preloadIcon($icon));

return self::SUCCESS;
}

/**
* Find all Blade files in the application
*
* This method will look for all Blade files in the application and return
* them as an array of paths.
*
* @return Collection<string>
*/
protected function findAllBladeFiles(): Collection
{
return $this->glob('*.blade.php');
}

/**
* Recursive glob
*
* This method will recursively glob files using the given pattern.
*/
protected function glob(string $pattern, ?string $root = null): Collection
{
$root ??= base_path();

$files = collect(glob($root . '/' . $pattern));

collect(glob($root . '/*', GLOB_ONLYDIR))->each(function ($dir) use (&$files, $pattern) {
if (!in_array(basename($dir), ['node_modules', 'vendor'])) {
$files = $files->merge($this->glob($pattern, $dir));
}
});

return $files;
}

/**
* Find all icons in a Blade file
*
* This method will attempt to find all Unicon icons in a Blade file
* by performing a regex search on the file contents. This implementation
* only works for icons that have been statitcally defined. Variables in
* the name attribute will not be evaluated.
*/
protected function findIconsInFile(string $path): Collection
{
$contents = file_get_contents($path);

$componentName = Str::snake(config('unicon.name', 'icon'));

$hasMatches = preg_match_all(
pattern: '/<x-' . $componentName . '\s+name\s*=\s*(["\'])(?<name>[\s\S]*?)\1/m',
subject: $contents,
matches: $matches,
flags: PREG_SET_ORDER,
);

if (!$hasMatches) {
return [];
}

return collect($matches)->map(fn($match) => $match['name']);
}

/**
* Preloads an icon
*/
protected function preloadIcon(string $icon): void
{
$this->info("Preloading {$icon}...");
$this->renderer->render($icon);
}
}
8 changes: 6 additions & 2 deletions src/IconServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ class IconServiceProvider extends ServiceProvider
public function register(): void
{
// Merge the default configuration
$this->mergeConfigFrom(__DIR__.'/../config/unicon.php', 'unicon');
$this->mergeConfigFrom(__DIR__ . '/../config/unicon.php', 'unicon');

// Bind the IconRenderer to the container
$this->app->bind(IconRenderer::class, function (Application $app) {
Expand All @@ -34,8 +34,12 @@ public function boot(): void
{
if ($this->app->runningInConsole()) {
$this->publishes([
__DIR__.'/../config/unicon.php' => config_path('unicon.php'),
__DIR__ . '/../config/unicon.php' => config_path('unicon.php'),
], 'unicon-config');

$this->commands([
Commands\IconsPreloadCommand::class,
]);
}
}
}
Loading