Files
livewire-material/tests/Support/ComponentStylesheet.php
T
Andreas Reinhold / reiniandClaude Opus 5 247c596c3a Cut duplicated and speculative code across the package
An over-engineering audit of the whole tree, applied in five reviewed
batches. Behaviour stays the same except where UPGRADE.md says otherwise.

PHP: the showcase and error-page stylesheets are prebuilt into
resources/dist by bin/stylesheets.mjs, through Vite's own postcss-import
(first occurrence kept, the order an application's build gives), instead
of Stylesheets::bundle() inlining imports on every request; only the
import walk DesignGuard needs stays. SchemeStylesheet::withProfiles()
replaces three copies of the scheme-plus-profiles loop, material:scheme
leaves spec and contrast checks to the node script that already made
them, and the error page's scheme cache, the hashed view namespace, the
translations path with no lang/ folder and DesignGuard's 1.x-name hints
are gone.

JS: the androidx shape port progress.js and both bin scripts each carried
lives once in resources/js/shapes.js (the generated SVGs are unchanged);
util.js holds ringIndex(), ms(), reopenGuard() and remember(), which
were written out several times; listeners are released through
AbortController; tooltip.js's hoverPopover() serves the rich tooltip too.

CSS: every rule for an element inside the navigation rail queries
`--md-navigation-rail-value` instead of repeating the seven collapsed
conditions under five media branches; badge, alert, progress, slider and
button read one non-inheriting colour-role table (components/color.css);
the dialog chrome, the submenu's popover chrome, the chip's state layer
and touch target, and the visually-hidden inputs use the shared rules
they copied; foundation/tokens.css is folded into foundation.css.

Views: Support\Field and Support\Link replace the error-key, bound-value
and link-attribute blocks copied into the fields and link components;
the timepicker period group, the menu filter and the showcase head are
partials; the datepicker's steppers and entry fields are loops; component
docblocks no longer restate SKILL.md.

Tests and tooling: one dataset-driven ComponentStylesheetsTest replaces
four per-group files, DesignGuardTest and the layout-component tests use
datasets, browser tests share one ready() helper, CSS parsing lives in
ComponentStylesheet alone. docs/audits and the finding IDs citing it are
removed, as are pestphp/pest-plugin-laravel, the unused composer scripts
and check:font; the lint job runs in the feature job, which now installs
node packages so the prebuilt-stylesheet staleness test runs in CI.

Feature suite 1177 passed, Chrome browser suite 299 passed.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 19:29:21 +02:00

349 lines
11 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
namespace NoNameWeb\LivewireMaterial\Tests\Support;
use RuntimeException;
/**
* A component stylesheet (resources/css/components/<name>.css), read the way a render test asks
* about it: its imports, its layer blocks, and the declarations of a rule by its selector.
*
* Nesting is resolved as the browser resolves it — `&` stands for the parent selector, and a
* nested selector without `&` is a descendant of it — so a test names the selector the rule
* applies to (`[data-md-button]:focus-visible`), not how the file happens to nest it. At-rules
* (`@media`, `@starting-style`, `@supports`) are kept beside the selector they wrap.
*/
final class ComponentStylesheet
{
/** @var list<array{selector: string, at: list<string>, declarations: array<string, string>}> */
private array $rules = [];
/** @var list<string> */
private array $statements = [];
/** @var list<string> */
private array $blocks = [];
private function __construct(public readonly string $name, public readonly string $css)
{
$source = self::withoutComments($css);
foreach (self::items($source) as $item) {
if (isset($item['statement'])) {
$this->statements[] = $item['statement'];
continue;
}
$this->blocks[] = $item['prelude'];
$this->collect($item['prelude'], $item['body'], null, []);
}
}
public static function read(string $name): self
{
$path = self::path($name);
if (! is_file($path)) {
throw new RuntimeException("No stylesheet [{$name}].");
}
return new self($name, (string) file_get_contents($path));
}
public static function path(string $name): string
{
return self::cssPath("components/{$name}.css");
}
/**
* resources/css itself, or a path under it — the root every stylesheet test resolves paths
* from.
*/
public static function cssPath(string $relative = ''): string
{
return dirname(__DIR__, 2).'/resources/css'.($relative === '' ? '' : "/{$relative}");
}
/**
* The statements before the first block, in order: the layer statement and the imports.
*
* @return list<string>
*/
public function statements(): array
{
return $this->statements;
}
/**
* The files this stylesheet imports, as written.
*
* @return list<string>
*/
public function imports(): array
{
return array_values(array_filter(array_map(self::importPath(...), $this->statements)));
}
/**
* The file a plain `@import '<path>';` statement names, or null for anything else (a
* statement with `layer()`/`supports()`/media after the path, or not an import at all).
*/
public static function importPath(string $statement): ?string
{
return preg_match('/^@import\s+([\'"])(.+?)\1;$/', $statement, $match) === 1 ? $match[2] : null;
}
/**
* The declarations of a flat block body — no nested rule inside it, just `property: value;`
* pairs (a `:root` block, a media query's own single nested rule already unwrapped by the
* caller). declarations() above is for a selector inside the full, nested stylesheet; this is
* for a body a caller already has in hand.
*
* @return array<string, string>
*/
public static function flatDeclarations(string $body): array
{
return collect(explode(';', $body))
->map(fn (string $declaration): string => trim($declaration))
->filter()
->mapWithKeys(fn (string $declaration): array => [trim(strstr($declaration, ':', true)) => trim(substr(strstr($declaration, ':'), 1))])
->all();
}
/**
* The preludes of the top-level blocks.
*
* @return list<string>
*/
public function blocks(): array
{
return $this->blocks;
}
/**
* The declarations of every rule for this selector (and inside these at-rules, outermost
* first), merged in source order.
*
* @param list<string> $at
* @return array<string, string>
*/
public function declarations(string $selector, array $at = []): array
{
$selector = self::normalise($selector);
$at = array_map(self::normalise(...), $at);
$found = false;
$declarations = [];
foreach ($this->rules as $rule) {
if ($rule['selector'] === $selector && $rule['at'] === $at) {
$found = true;
$declarations = array_merge($declarations, $rule['declarations']);
}
}
if (! $found) {
throw new RuntimeException("{$this->name}.css has no rule [{$selector}]".($at === [] ? '' : ' inside ['.implode(' ', $at).']').'.');
}
return $declarations;
}
/**
* Every rule, nesting resolved, in source order: for a test that has to walk all of them rather
* than name one.
*
* @return list<array{selector: string, at: list<string>, declarations: array<string, string>}>
*/
public function rules(): array
{
return $this->rules;
}
public function has(string $selector, array $at = []): bool
{
try {
$this->declarations($selector, $at);
return true;
} catch (RuntimeException) {
return false;
}
}
/**
* Every media query the stylesheet writes.
*
* @return list<string>
*/
public function mediaQueries(): array
{
preg_match_all('/@media\s*([^{]+)\{/', self::withoutComments($this->css), $matches);
return array_map(fn (string $query): string => self::normalise($query), $matches[1]);
}
/**
* @param list<string> $at
*/
private function collect(string $prelude, string $body, ?string $parent, array $at): void
{
if (str_starts_with($prelude, '@layer')) {
foreach (self::items($body) as $item) {
if (isset($item['prelude'])) {
$this->collect($item['prelude'], $item['body'], $parent, $at);
}
}
return;
}
if (str_starts_with($prelude, '@')) {
$at[] = self::normalise($prelude);
$selector = $parent;
} else {
$selector = $parent === null ? self::normalise($prelude) : self::nest($parent, $prelude);
}
$declarations = [];
foreach (self::items($body, true) as $item) {
if (isset($item['prelude'])) {
$this->collect($item['prelude'], $item['body'], $selector, $at);
} elseif (isset($item['statement']) && str_contains($item['statement'], ':') && $selector !== null) {
[$property, $value] = explode(':', rtrim($item['statement'], ';'), 2);
$declarations[trim($property)] = self::normalise($value);
}
}
if ($selector !== null && $declarations !== []) {
$this->rules[] = ['selector' => $selector, 'at' => $at, 'declarations' => $declarations];
}
}
private static function nest(string $parent, string $child): string
{
$parents = self::split($parent);
return implode(', ', array_merge(...array_map(
fn (string $each): array => array_map(
fn (string $part): string => str_contains($part, '&') ? str_replace('&', $each, $part) : "{$each} {$part}",
self::split($child),
),
$parents,
)));
}
/**
* A selector list split at its top-level commas.
*
* @return list<string>
*/
private static function split(string $selector): array
{
$parts = [];
$depth = 0;
$current = '';
foreach (str_split(self::normalise($selector)) as $char) {
$depth += match ($char) {
'(', '[' => 1,
')', ']' => -1,
default => 0,
};
if ($char === ',' && $depth === 0) {
$parts[] = trim($current);
$current = '';
continue;
}
$current .= $char;
}
$parts[] = trim($current);
return $parts;
}
private static function normalise(string $text): string
{
return trim((string) preg_replace('/\s+/', ' ', $text));
}
/**
* `$css` with every comment and quoted string blanked out (the quoted string kept, the comment
* dropped) — shared by every test that has to tell a `/* … *\/` in a stylesheet from real CSS.
*/
public static function withoutComments(string $css): string
{
return (string) preg_replace('~("(?:\\\\.|[^"\\\\])*"|\'(?:\\\\.|[^\'\\\\])*\')|/\*.*?\*/~s', '$1', $css);
}
/**
* The statements and blocks at the top of a piece of CSS. Inside a rule a declaration may end
* at the closing brace without a semicolon. `$css` must already be comment-free
* (withoutComments()) — this does not strip them itself, so a caller walking nested bodies
* (already substrings of a stripped source) does not pay for it twice.
*
* @return list<array{statement: string}|array{prelude: string, body: string}>
*/
public static function items(string $css, bool $declarations = false): array
{
$items = [];
$start = 0;
$depth = 0;
$parens = 0;
$quote = null;
$opening = 0;
for ($i = 0, $length = strlen($css); $i < $length; $i++) {
$char = $css[$i];
if ($quote !== null) {
if ($char === '\\') {
$i++;
} elseif ($char === $quote) {
$quote = null;
}
continue;
}
if ($char === '"' || $char === "'") {
$quote = $char;
} elseif ($char === '(') {
$parens++;
} elseif ($char === ')') {
$parens--;
} elseif ($char === '{') {
if ($depth++ === 0) {
$opening = $i;
}
} elseif ($char === '}' && --$depth === 0) {
$items[] = [
'prelude' => self::normalise(substr($css, $start, $opening - $start)),
'body' => substr($css, $opening + 1, $i - $opening - 1),
];
$start = $i + 1;
} elseif ($char === ';' && $depth === 0 && $parens === 0) {
$items[] = ['statement' => self::normalise(substr($css, $start, $i - $start)).';'];
$start = $i + 1;
}
}
$rest = trim(substr($css, $start));
if ($rest !== '') {
if (! $declarations) {
throw new RuntimeException('The stylesheet ends inside an unclosed rule.');
}
$items[] = ['statement' => self::normalise($rest).';'];
}
return $items;
}
}