LessCompiler: Add support for variable exports by modules

Using the following in a module's less file:

```
@exports: {
  @foo: "bar";
  @number: 4;
  @color: red;
};
```

will export the variables `@foo`, `@number` and `@color` into the global
scope. Though, exports are not able to override already defined variables.
That's still reserved for themes.
This commit is contained in:
Johannes Meyer 2020-11-19 11:30:34 +01:00
parent a33317aeab
commit 7c58b3ced1
1 changed files with 25 additions and 3 deletions

View File

@ -4,8 +4,6 @@
namespace Icinga\Web;
use Icinga\Application\Logger;
use RecursiveArrayIterator;
use RecursiveIteratorIterator;
use lessc;
/**
@ -173,6 +171,7 @@ class LessCompiler
}
$moduleCss = '';
$exportedVars = [];
foreach ($this->moduleLessFiles as $moduleName => $moduleLessFiles) {
$moduleCss .= '.icinga-module.module-' . $moduleName . ' {';
@ -184,13 +183,36 @@ class LessCompiler
}
foreach ($moduleLessFiles as $moduleLessFile) {
$moduleCss .= file_get_contents($moduleLessFile);
$content = file_get_contents($moduleLessFile);
$pattern = '/^@exports:\s*{((?:\s*@[^:}]+:[^;]*;\s+)+)};$/m';
if (preg_match_all($pattern, $content, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$content = str_replace($match[0], '', $content);
foreach (explode("\n", trim($match[1])) as $line) {
list($name, $value) = explode(':', $line, 2);
$exportedVars[trim($name)] = trim($value, ' ;');
}
}
}
$moduleCss .= $content;
}
$moduleCss .= '}';
}
$this->source .= $moduleCss;
$varExports = '';
foreach ($exportedVars as $name => $value) {
$varExports .= sprintf("%s: %s;\n", $name, $value);
}
// exported vars are injected at the beginning to avoid that they are
// able to override other variables, that's what themes are for
$this->source = $varExports . "\n\n" . $this->source;
if ($this->theme !== null) {
$this->source .= file_get_contents($this->theme);
}