Skip to content
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
21 changes: 21 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,27 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog).

## [0.3.0](https://github.com/hphoeksma/theme.cssvariables/compare/0.2.3...0.3.0) - 2026-11-19

### Added

- Support for Neos 8.3, 8.4, 9.0, 9.1 and 9.2 (`neos/neos` and `neos/flow` `^8.3 || ^9.0`).
- Eel helper `CssVariables.customCss(site)`.

### Changed

- Overrides are rendered inline as a `<style>` tag in the page head instead of a published stylesheet. Saving and restoring flushes the content cache.
- Minified CSS is read as well.
- `symfony/finder` is now an explicit dependency.

### Fixed

- Module crashed on Neos 9 (`SiteNodeName` used as array key).
- The default `excludedPaths` entry excluded every CSS file, so no variables were found.
- The custom stylesheet was never loaded on the frontend.
- Saving created a symlink inside the package directory, which could break every page.
- Variable names and values are sanitised before they are stored.

## [0.2.1](https://github.com/hphoeksma/theme.cssvariables/compare/0.2.0...0.2.1) - 2019-10-18

### Commits
Expand Down
60 changes: 60 additions & 0 deletions Classes/Eel/CssVariablesHelper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
<?php
declare(strict_types=1);

namespace Theme\CssVariables\Eel;

use Neos\Eel\ProtectedContextAwareInterface;
use Neos\Flow\Annotations as Flow;
use Theme\CssVariables\Service\WriteCssVariablesService;

/**
* Eel helper `CssVariables`: returns the overridden variables of a site for inline rendering.
*/
class CssVariablesHelper implements ProtectedContextAwareInterface
{
/**
* @Flow\Inject
* @var WriteCssVariablesService
*/
protected $writeCssVariablesService;

/**
* @param object|null $siteNode the site node (Neos 8 NodeInterface or Neos 9 Node)
*/
public function customCss($siteNode): string
{
$siteNodeName = $this->getSiteNodeName($siteNode);
if ($siteNodeName === null) {
return '';
}

$pathAndFilename = $this->writeCssVariablesService->getPathAndFilename($siteNodeName);
if (!is_file($pathAndFilename)) {
return '';
}

// The file is written by WriteCssVariablesService, but never allow it to close the style tag
return str_replace('<', '', (string)file_get_contents($pathAndFilename));
}

private function getSiteNodeName($siteNode): ?string
{
if (!is_object($siteNode)) {
return null;
}
// Neos 8: NodeInterface::getName()
if (method_exists($siteNode, 'getName')) {
return (string)$siteNode->getName();
}
// Neos 9: Node::$name (NodeName|null), equal to the SiteNodeName
if (property_exists($siteNode, 'name') && $siteNode->name !== null) {
return $siteNode->name->value;
}
return null;
}

public function allowsCallOfMethod($methodName): bool
{
return true;
}
}
12 changes: 11 additions & 1 deletion Classes/Module/Controller/BackendController.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Neos\Flow\Mvc\Controller\ActionController;
use Neos\Flow\Mvc\Exception\StopActionException;
use Neos\Flow\Package\PackageManager;
use Neos\Fusion\Core\Cache\ContentCache;
use Neos\Neos\Domain\Exception;
use Neos\Neos\Domain\Model\Site;
use Neos\Neos\Domain\Repository\SiteRepository;
Expand Down Expand Up @@ -45,6 +46,13 @@ class BackendController extends ActionController
* @Flow\Inject
*/
protected SiteRepository $siteRepository;

/**
* The variables are rendered inline in the cached page head
* @Flow\Inject
* @var ContentCache
*/
protected $contentCache;
/**
*
* @throws Exception
Expand Down Expand Up @@ -77,6 +85,7 @@ public function saveAction(array $variables, array $default, string $site): void
// Save only if there are changed variables
if (!empty($changedVariables)) {
$this->writeCssVariablesService->writeCssVariables($changedVariables, $site);
$this->contentCache->flush();
}

$this->redirect('index');
Expand All @@ -88,7 +97,8 @@ public function saveAction(array $variables, array $default, string $site): void
*/
public function restoreAction(Site $site): void
{
$this->writeCssVariablesService->cleanCustomCss($site->getNodeName());
$this->writeCssVariablesService->cleanCustomCss((string)$site->getNodeName());
$this->contentCache->flush();
$this->redirect('index');
}

Expand Down
22 changes: 15 additions & 7 deletions Classes/Service/ReadCSsVariablesService.php
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,11 @@ public function readCssVariables()

