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

Preload FontAwesome, JS and CSS #3057

Merged
merged 25 commits into from
Sep 20, 2021
Merged
Show file tree
Hide file tree
Changes from 20 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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
54 changes: 54 additions & 0 deletions src/Extend/Frontend.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Flarum\Foundation\Event\ClearingCache;
use Flarum\Frontend\Assets;
use Flarum\Frontend\Compiler\Source\SourceCollector;
use Flarum\Frontend\Document;
use Flarum\Frontend\Frontend as ActualFrontend;
use Flarum\Frontend\RecompileFrontendAssets;
use Flarum\Http\RouteCollection;
Expand All @@ -33,6 +34,7 @@ class Frontend implements ExtenderInterface
private $routes = [];
private $removedRoutes = [];
private $content = [];
private $preloads = [];

/**
* @param string $frontend: The name of the frontend.
Expand Down Expand Up @@ -124,11 +126,45 @@ public function content($callback): self
return $this;
}

/**
* Adds multiple asset preloads.
*
* The parameter should be an array of preload arrays, or a callable that returns this.
*
* A preload array must contain keys that pertain to the `<link rel="preload">` tag.
*
* For example, the following will add preload tags for a script and font file:
* ```
* $frontend->preloads([
* [
davwheat marked this conversation as resolved.
Show resolved Hide resolved
* 'href' => '/assets/my-script.js',
* 'as' => 'script',
* ],
* [
* 'href' => '/assets/fonts/my-font.woff2',
* 'as' => 'font',
* 'type' => 'font/woff2',
* 'crossorigin' => ''
* ]
* ]);
* ```
*
* @param callable|array $preloads
* @return self
*/
public function preloads($preloads): self
{
$this->preloads = array_merge($this->preloads, $preloads);
davwheat marked this conversation as resolved.
Show resolved Hide resolved

return $this;
}

public function extend(Container $container, Extension $extension = null)
{
$this->registerAssets($container, $this->getModuleName($extension));
$this->registerRoutes($container);
$this->registerContent($container);
$this->registerPreloads($container);
}

private function registerAssets(Container $container, string $moduleName): void
Expand Down Expand Up @@ -236,6 +272,24 @@ function (ActualFrontend $frontend, Container $container) {
);
}

private function registerPreloads(Container $container): void
{
if (empty($this->preloads)) {
return;
}

$container->resolving(
"flarum.frontend.$this->frontend",
function (ActualFrontend $frontend, Container $container) {
$frontend->content(function (Document $document) use ($container) {
foreach ($this->preloads as $preload) {
$document->preloads[] = is_callable($preload) ? ContainerUtil::wrapCallback($preload, $container)($document) : $preload;
}
askvortsov1 marked this conversation as resolved.
Show resolved Hide resolved
});
askvortsov1 marked this conversation as resolved.
Show resolved Hide resolved
}
);
}

private function getModuleName(?Extension $extension): string
{
return $extension ? $extension->getId() : 'site-custom';
Expand Down
37 changes: 37 additions & 0 deletions src/Frontend/Document.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,28 @@ class Document implements Renderable
*/
public $css = [];

/**
* An array of preloaded assets.
*
* Each array item should be an array containing keys that pertain to the
* `<link rel="preload">` tag.
*
* For example, the following will add a preload tag for a FontAwesome font file:
* ```
* $this->preloads[] = [
* 'href' => '/assets/fonts/fa-solid-900.woff2',
* 'as' => 'font',
* 'type' => 'font/woff2',
* 'crossorigin' => ''
* ];
* ```
*
* @see https://developer.mozilla.org/en-US/docs/Web/HTML/Link_types/preload
*
* @var array
*/
public $preloads = [];

/**
* @var Factory
*/
Expand Down Expand Up @@ -203,6 +225,19 @@ protected function makeContent(): View
return $this->view->make($this->contentView)->with('content', $this->content);
}

protected function makePreloads(): array
{
return array_map(function ($preload) {
$attributes = '';

foreach ($preload as $key => $value) {
$attributes .= " $key=\"".e($value).'"';
}

return "<link rel=\"preload\"$attributes>";
}, $this->preloads);
}

