[1.x] Theme Extender to Allow overriding LESS files (#3008)

This PR introduces the ability to just override a LESS file's contents through an extender.
This is mainly useful for theme development, as there are times in extensively customized themes where overriding the actual file makes a huge difference vs overriding CSS styles which can turn into a maintenance hell real fast.

Overriding styles is more tedious than overriding files. When you're designing an element, you would normally rather start from a blank canvas, than a styled element. With an already styled element you have to first override and undo the styles you do not wish to have, only then can you start shaping it, but even then you'd always end up constantly undoing default styles. This mostly applies for more advanced themes. (example: 851c55516d/less/forum/DiscussionList.less)
This commit is contained in:
Sami Mazouz 2021-09-10 18:45:18 +01:00 committed by GitHub
parent 31961c4490
commit e4e3eb22f4
11 changed files with 313 additions and 6 deletions

View File

@ -153,9 +153,9 @@ class Frontend implements ExtenderInterface
}
if ($this->css) {
$assets->css(function (SourceCollector $sources) {
$assets->css(function (SourceCollector $sources) use ($moduleName) {
foreach ($this->css as $path) {
$sources->addFile($path);
$sources->addFile($path, $moduleName);
}
});
}

View File

@ -0,0 +1,69 @@
<?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\Extend;
use Flarum\Extension\Extension;
use Flarum\Frontend\Assets;
use Illuminate\Contracts\Container\Container;
class Theme implements ExtenderInterface
{
private $lessImportOverrides = [];
private $fileSourceOverrides = [];
/**
* This can be used to override LESS files that are imported within the code.
* For example, core's `forum.less` file imports a `forum/DiscussionListItem.less` file.
* The contents of this file can be overriden with this method.
*
* @param string $file : Relative path of the file to override, for example: `forum/Hero.less`
* @param string $newFilePath : Absolute path of the new file.
* @param string|null $extensionId : If overriding an extension file, specify its ID, for example: `flarum-tags`.
* @return self
*/
public function overrideLessImport(string $file, string $newFilePath, string $extensionId = null): self
{
$this->lessImportOverrides[] = compact('file', 'newFilePath', 'extensionId');
return $this;
}
/**
* This method allows overriding LESS file sources.
* For example `forum.less`, `admin.less`, `mixins.less` and `variables.less` are file sources,
* and can therefore be overriden using this method.
*
* @param string $file : Name of the file to override, for example: `admin.less`
* @param string $newFilePath : Absolute path of the new file.
* @param string|null $extensionId : If overriding an extension file, specify its ID, for example: `flarum-tags`.
* @return self
*/
public function overrideFileSource(string $file, string $newFilePath, string $extensionId = null): self
{
$this->fileSourceOverrides[] = compact('file', 'newFilePath', 'extensionId');
return $this;
}
public function extend(Container $container, Extension $extension = null)
{
$container->extend('flarum.assets.factory', function (callable $factory) {
return function (...$args) use ($factory) {
/** @var Assets $assets */
$assets = $factory(...$args);
$assets->addLessImportOverrides($this->lessImportOverrides);
$assets->addFileSourceOverrides($this->fileSourceOverrides);
return $assets;
};
});
}
}

View File

@ -52,6 +52,16 @@ class Assets
*/
protected $lessImportDirs;
/**
* @var array
*/
protected $lessImportOverrides = [];
/**
* @var array
*/
protected $fileSourceOverrides = [];
public function __construct(string $name, Filesystem $assetsDir, string $cacheDir = null, array $lessImportDirs = null)
{
$this->name = $name;
@ -155,6 +165,14 @@ class Assets
$compiler->setImportDirs($this->lessImportDirs);
}
if ($this->lessImportOverrides) {
$compiler->setLessImportOverrides($this->lessImportOverrides);
}
if ($this->fileSourceOverrides) {
$compiler->setFileSourceOverrides($this->fileSourceOverrides);
}
return $compiler;
}
@ -197,4 +215,14 @@ class Assets
{
$this->lessImportDirs = $lessImportDirs;
}
public function addLessImportOverrides(array $lessImportOverrides)
{
$this->lessImportOverrides = array_merge($this->lessImportOverrides, $lessImportOverrides);
}
public function addFileSourceOverrides(array $fileSourceOverrides)
{
$this->fileSourceOverrides = array_merge($this->fileSourceOverrides, $fileSourceOverrides);
}
}

View File