/** @var Site $site */
foreach ($this->siteRepository->findAll() as $site) {
// Neos 8 returns a string, Neos 9 a SiteNodeName value object
$siteNodeName = (string)$site->getNodeName();

// Load the override values
$files = $this->getCustomCssVariables($site->getNodeName());
$files = $this->getCustomCssVariables($siteNodeName);
if ($this->getCssFiles()) {
foreach ($this->getCssFiles() as $file) {
if (!empty($this->readVariables($file)) && !str_starts_with($file->getRelativePathname(), 'Private')) {
Expand All @@ -73,13 +76,13 @@ public function readCssVariables()
}
}

$result[$site->getNodeName()]['cssfile'] = [];
$result[$siteNodeName]['cssfile'] = [];

foreach (array_reverse($files) as $file) {
$result[$site->getNodeName()]['cssfile'] = Arrays::arrayMergeRecursiveOverrule($result[$site->getNodeName()]['cssfile'], $file);
$result[$siteNodeName]['cssfile'] = Arrays::arrayMergeRecursiveOverrule($result[$siteNodeName]['cssfile'], $file);
}

if (empty($result[$site->getNodeName()]['cssfile'])) $result[$site->getNodeName()]['error'] = 'No css variables found';
if (empty($result[$siteNodeName]['cssfile'])) $result[$siteNodeName]['error'] = 'No css variables found';

}

Expand Down Expand Up @@ -120,8 +123,9 @@ public function readVariables(SplFileInfo $file): array
$variables = [];
$content = $file->getContents();

// Match all standalone custom variables formatted as `--variable-name: value;`
preg_match_all('/^\s*--([\w-]+):\s*([^;]+);/m', $content, $matches, PREG_SET_ORDER);
// Match custom property declarations `--variable-name: value` at the start of a line or after
// `{` / `;`, so minified CSS (and the stored override file) is read as well
preg_match_all('/(?:^|[{;])\s*--([\w-]+)\s*:\s*([^;{}]+)(?=[;}])/m', $content, $matches, PREG_SET_ORDER);

foreach ($matches as $match) {
if (isset($match[1]) && isset($match[2])) {
Expand Down Expand Up @@ -258,7 +262,11 @@ private function getCssFiles(): array|Finder|null

// Manually filter out files from the excluded paths
$finder->filter(function (\SplFileInfo $file) {
foreach ($this->excludedPaths as $excludedPath) {
foreach ($this->excludedPaths ?? [] as $excludedPath) {
// An empty entry (the default `-` in Settings.yaml) would match every path
if (empty($excludedPath)) {
continue;
}
if (str_contains($file->getRealPath(), $excludedPath)) {
return false; // Exclude this file
}
Expand Down
110 changes: 40 additions & 70 deletions Classes/Service/WriteCssVariablesService.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,110 +7,80 @@
use Neos\Utility\Files;

/**
* Class WriteCssVariablesService
* @package Theme\CssVariables\Module\Service
* Stores the overridden CSS variables of a site in Data/Persistent.
*
* The file is rendered inline by Fusion (see CssVariablesHelper), so nothing is
* published to Web/_Resources and nothing is written into the package directory.
*
* @Flow\Scope("singleton")
*/
class WriteCssVariablesService
{

/**
* @Flow\InjectConfiguration("stylesheetName")
* @var string
*/
protected $stylesheetName;

/**
* @param array $variables
* @param string $site
* @return bool|int
* @param array<string, string> $variables
* @throws FilesException
*/
public function writeCssVariables(array $variables, string $site): bool|int
public function writeCssVariables(array $variables, string $site): bool
{

$contents = ':root{' . $this->processVariables($variables) . '}';

// Setup the Directory structure
Files::createDirectoryRecursively(Files::concatenatePaths([
FLOW_PATH_DATA,
'Persistent',
'Theme',
'CssVariables',
$site
]));

// Store in Data/Persistent
$persistentPathAndFilename = Files::concatenatePaths([
FLOW_PATH_ROOT,
'Data',
'Persistent',
'Theme',
'CssVariables',
$site,
$this->stylesheetName
]);

file_put_contents($persistentPathAndFilename, $contents);

// Create a symlink in Public Resources if it doesn't exist
$publicPathAndFilename = Files::concatenatePaths([
FLOW_PATH_ROOT,
'Web',
'_Resources',
'Static',
'Packages',
'Theme.CssVariables',
$site . '_' . $this->stylesheetName
]);

if (!Files::is_link($publicPathAndFilename)) {
Files::createRelativeSymlink($persistentPathAndFilename, $publicPathAndFilename);
}
Files::createDirectoryRecursively($this->getDirectory($site));
file_put_contents($this->getPathAndFilename($site), $contents);

return true;
}

/**
* @param array $variables
* @return string
* @param array<string, string> $variables
*/
public function processVariables(array $variables)
public function processVariables(array $variables): string
{
$processedVariables = [];
foreach ($variables as $variableName => $variableValue) {
$variableName = (string)$variableName;
// Only accept custom property names, and keep values from breaking out of the declaration
if (!preg_match('/^--[\w-]+$/', $variableName)) {
continue;
}
$variableValue = trim(str_replace(['<', '>', '{', '}', ';'], '', (string)$variableValue));
if ($variableValue === '') {
continue;
}
$processedVariables[] = $variableName . ':' . $variableValue;
}

return implode(';', $processedVariables);
}

/**
* @param string $site
*/
public function cleanCustomCss(string $site): void
{
// Remove the symlink
$publicPathAndFilename = Files::concatenatePaths([
FLOW_PATH_WEB,
'_Resources',
'Static',
'Packages',
'Theme.CssVariables',
$site . '_' . $this->stylesheetName
]);

Files::unlink($publicPathAndFilename);
$pathAndFilename = $this->getPathAndFilename($site);
if (is_file($pathAndFilename)) {
Files::unlink($pathAndFilename);
}

// Remove the stored variables
$persistentPathAndFilename = Files::concatenatePaths([
FLOW_PATH_DATA,
'Persistent',
'Theme',
'CssVariables',
$site,
$this->stylesheetName
// Versions up to 0.2.x published a symlink next to the package's public resources
$legacyLink = Files::concatenatePaths([
FLOW_PATH_WEB, '_Resources', 'Static', 'Packages', 'Theme.CssVariables', $site . '_' . $this->stylesheetName
]);
if (is_link($legacyLink)) {
unlink($legacyLink);
}
}

Files::unlink($persistentPathAndFilename);
public function getPathAndFilename(string $site): string
{
return Files::concatenatePaths([$this->getDirectory($site), $this->stylesheetName]);
}

private function getDirectory(string $site): string
{
return Files::concatenatePaths([FLOW_PATH_DATA, 'Persistent', 'Theme', 'CssVariables', $site]);
}
}
3 changes: 3 additions & 0 deletions Configuration/Settings.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ Neos:
fusion:
autoInclude:
Theme.CssVariables: true
Fusion:
defaultContext:
CssVariables: 'Theme\CssVariables\Eel\CssVariablesHelper'

Theme:
CssVariables:
Expand Down
20 changes: 15 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,13 @@ Each of those can be enabled via the `Settings.yaml`. (See below).
![](Resources/Private/Documentation/Images/Module.png)

### What happens in the background?
The module reads all CSS files and extracts all variables declared inside the `:root` selector.
The module reads all CSS files in the `Resources/Public` folders of your packages (minified or not) and extracts the custom properties (`--name: value`).
If multiple files are found (for example when using a bootstrap based theme) the array of variables
get merged where the top level file is considered to be the most relevant one.

When you change the values a new css file is being created and store inside the `Data/Persistent/Theme/CssVariables` folder.
It is then symlinked inside the Public resources folder of the Theme.CssVariables package.
When you change the values, the overrides are stored in `Data/Persistent/Theme/CssVariables/<site>/custom.css`.
Fusion renders that file inline as a `<style>` tag in the page head, so nothing is published to `Web/_Resources`
and the overrides survive deployments that share `Data/Persistent`. Saving or restoring flushes the content cache.

It is loaded as well, if it exists, and is merged as last so the module shows the active settings
for the variables.
Expand All @@ -45,8 +46,17 @@ composer require theme/cssvariables
| types | `array` | `color` | Supported are: `color`,`font`,`breakpoint`,`other`. Where `other` means every variable we could not sensibly map to one of the others. |

### Fusion
Default the newly created CSS-file is placed with `@position = 'after stylesheets'`.
If your Neos Page setup is different, make sure the file is loaded after your Site's css files.
The overrides are rendered as `<style data-theme-cssvariables>` in `Neos.Neos:Page.head.cssVariables`,
with `@position = 'after stylesheets'`. If your Neos Page setup is different, make sure it is rendered after your site's CSS files.

The Eel helper `CssVariables.customCss(site)` returns the stored CSS, if you want to render it elsewhere.

## Compatibility

| Version | Neos |
| --- | --- |
| 0.3.x | 8.3, 8.4, 9.0, 9.1, 9.2 |
| 0.2.x | not installable on current Neos 8/9 |

### Access to the module
Our default policy is set for `Neos Administrators` only. However feel free to copy-paste the
Expand Down
9 changes: 3 additions & 6 deletions Resources/Private/Fusion/Root.fusion
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
prototype(Neos.Neos:Page) {
head {
cssVariables = Neos.Fusion:Component {
uri = Neos.Fusion:ResourceUri {
path = ${'resource://Theme.CssVariables/Public/' + Configuration.setting('Theme.CssVariables.stylesheetName')}
}
renderer = afx`
<link rel="stylesheet" href={props.uri}/>`
renderer.@if.has = ${File.exists(props.uri)}
css = ${CssVariables.customCss(site)}
renderer = afx`<style data-theme-cssvariables>{props.css}</style>`
renderer.@if.hasCss = ${!String.isBlank(props.css)}
@position = 'after stylesheets'
}
}
Expand Down
Loading
Loading