/**
* @return string
*/
Expand All @@ -216,6 +251,8 @@ protected function makeHead(): string
$head[] = '<link rel="canonical" href="'.e($this->canonicalUrl).'">';
}

$head = array_merge($head, $this->makePreloads());

$head = array_merge($head, array_map(function ($content, $name) {
return '<meta name="'.e($name).'" content="'.e($content).'">';
}, $this->meta, array_keys($this->meta)));
Expand Down
42 changes: 42 additions & 0 deletions src/Frontend/FrontendServiceProvider.php
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,48 @@ public function register()
$frontend->content($container->make(Content\CorePayload::class));
$frontend->content($container->make(Content\Meta::class));

$frontend->content(function (Document $document) use ($container) {
$filesystem = $container->make('filesystem')->disk('flarum-assets');

$fontawesome_preloads = [
[
'href' => $filesystem->url('fonts/fa-solid-900.woff2'),
'as' => 'font',
'type' => 'font/woff2',
'crossorigin' => ''
], [
'href' => $filesystem->url('fonts/fa-regular-400.woff2'),
'as' => 'font',
'type' => 'font/woff2',
'crossorigin' => ''
]
];
davwheat marked this conversation as resolved.
Show resolved Hide resolved

// Add preloads for base CSS and JS assets. Extensions should add their own via the extender.
$js_preloads = [];
$css_preloads = [];

foreach ($document->css as $url) {
$css_preloads[] = [
'href' => $url,
'as' => 'style'
];
}
foreach ($document->js as $url) {
$css_preloads[] = [
'href' => $url,
'as' => 'script'
];
}

$document->preloads = array_merge(
$css_preloads,
$js_preloads,
$fontawesome_preloads,
$document->preloads,
);
});

return $frontend;
};
});
Expand Down
93 changes: 93 additions & 0 deletions tests/integration/extenders/FrontendPreloadTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

/*
* This file is part of Flarum.
*
* For detailed copyright and license information, please view the
* LICENSE file that was distributed with this source code.
*/

namespace Flarum\Tests\integration\extenders;

use Flarum\Extend;
use Flarum\Testing\integration\TestCase;

class FrontendPreloadTest extends TestCase
{
private $customPreloadUrls = ['/my-preload', '/my-preload2'];

/**
* @test
*/
public function default_preloads_are_present()
{
$response = $this->send(
$this->request('GET', '/')
);

$filesystem = $this->app()->getContainer()->make('filesystem')->disk('flarum-assets');

$urls = [
$filesystem->url('fonts/fa-solid-900.woff2'),
$filesystem->url('fonts/fa-regular-400.woff2'),
];

$body = $response->getBody()->getContents();

foreach ($urls as $url) {
$this->assertStringContainsString("<link rel=\"preload\" href=\"$url\" as=\"font\" type=\"font/woff2\" crossorigin=\"\">", $body);
}
}

/**
* @test
*/
public function preloads_can_be_added()
{
$urls = $this->customPreloadUrls;

$this->extend(
(new Extend\Frontend('forum'))
->preloads(
array_map(function ($url) {
return ['href' => $url];
}, $urls)
)
);

$response = $this->send(
$this->request('GET', '/')
);
$body = $response->getBody()->getContents();

foreach ($urls as $url) {
$this->assertStringContainsString("<link rel=\"preload\" href=\"$url\">", $body);
}
}

/**
* @test
*/
public function preloads_can_be_added_via_callable()
{
$urls = $this->customPreloadUrls;

$this->extend(
(new Extend\Frontend('forum'))
->preloads(function () use ($urls) {
return array_map(function ($url) {
return ['href' => $url];
}, $urls);
})
);

$response = $this->send(
$this->request('GET', '/')
);
$body = $response->getBody()->getContents();

foreach ($urls as $url) {
$this->assertStringContainsString("<link rel=\"preload\" href=\"$url\">", $body);
}
}
}