@ -10,6 +10,8 @@
namespace Flarum\Frontend\Compiler;
use Flarum\Frontend\Compiler\Source\FileSource;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Less_Parser;
/**
@ -27,6 +29,16 @@ class LessCompiler extends RevisionCompiler
*/
protected $importDirs = [];
/**
* @var Collection
*/
protected $lessImportOverrides;
/**
* @var Collection
*/
protected $fileSourceOverrides;
public function getCacheDir(): string
{
return $this->cacheDir;
@ -47,6 +59,16 @@ class LessCompiler extends RevisionCompiler
$this->importDirs = $importDirs;
}
public function setLessImportOverrides(array $lessImportOverrides)
{
$this->lessImportOverrides = new Collection($lessImportOverrides);
}
public function setFileSourceOverrides(array $fileSourceOverrides)
{
$this->fileSourceOverrides = new Collection($fileSourceOverrides);
}
/**
* @throws \Less_Exception_Parser
*/
@ -61,9 +83,14 @@ class LessCompiler extends RevisionCompiler
$parser = new Less_Parser([
'compress' => true,
'cache_dir' => $this->cacheDir,
'import_dirs' => $this->importDirs
'import_dirs' => $this->importDirs,
'import_callback' => $this->lessImportOverrides ? $this->overrideImports($sources) : null,
]);
if ($this->fileSourceOverrides) {
$sources = $this->overrideSources($sources);
}
foreach ($sources as $source) {
if ($source instanceof FileSource) {
$parser->parseFile($source->getPath());
@ -75,6 +102,54 @@ class LessCompiler extends RevisionCompiler
return $parser->getCss();
}
protected function overrideSources(array $sources): array
{
foreach ($sources as $source) {
if ($source instanceof FileSource) {
$basename = basename($source->getPath());
$override = $this->fileSourceOverrides
->where('file', $basename)
->firstWhere('extensionId', $source->getExtensionId());
if ($override) {
$source->setPath($override['newFilePath']);
}
}
}
return $sources;
}
protected function overrideImports(array $sources): callable
{
$baseSources = (new Collection($sources))->filter(function ($source) {
return $source instanceof Source\FileSource;
})->map(function (FileSource $source) {
$path = realpath($source->getPath());
$path = Str::beforeLast($path, '/less/');
return [
'path' => $path,
'extensionId' => $source->getExtensionId(),
];
})->unique('path');
return function ($evald) use ($baseSources): ?array {
$relativeImportPath = Str::of($evald->PathAndUri()[0])->split('/\/less\//');
$extensionId = $baseSources->where('path', $relativeImportPath->first())->pluck('extensionId')->first();
$overrideImport = $this->lessImportOverrides
->where('file', $relativeImportPath->last())
->firstWhere('extensionId', $extensionId);
if (! $overrideImport) {
return null;
}
return [$overrideImport['newFilePath'], $evald->PathAndUri()[1]];
};
}
protected function getCacheDifferentiator(): ?array
{
return [

View File

@ -21,16 +21,22 @@ class FileSource implements SourceInterface
*/
protected $path;
/**
* @var string
*/
protected $extensionId;
/**
* @param string $path
*/
public function __construct(string $path)
public function __construct(string $path, ?string $extensionId = null)
{
if (! file_exists($path)) {
throw new InvalidArgumentException("File not found at path: $path");
}
$this->path = $path;
$this->extensionId = $extensionId;
}
/**
@ -56,4 +62,14 @@ class FileSource implements SourceInterface
{
return $this->path;
}
public function setPath(string $path): void
{
$this->path = $path;
}
public function getExtensionId(): ?string
{
return $this->extensionId;
}
}

View File

@ -23,9 +23,9 @@ class SourceCollector
* @param string $file
* @return $this
*/
public function addFile(string $file)
public function addFile(string $file, string $extensionId = null)
{
$this->sources[] = new FileSource($file);
$this->sources[] = new FileSource($file, $extensionId);
return $this;
}

View File

@ -0,0 +1,3 @@
.Imported {
// ...
}

View File

@ -0,0 +1 @@
.dummy_test_case{color:red}

View File

@ -0,0 +1,5 @@
@import 'Imported';
.dummy {
color: yellow;
}

View File

@ -0,0 +1,3 @@
body {
color: orange;
}

View File

@ -0,0 +1,107 @@
<?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 ThemeTest extends TestCase
{
/**
* @test
*/
public function theme_extender_override_import_doesnt_work_by_default()
{
$response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode());
$cssFilePath = $this->app()->getContainer()->make('filesystem')->disk('flarum-assets')->path('forum.css');
$this->assertStringNotContainsString('.dummy_test_case{color:red}', file_get_contents($cssFilePath));
}
/**
* @test
*/
public function theme_extender_override_import_works()
{
$this->extend(
(new Extend\Theme)
->overrideLessImport('forum/Hero.less', __DIR__.'/../../fixtures/less/dummy.less')
);
$response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode());
$cssFilePath = $this->app()->getContainer()->make('filesystem')->disk('flarum-assets')->path('forum.css');
$this->assertStringContainsString('.dummy_test_case{color:red}', file_get_contents($cssFilePath));
}
/**
* @test
*/
public function theme_extender_override_import_works_with_external_sources()
{
$this->extend(
(new Extend\Frontend('forum'))
->css(__DIR__.'/../../fixtures/less/forum.less'),
(new Extend\Theme)
->overrideLessImport('Imported.less', __DIR__.'/../../fixtures/less/dummy.less', 'site-custom')
);
$response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode());
$cssFilePath = $this->app()->getContainer()->make('filesystem')->disk('flarum-assets')->path('forum.css');
$contents = file_get_contents($cssFilePath);
$this->assertStringNotContainsString('.Imported', $contents);
$this->assertStringContainsString('.dummy_test_case{color:red}', $contents);
$this->assertStringContainsString('.dummy{color:yellow}', $contents);
}
/**
* @test
*/
public function theme_extender_override_file_source_works()
{
$this->extend(
(new Extend\Theme)
->overrideFileSource('forum.less', __DIR__.'/../../fixtures/less/override_filesource.less')
);
$response = $this->send($this->request('GET', '/'));
$this->assertEquals(200, $response->getStatusCode());
$cssFilePath = $this->app()->getContainer()->make('filesystem')->disk('flarum-assets')->path('forum.css');
$this->assertEquals('body{color:orange}', file_get_contents($cssFilePath));
}
/**
* @test
*/
public function theme_extender_override_file_source_works_by_failing_when_necessary()
{
$this->extend(
(new Extend\Theme)
->overrideFileSource('mixins.less', __DIR__.'/../../fixtures/less/dummy.less')
);
$response = $this->send($this->request('GET', '/'));
$this->assertStringContainsString('Less_Exception_Compiler', $response->getBody()->getContents());
$this->assertEquals(500, $response->getStatusCode());
}
}