Merge branch 'worktree-agent-a9b4c522a39c6ce62'

# Conflicts:
#	tests/Feature/StylesheetsTest.php
#	workbench/resources/css/app.css
This commit is contained in:
Andreas Reinhold / reini
2026-09-14 15:41:37 +02:00
37 changed files with 2791 additions and 881 deletions
+73 -3
View File
@@ -222,10 +222,10 @@ it('moves a connected group\'s choice with the arrow keys', function () {
});
it('rounds a split button\'s trailing half while its menu is open', function () {
$trailing = "document.querySelector('[data-split=\"trailing\"]')";
$trailing = "document.querySelector('[data-md-split=\"trailing\"]')";
showcase()
->click('[data-split="trailing"] >> nth=0')
->click('[data-md-split="trailing"] >> nth=0')
->assertScript("{$trailing}.getAttribute('aria-expanded') === 'true'")
->assertScript("getComputedStyle({$trailing}).borderTopLeftRadius === ({$trailing}.offsetHeight / 2) + 'px'");
});
@@ -235,7 +235,7 @@ it('keeps a connected segment\'s small inner corners, which a 9999px outer corne
// factor: a full corner written as 9999px drew the 8px inner corners square. Every radius
// in a connected group or a split button stays within half its height, so none is scaled.
showcase()
->assertScript("[...document.querySelectorAll('[data-button-group=\"connected\"] > *, [data-split]')].every((el) => { const cs = getComputedStyle(el); const half = el.offsetHeight / 2 + 0.5; return el.offsetHeight === 0 || ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomLeftRadius', 'borderBottomRightRadius'].every((corner) => parseFloat(cs[corner]) <= half); })")
->assertScript("[...document.querySelectorAll('[data-md-button-group=\"connected\"] > *, [data-md-split]')].every((el) => { const cs = getComputedStyle(el); const half = el.offsetHeight / 2 + 0.5; return el.offsetHeight === 0 || ['borderTopLeftRadius', 'borderTopRightRadius', 'borderBottomLeftRadius', 'borderBottomRightRadius'].every((corner) => parseFloat(cs[corner]) <= half); })")
->assertScript("(el => getComputedStyle(el).borderTopRightRadius === '8px')(document.querySelector('#buttons input[name=\"showcase-theme\"][value=\"light\"]').parentElement)");
});
@@ -464,3 +464,73 @@ it('closes a FAB menu when an item\'s action runs, and opens and closes it clean
->assertScript('! '.FAB_MENU.".matches(':popover-open')")
->assertScript(focused("getAttribute('aria-label') === 'New'"));
});
it('collapses an extended FAB to a FAB while the page scrolls down, and extends it on the way back', function () {
$fab = "document.querySelector('#buttons [data-md-collapse-on-scroll]')";
// Reduced motion takes the spring's duration to zero, so the width is final at once.
$page = visit('/material/buttons', ['reducedMotion' => 'reduce'])
->assertScript("document.readyState === 'complete' && typeof window.Alpine !== 'undefined'")
->assertScript("! {$fab}.hasAttribute('data-md-collapsed') && {$fab}.getBoundingClientRect().width > 56");
$page->script('window.scrollTo(0, 600)');
$page->assertScript("{$fab}.hasAttribute('data-md-collapsed')")
->assertScript("Math.round({$fab}.getBoundingClientRect().width) === 56")
// Clipped, not removed: the collapsed FAB keeps the extended one's name.
->assertScript("{$fab}.textContent.trim() === 'Compose'");
$page->script('window.scrollTo(0, 200)');
$page->assertScript("! {$fab}.hasAttribute('data-md-collapsed')")
->assertScript("{$fab}.getBoundingClientRect().width > 56");
});
it('takes a press on a small connected segment at its 48px edge, past what it draws', function () {
// M3: "XS and S connected button groups have a 48dp target area and a 48dp minimum width".
showcase()->assertScript(<<<'JS'
(() => {
const segment = document.querySelector('#buttons input[name="showcase-theme"][value="light"]').parentElement
segment.scrollIntoView({ block: 'center' })
const box = segment.getBoundingClientRect()
const x = box.left + box.width / 2
return box.height === 40 && box.width >= 48
&& document.elementFromPoint(x, box.top - 3) === segment
&& document.elementFromPoint(x, box.bottom + 3) === segment
})()
JS);
});
it('keeps one choice in a single, required selection group', function () {
$group = '#buttons [data-md-selection="single"]';
$view = "document.querySelector('{$group}').parentElement.querySelector('code').textContent";
$page = showcase();
$page->assertAttribute("{$group} button:has-text(\"Week\")", 'aria-pressed', 'true')
->click("{$group} button:has-text(\"Day\")")
->assertAttribute("{$group} button:has-text(\"Day\")", 'aria-pressed', 'true')
->assertAttribute("{$group} button:has-text(\"Week\")", 'aria-pressed', 'false')
->assertScript("{$view} === 'day'");
// Required: pressing the chosen button again leaves it chosen.
$page->click("{$group} button:has-text(\"Day\")")
->assertAttribute("{$group} button:has-text(\"Day\")", 'aria-pressed', 'true')
->assertScript("{$view} === 'day'");
});
it('toggles each choice of a multi selection group, down to none', function () {
$group = '#buttons [data-md-selection="multi"]';
$marks = "document.querySelector('{$group}').parentElement.querySelectorAll('code')[1].textContent";
showcase()
->assertAttribute("{$group} [aria-label=\"Bold\"]", 'aria-pressed', 'true')
->click("{$group} [aria-label=\"Italic\"]")
->assertAttribute("{$group} [aria-label=\"Italic\"]", 'aria-pressed', 'true')
->assertScript("{$marks} === 'bold, italic'")
->click("{$group} [aria-label=\"Bold\"]")
->click("{$group} [aria-label=\"Italic\"]")
->assertAttribute("{$group} [aria-label=\"Bold\"]", 'aria-pressed', 'false')
->assertAttribute("{$group} [aria-label=\"Italic\"]", 'aria-pressed', 'false')
->assertScript("{$marks} === 'none'");
});
@@ -0,0 +1,85 @@
<?php
use Illuminate\Support\Facades\File;
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
/**
* The actions and communication components, rewritten without Tailwind (plan step 36): each view
* renders `data-md-*` attributes and no class list of its own, and each has a stylesheet in
* `material.components` that imports the stylesheets of the components its view renders, writes
* its values from the tokens and its breakpoints as px range queries, and is imported from the
* "Actions and communication" block of components.css.
*/
dataset('action components', [
'loading',
'tooltip',
'badge',
'button',
'group',
'button-group',
'split-button',
'fab',
]);
it('draws the component from a stylesheet shaped like every package stylesheet', function (string $name) {
$css = ComponentStylesheet::read($name);
expect($css->css)->toStartWith('/*')
->and($css->statements()[0] ?? null)->toBe('@layer material.reset, material.tokens, material.base, material.layout, material.components, material.text, material.visibility;')
->and(array_slice($css->statements(), 1))->each->toMatch('/^@import \'\.\/[a-z-]+\.css\';$/')
->and($css->blocks())->each->toBe('@layer material.components')
->and($css->css)->not->toMatch('/@(?:tailwind|theme|utility|variant|custom-variant|apply|source|config|plugin|reference)\b|--(?:theme|spacing|alpha)\(|\btheme\(/');
foreach ($css->imports() as $import) {
expect(is_file(dirname(ComponentStylesheet::path($name)).'/'.$import))->toBeTrue("{$name}.css imports {$import}, which does not exist");
}
})->with('action components');
it('imports the stylesheet of every component its view renders', function (string $name) {
preg_match_all('/<x-livewire-material::([a-z-]+)/', File::get(__DIR__."/../../../resources/views/components/{$name}.blade.php"), $tags);
$rendered = collect($tags[1])->unique()
// A component still written for Tailwind has no stylesheet of its own to import yet; its
// old stylesheet, if it has one, lives in tailwind.css without the layer statement.
->filter(fn (string $tag): bool => is_file(ComponentStylesheet::path($tag)) && str_contains(File::get(ComponentStylesheet::path($tag)), '@layer material.components'))
->map(fn (string $tag): string => "./{$tag}.css")
->values()
->all();
expect(array_values(array_diff($rendered, ComponentStylesheet::read($name)->imports())))->toBe([]);
})->with('action components');
it('writes no class list into the view', function (string $name) {
$view = File::get(__DIR__."/../../../resources/views/components/{$name}.blade.php");
// A class the caller hands in (`hint-class`, `icon-class`, a slot's attributes) passes through.
expect($view)->not->toMatch('/(?<![\w-])class="(?!\{\{ \$)|@class\(|->class\(|toCssClasses|(?:x-bind)?:class=/');
})->with('action components');
it('takes its values from the tokens and its breakpoints in px', function (string $name) {
$css = ComponentStylesheet::read($name);
$source = (string) preg_replace('~/\*.*?\*/~s', '', $css->css);
// Colours are roles, shadows are elevation levels, type is a type style, motion is a spring.
expect($source)->not->toMatch('/#[0-9a-f]{3,8}\b|\b(?:rgba?|hsla?|oklch|oklab|lab|lch)\(/i')
->not->toMatch('/\bbox-shadow:(?!\s*(?:none|var\(--md-))/')
->not->toMatch('/\bfont:(?!\s*var\(--md-sys-typescale-)/')
->not->toMatch('/\btransition[a-z-]*:[^;]*(?:\d+m?s\b|\bease\b|ease-in|ease-out|cubic-bezier)/');
foreach ($css->mediaQueries() as $query) {
preg_match_all('/(\d*\.?\d+)(px|rem|em)\b/', $query, $lengths, PREG_SET_ORDER);
foreach ($lengths as [, $number, $unit]) {
expect($unit)->toBe('px', "{$name}.css: {$query}")
->and(in_array($number, ['600', '840', '1200', '1600'], true))->toBeTrue("{$name}.css: {$query} is not at an M3 breakpoint");
}
}
})->with('action components');
it('is imported from the actions and communication block of components.css', function (string $name) {
$components = File::get(__DIR__.'/../../../resources/css/components.css');
$block = substr($components, (int) strpos($components, '/* Actions and communication */'));
$block = substr($block, 0, (int) strpos($block, '/* Inputs, selection and data */'));
expect($block)->toContain("@import './components/{$name}.css';");
})->with('action components');
+7 -7
View File
@@ -65,14 +65,14 @@ it('keeps two trailing icon buttons below medium and four from it, the rest in a
->and(substr_count($html, '<span data-app-bar-action'))->toBe(3)
->and(substr_count($html, 'data-overflows-compact'))->toBe(2)
->and($html)->toMatch('/<span data-app-bar-action\s*>\s*<button[^>]*aria-label="Search"/')
->toMatch('/<span data-app-bar-action\s+data-overflows-compact\s*>\s*<a href="\/shares\/1\/share"[^>]*aria-label="Share"/')
->toMatch('/<span data-app-bar-action\s+data-overflows-compact\s*>\s*<a [^>]*href="\/shares\/1\/share"[^>]*aria-label="Share"/')
->not->toMatch('/<(?:button|a)[^>]*aria-label="(?:Archive|Delete)"/')
// Every icon button is named, tooltipped and reaches 48px.
->toMatch('/<button[^>]*aria-label="Search"[^>]*class="[^"]*touch-target/')
->toMatch('/<button[^>]*data-md-size="sm"[^>]*aria-label="Search"/')
->toMatch('/popover="manual"[^>]*>\s*Search<\/span>/')
->toMatch('/<button[^>]*aria-label="Star" aria-pressed="true"/')
// One overflow button per width, named and tooltipped.
->and(preg_match_all('/<button[^>]*aria-label="More options"[^>]*class="[^"]*touch-target/', $html))->toBe(2)
->and(preg_match_all('/<button[^>]*data-md-size="sm"[^>]*aria-label="More options"/', $html))->toBe(2)
->and(preg_match_all('/role="menu"\s+data-menu\s+aria-label="More options"/', $html))->toBe(2)
// Below medium: all but the first.
->and($compact)
@@ -168,7 +168,7 @@ it('sets a FAB at the end of a docked toolbar, resting flat on it', function ()
expect(file_get_contents(__DIR__.'/../../../resources/css/components/toolbar.css'))
->toMatch('/\[data-toolbar-fab\] \{\s+display: flex;\s+margin-inline-start: auto;/')
// A nested FAB rests at elevation 0.
->toMatch('/\[data-toolbar-fab\] \[data-fab\],\s+\[data-toolbar-fab\] \[data-fab\]:hover \{\s+box-shadow: none;/');
->toMatch('/\[data-toolbar-fab\] \[data-md-fab\],\s+\[data-toolbar-fab\] \[data-md-fab\]:hover \{\s+box-shadow: none;/');
});
it('centres a headline on a three-column row and curves the search container', function () {
@@ -192,7 +192,7 @@ it('keeps a toolbar at the bottom clear of the navigation bar', function () {
// A vertical toolbar keeps 24dp from the edge where a horizontal one keeps 16 (N-12).
->toContain('inset-inline-end: calc(1.5rem + var(--material-safe-right, env(safe-area-inset-right)));')
// A standard toolbar's standard buttons are primary (N-13).
->toContain('[data-toolbar]:not([data-vibrant]) [data-icon-button]:not([aria-pressed="true"]) {');
->toContain('[data-toolbar]:not([data-vibrant]) [data-md-icon-button]:not([aria-pressed="true"]) {');
});
it('offers M3\'s three contrast levels, marking the one in force', function () {
@@ -200,7 +200,7 @@ it('offers M3\'s three contrast levels, marking the one in force', function () {
->toContain('data-theme-toggle="contrast"')
->toContain('aria-label="Contrast"')
// A connected button group over native radios, not the deprecated segmented button (N-04).
->toContain('data-button-group="connected"')
->toContain('data-md-button-group="connected"')
->toContain('name="material-contrast"')
->toContain('value="standard"')
->toContain('value="medium"')
@@ -216,7 +216,7 @@ it('names a theme row for a screen reader and legends it on request', function (
->not->toContain('<legend')
->and((string) $this->blade('<x-theme-toggle mode="picker" label="Appearance" />'))
->toContain('aria-label="Appearance"')
->toContain('<legend class="mb-2 type-label-lg text-on-surface-variant">Appearance</legend>');
->toContain('<legend data-md-group-legend>Appearance</legend>');
});
it('switches the theme through the store in three shapes', function () {
+116 -63
View File
@@ -1,92 +1,145 @@
<?php
it('is M3\'s small badge without a value', function () {
expect((string) $this->blade('<x-badge />'))
->toContain('size-1.5 rounded-corner-full')
->toContain('bg-error text-on-error')
->toContain('aria-hidden="true"');
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
/**
* The attributes of the rendered badge, by name.
*
* @return array<string, string>
*/
function badgeAttributes(string $blade): array
{
preg_match('/<span\b([^>]*)>/', (string) test()->blade($blade), $tag);
preg_match_all('/([\w:-]+)="([^"]*)"/', $tag[1] ?? '', $pairs, PREG_SET_ORDER);
return collect($pairs)->mapWithKeys(fn (array $pair): array => [$pair[1] => $pair[2]])->all();
}
it('is M3\'s small badge without a value, hidden from screen readers', function () {
expect(badgeAttributes('<x-badge />'))->toBe([
'data-md-badge' => 'data-md-badge',
'data-md-dot' => 'data-md-dot',
'data-md-color' => 'error',
'aria-hidden' => 'true',
])
->and(ComponentStylesheet::read('badge')->declarations('[data-md-badge][data-md-dot]'))->toBe([
'inline-size' => '6px',
'block-size' => '6px',
'border-radius' => 'var(--md-sys-shape-corner-full)',
]);
});
it('is M3\'s large badge with a count, capped by max', function () {
expect((string) $this->blade('<x-badge value="4" />'))->toContain('h-4 min-w-4')->toContain('>4</span>')
$css = ComponentStylesheet::read('badge');
expect((string) $this->blade('<x-badge value="4" />'))->toContain('>4</span>')->not->toContain('data-md-dot')->not->toContain('data-md-variant')
->and((string) $this->blade('<x-badge value="1204" max="999" />'))->toContain('>999+</span>')
->and((string) $this->blade('<x-badge value="12" max="999" color="primary" />'))->toContain('>12</span>')->toContain('bg-primary text-on-primary');
->and((string) $this->blade('<x-badge value="12" max="999" color="primary" />'))->toContain('>12</span>')->toContain('data-md-color="primary"')
->and($css->declarations('[data-md-badge]:not([data-md-dot], [data-md-variant])'))->toMatchArray([
'min-inline-size' => '16px',
'block-size' => '16px',
'border-radius' => 'var(--md-sys-shape-corner-full)',
'padding-inline' => 'var(--md-sys-measurement-space50)',
'font' => 'var(--md-sys-typescale-label-sm)',
'font-variant-numeric' => 'tabular-nums',
]);
});
it('pins itself to the corner of an icon when floating', function () {
expect((string) $this->blade('<x-badge floating />'))->toContain('absolute top-0 end-0')
->and((string) $this->blade('<x-badge value="3" floating label="3 new messages" />'))
->toContain('absolute -top-0.5')
->toContain('aria-label="3 new messages"')
->not->toContain('aria-hidden');
$css = ComponentStylesheet::read('badge');
expect((string) $this->blade('<x-badge floating />'))->toContain('data-md-floating')
->and(badgeAttributes('<x-badge value="3" floating label="3 new messages" />'))
->toMatchArray(['data-md-floating' => 'data-md-floating', 'aria-label' => '3 new messages'])
->not->toHaveKey('aria-hidden')
->and($css->declarations('[data-md-badge][data-md-floating]'))->toBe([
'position' => 'absolute',
'inset-block-start' => 'calc(-1 * var(--md-sys-measurement-space25))',
'inset-inline-start' => 'calc(100% - 12px)',
])
->and($css->declarations('[data-md-badge][data-md-floating][data-md-dot]'))->toBe(['inset-block-start' => '0', 'inset-inline' => 'auto 0']);
});
it('draws a status label in a container or an outline', function () {
expect((string) $this->blade('<x-badge value="Active" tone="success" tonal />'))
->toContain('h-6 gap-1 rounded-corner-sm px-2 type-label-md')
->toContain('bg-success-container text-on-success-container')
->not->toContain('aria-hidden')
->and((string) $this->blade('<x-badge value="Pro" outline />'))
->toContain('border border-outline text-on-surface-variant')
->not->toContain('bg-error');
it('draws a status label in a container or an outline, spoken like any label', function () {
$css = ComponentStylesheet::read('badge');
expect(badgeAttributes('<x-badge value="Active" tone="success" tonal />'))
->toBe(['data-md-badge' => 'data-md-badge', 'data-md-variant' => 'tonal', 'data-md-color' => 'success'])
->and(badgeAttributes('<x-badge value="Pro" outline />'))
->toBe(['data-md-badge' => 'data-md-badge', 'data-md-variant' => 'outline', 'data-md-color' => 'error'])
->and($css->declarations('[data-md-badge][data-md-variant]'))->toMatchArray([
'gap' => 'var(--md-sys-measurement-space50)',
'block-size' => '24px',
'border-radius' => 'var(--md-sys-shape-corner-sm)',
'padding-inline' => 'var(--md-sys-measurement-space100)',
'font' => 'var(--md-sys-typescale-label-md)',
])
->and($css->declarations("[data-md-badge]:not([data-md-color='plain'])[data-md-variant='tonal']"))->toBe([
'background-color' => 'var(--md-badge-container)',
'color' => 'var(--md-badge-on-container)',
])
// The outline role, not outline-variant: a badge needs 3:1 against what is behind it.
->and($css->declarations("[data-md-badge]:not([data-md-color='plain'])[data-md-variant='outline']"))->toBe([
'border-color' => 'var(--md-sys-color-outline)',
'background-color' => 'transparent',
'color' => 'var(--md-sys-color-on-surface-variant)',
])
->and($css->declarations("[data-md-badge][data-md-variant='outline']"))->toBe(['border' => '1px solid']);
});
it('resolves solid over tonal, and either over outline', function () {
expect(badgeAttributes('<x-badge value="Built in" solid tonal outline color="primary" />'))->toMatchArray(['data-md-variant' => 'solid', 'data-md-color' => 'primary'])
->and(badgeAttributes('<x-badge value="Built in" tonal outline />'))->toMatchArray(['data-md-variant' => 'tonal'])
->and(badgeAttributes('<x-badge solid />'))->toMatchArray(['data-md-dot' => 'data-md-dot'])->not->toHaveKey('data-md-variant')
->and((string) $this->blade('<x-badge value="Built in" solid color="primary" />'))->toContain('>Built in<')->not->toContain('aria-hidden');
});
it('renders its slot as HTML, and is a dot while the slot holds nothing but comments', function () {
$html = (string) $this->blade('<x-badge tonal><x-icon name="bolt" class="size-3" /> Pro</x-badge>');
$html = (string) $this->blade('<x-badge tonal><x-icon name="bolt" size="12" /> Pro</x-badge>');
expect($html)
->toContain('h-6 gap-1 rounded-corner-sm')
->toContain('data-md-variant="tonal"')
->toContain('<svg')
->toContain(' Pro</span>')
->not->toContain('&lt;svg')
->and((string) $this->blade('<x-badge value="<b>4</b>" />'))->toContain('&lt;b&gt;4&lt;/b&gt;')
->and((string) $this->blade("<x-badge tonal>\n <!-- nothing yet -->\n</x-badge>"))->toContain('size-1.5 rounded-corner-full')
->and((string) $this->blade("<x-badge tonal>\n <!-- nothing yet -->\n</x-badge>"))->toContain('data-md-dot')
->and((string) $this->blade('<x-badge max="99">120</x-badge>'))->toContain('>99+</span>');
});
it('draws neutral ink on every variant', function () {
expect((string) $this->blade('<x-badge color="neutral" />'))->toContain('size-1.5 rounded-corner-full bg-on-surface-variant text-surface')
->and((string) $this->blade('<x-badge value="7" color="neutral" />'))->toContain('tabular-nums bg-on-surface-variant text-surface')
->and((string) $this->blade('<x-badge value="Draft" tone="neutral" tonal />'))->toContain('type-label-md bg-surface-container-high text-on-surface-variant')
->and((string) $this->blade('<x-badge value="Draft" color="neutral" outline />'))->toContain('type-label-md border border-outline text-on-surface-variant');
});
it('leaves a plain badge to the caller\'s colour classes', function (string $badge, string $shape) {
$html = (string) $this->blade($badge);
preg_match('/class="([^"]*)"/', $html, $class);
expect($class[1])
->toContain($shape)
->toEndWith('bg-tertiary-container text-on-tertiary-container')
->and(preg_replace('/bg-tertiary-container text-on-tertiary-container$/', '', $class[1]))->not->toMatch('/(^|\s)(bg|text|border)-/');
it('paints each colour from its pair of roles, and neutral without a hue', function (string $color, array $roles) {
expect(ComponentStylesheet::read('badge')->declarations("[data-md-badge][data-md-color='{$color}']"))->toBe([
'--md-badge-color' => "var(--md-sys-color-{$roles[0]})",
'--md-badge-on-color' => "var(--md-sys-color-{$roles[1]})",
'--md-badge-container' => "var(--md-sys-color-{$roles[2]})",
'--md-badge-on-container' => "var(--md-sys-color-{$roles[3]})",
]);
})->with([
'dot' => ['<x-badge color="plain" class="bg-tertiary-container text-on-tertiary-container" />', 'size-1.5 rounded-corner-full'],
'count' => ['<x-badge value="3" color="plain" class="bg-tertiary-container text-on-tertiary-container" />', 'h-4 min-w-4 rounded-corner-full px-1 type-label-sm tabular-nums'],
'tonal' => ['<x-badge value="Run" color="plain" tonal class="bg-tertiary-container text-on-tertiary-container" />', 'h-6 gap-1 rounded-corner-sm px-2 type-label-md'],
'outline' => ['<x-badge value="Run" color="plain" outline class="bg-tertiary-container text-on-tertiary-container" />', 'h-6 gap-1 rounded-corner-sm px-2 type-label-md border'],
'primary' => ['primary', ['primary', 'on-primary', 'primary-container', 'on-primary-container']],
'secondary' => ['secondary', ['secondary', 'on-secondary', 'secondary-container', 'on-secondary-container']],
'tertiary' => ['tertiary', ['tertiary', 'on-tertiary', 'tertiary-container', 'on-tertiary-container']],
'success' => ['success', ['success', 'on-success', 'success-container', 'on-success-container']],
'warning' => ['warning', ['warning', 'on-warning', 'warning-container', 'on-warning-container']],
'info' => ['info', ['info', 'on-info', 'info-container', 'on-info-container']],
'neutral' => ['neutral', ['on-surface-variant', 'surface', 'surface-container-high', 'on-surface-variant']],
]);
it('keeps its default colours, and falls back to error on a colour it does not know', function () {
expect((string) $this->blade('<x-badge value="4" />'))
->toContain('class="inline-flex shrink-0 items-center justify-center whitespace-nowrap h-4 min-w-4 rounded-corner-full px-1 type-label-sm tabular-nums bg-error text-on-error"')
->and((string) $this->blade('<x-badge value="Active" tonal />'))
->toContain('class="inline-flex shrink-0 items-center justify-center whitespace-nowrap h-6 gap-1 rounded-corner-sm px-2 type-label-md bg-error-container text-on-error-container"')
->and((string) $this->blade('<x-badge value="Pro" outline color="success" />'))
->toContain('class="inline-flex shrink-0 items-center justify-center whitespace-nowrap h-6 gap-1 rounded-corner-sm px-2 type-label-md border border-outline text-on-surface-variant"')
->and((string) $this->blade('<x-badge value="3" color="sport-run" />'))->toContain('bg-error text-on-error');
it('is error by default, and falls back to error on a colour it does not know', function () {
$css = ComponentStylesheet::read('badge');
expect($css->declarations('[data-md-badge]'))->toMatchArray([
'--md-badge-color' => 'var(--md-sys-color-error)',
'--md-badge-on-color' => 'var(--md-sys-color-on-error)',
])
->and($css->declarations("[data-md-badge]:not([data-md-color='plain'])"))->toBe([
'background-color' => 'var(--md-badge-color)',
'color' => 'var(--md-badge-on-color)',
])
->and(badgeAttributes('<x-badge value="3" color="sport-run" />'))->toMatchArray(['data-md-color' => 'error']);
});
it('draws a solid status label in the colour itself, spoken like any label', function () {
$html = (string) $this->blade('<x-badge value="Built in" solid color="primary" />');
expect($html)
->toContain('bg-primary text-on-primary')
->toContain('h-6 gap-1 rounded-corner-sm px-2 type-label-md')
->not->toContain('aria-hidden')
->toContain('>Built in<')
->and((string) $this->blade('<x-badge value="Draft" solid color="neutral" />'))
->toContain('bg-on-surface-variant text-surface')
->and((string) $this->blade('<x-badge solid />'))
->toContain('size-1.5');
it('leaves a plain badge, and every colour, to the caller\'s CSS', function () {
// `plain` matches none of the colour rules; a caller's class lands on the root untouched.
expect(badgeAttributes('<x-badge value="Run" color="plain" tonal class="bg-tertiary-container text-on-tertiary-container" />'))
->toMatchArray(['data-md-color' => 'plain', 'data-md-variant' => 'tonal', 'class' => 'bg-tertiary-container text-on-tertiary-container']);
});
+60 -115
View File
@@ -2,46 +2,73 @@
use Livewire\Component;
use Livewire\Livewire;
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
it('groups buttons with the spacing of their size', function () {
expect((string) $this->blade('<x-button-group label="Views" size="md"><x-button label="Day" /></x-button-group>'))
->toContain('role="group"')
->toContain('aria-label="Views"')
->toContain('data-button-group="standard"')
->toContain('data-size="md"')
->toContain('gap-2')
->and((string) $this->blade('<x-button-group><x-button label="Day" /></x-button-group>'))
->toContain('gap-3');
it('groups buttons with the spacing of their size', function (string $size, string $gap) {
expect((string) $this->blade("<x-button-group label=\"Views\" size=\"{$size}\"><x-button label=\"Day\" /></x-button-group>"))
->toMatch("/<div\\s+role=\"group\"\\s+aria-label=\"Views\"\\s+data-md-button-group=\"standard\"\\s+data-md-size=\"{$size}\"\\s+data-md-shape=\"round\"/")
->not->toContain('class=')
->and(ComponentStylesheet::read('button-group')->declarations(in_array($size, ['xs', 'sm'], true)
? "[data-md-button-group='standard'][data-md-size='{$size}']"
: "[data-md-button-group='standard']"))->toBe(['gap' => $gap]);
})->with([
'xs' => ['xs', '18px'],
'sm' => ['sm', '12px'],
'md' => ['md', 'var(--md-sys-measurement-space100)'],
'lg' => ['lg', 'var(--md-sys-measurement-space100)'],
'xl' => ['xl', 'var(--md-sys-measurement-space100)'],
]);
it('connects buttons 2px apart, with M3\'s inner corners', function () {
$css = ComponentStylesheet::read('button-group');
expect((string) $this->blade('<x-button-group connected><x-button label="Day" /></x-button-group>'))->toContain('data-md-button-group="connected"')
->and($css->declarations("[data-md-button-group='connected']"))->toBe(['gap' => 'var(--md-sys-measurement-space25)'])
->and($css->declarations("[data-md-button-group='connected'] > *"))->toMatchArray([
'--md-button-group-corner' => 'var(--md-button-group-inner)',
'border-start-start-radius' => 'var(--md-button-group-corner)',
])
->and($css->declarations("[data-md-button-group='connected'] > :active"))->toBe(['--md-button-group-corner' => 'var(--md-button-group-inner-pressed)'])
->and($css->declarations("[data-md-button-group='connected'] > :first-child"))->toBe([
'border-start-start-radius' => 'var(--md-button-group-outer)',
'border-end-start-radius' => 'var(--md-button-group-outer)',
])
// Half the height, never 9999px, which would scale the small inner corners away.
->and($css->declarations("[data-md-button-group][data-md-size='xl']"))->toMatchArray(['--md-button-group-full' => '68px', '--md-button-group-inner' => 'var(--md-sys-shape-corner-lg-increased)']);
});
it('connects buttons 2px apart', function () {
expect((string) $this->blade('<x-button-group connected><x-button label="Day" /></x-button-group>'))
->toContain('data-button-group="connected"')
->toContain('gap-0.5');
});
it('squares a group, and a choice drawn as one', function () {
it('squares a group', function () {
// M3 lists "Default shape | Round, square" as a button-group configuration; the shape covers
// every button in the group, so it need not be written on each one.
$css = ComponentStylesheet::read('button-group');
expect((string) $this->blade('<x-button-group shape="square"><x-button label="Day" /></x-button-group>'))
->toContain('data-shape="square"')
->toContain('data-md-shape="square"')
->and((string) $this->blade('<x-button-group connected shape="square"><x-button label="Day" /></x-button-group>'))
->toContain('data-button-group="connected"')
->toContain('data-shape="square"')
->and((string) $this->blade('<x-button-group><x-button label="Day" /></x-button-group>'))
->toContain('data-shape="round"')
->and((string) $this->blade('<x-group shape="square" name="x" :options="[[\'id\' => \'a\', \'name\' => \'A\']]" />'))
->toContain('data-shape="square"')
->and((string) $this->blade('<x-group name="x" :options="[[\'id\' => \'a\', \'name\' => \'A\']]" />'))
->toContain('data-shape="round"');
->toContain('data-md-button-group="connected"')
->toContain('data-md-shape="square"')
->and((string) $this->blade('<x-button-group shape="oval"><x-button label="Day" /></x-button-group>'))
->toContain('data-md-shape="round"')
->and($css->declarations("[data-md-button-group='standard'][data-md-shape='square'] > *"))->toBe(['border-radius' => 'var(--md-button-group-square)'])
->and($css->declarations("[data-md-button-group='standard'][data-md-shape='square'] > [aria-pressed='true']"))->toBe(['border-radius' => 'var(--md-button-group-full)']);
});
it('widens a pressed label button while its neighbours give way', function () {
$css = ComponentStylesheet::read('button-group');
expect($css->declarations("[data-md-button-group='standard'] > :not([data-md-icon-button]):active:not(:disabled, [aria-disabled='true'])"))
->toBe(['padding-inline' => 'calc(var(--md-button-group-pad) + var(--md-button-group-grow))'])
->and($css->declarations("[data-md-button-group='standard'] > :not([data-md-icon-button]):active:not(:disabled, [aria-disabled='true']) + :not([data-md-icon-button])"))
->toBe(['padding-inline-start' => 'calc(var(--md-button-group-pad) - var(--md-button-group-grow))'])
->and($css->declarations("[data-md-button-group][data-md-size='lg']"))->toMatchArray(['--md-button-group-pad' => 'var(--md-sys-measurement-space600)', '--md-button-group-grow' => '16px']);
});
it('takes over aria-pressed for a group that carries a selection', function () {
$html = (string) $this->blade('<x-button-group connected selection="single" required label="View"><x-button label="Day" value="day" :selected="true" /></x-button-group>');
expect($html)
->toContain('data-selection="single"')
->toContain('data-selection-required')
->toContain('data-md-selection="single"')
->toContain('data-md-selection-required')
->toContain('multiple: false')
->toContain('required: true')
->toContain('value: null')
@@ -53,7 +80,7 @@ it('takes over aria-pressed for a group that carries a selection', function () {
->toContain('required: false')
->toContain('value: []')
->and((string) $this->blade('<x-button-group connected><x-button label="Day" /></x-button-group>'))
->not->toContain('data-selection')
->not->toContain('data-md-selection')
->not->toContain('press($event)');
});
@@ -78,99 +105,17 @@ it('entangles a selection group with the property it binds, and keeps wire:model
$html = Livewire::test($component)->assertSet('view', 'week')->html();
expect($html)
->toContain('data-selection="single"')
->toContain('data-md-selection="single"')
->toMatch('/value: window\.Livewire\.find\(/')
->and(substr_count($html, 'wire:model.live="view"'))->toBe(0);
});
it('never wraps a group onto a second line', function () {
expect((string) $this->blade('<x-button-group><x-button label="Day" /></x-button-group>'))
->not->toContain('flex-wrap');
expect(ComponentStylesheet::read('button-group')->declarations('[data-md-button-group]'))->toMatchArray(['display' => 'inline-flex'])
->not->toHaveKey('flex-wrap');
});
it('marks icon buttons, which keep their width when a group is pressed', function () {
expect((string) $this->blade('<x-button icon="format_bold" aria-label="Bold" />'))->toContain('data-icon-button')
->and((string) $this->blade('<x-button label="Bold" />'))->not->toContain('data-icon-button');
});
it('draws a choice as connected radios', function () {
$html = (string) $this->blade(<<<'BLADE'
<x-group label="Theme" name="theme" x-model="theme" :options="[
['id' => 'light', 'name' => 'Light', 'icon' => 'light_mode'],
['id' => 'dark', 'name' => 'Dark', 'disabled' => true],
]" />
BLADE);
expect($html)
->toContain('<legend class="mb-2 type-label-lg text-on-surface-variant">Theme</legend>')
->toContain('data-button-group="connected"')
->toContain('type="radio"')
->toContain('name="theme"')
->toContain('x-model="theme"')
->toContain('value="light"')
->toContain('has-checked:bg-secondary has-checked:text-on-secondary')
->toContain('disabled')
->and(substr_count($html, '<svg'))->toBe(1);
});
it('keeps a 48px target and a 48px minimum width on the smallest connected segments', function () {
$options = [['id' => 'a', 'name' => 'A']];
expect((string) $this->blade('<x-group size="sm" name="x" :$options />', ['options' => $options]))
->toContain('touch-target min-w-12')
->and((string) $this->blade('<x-group size="md" name="x" :$options />', ['options' => $options]))
->not->toContain('touch-target')
->toContain('min-w-0');
});
it('draws several choices as checkboxes', function () {
expect((string) $this->blade('<x-group name="days" multiple variant="outlined" :options="[[\'id\' => \'mon\', \'name\' => \'Mon\']]" />'))
->toContain('type="checkbox"')
->toContain('name="days[]"')
->toContain('has-checked:bg-inverse-surface');
});
it('binds to a Livewire property and shows its validation message', function () {
$component = new class extends Component
{
public string $theme = 'dark';
public function save(): void
{
$this->validate(['theme' => 'in:light'], ['theme.in' => 'Pick light.']);
}
public function render(): string
{
return <<<'BLADE'
<div>
<x-group wire:model="theme" hint="How it looks" :options="[['id' => 'light', 'name' => 'Light'], ['id' => 'dark', 'name' => 'Dark']]" />
</div>
BLADE;
}
};
Livewire::test($component)
->assertSeeHtml('wire:model="theme"')
->assertSee('How it looks')
->set('theme', 'light')
->assertSet('theme', 'light')
->set('theme', 'dark')
->call('save')
->assertSee('Pick light.')
->assertDontSee('How it looks');
});
it('adds hint-class to the hint, which a validation message still replaces', function () {
$options = [['id' => 'flat', 'name' => 'Flat'], ['id' => 'hilly', 'name' => 'Hilly']];
expect((string) $this->blade('<x-group wire:model="terrain" hint="No elevation data here" hint-class="text-warning" :$options />', ['options' => $options]))
->toContain('<p class="mt-1 type-body-sm [:where(&amp;)]:text-on-surface-variant text-warning">No elevation data here</p>')
->and((string) $this->blade('<x-group wire:model="terrain" hint="No elevation data here" :$options />', ['options' => $options]))
->toContain('<p class="mt-1 type-body-sm text-on-surface-variant">No elevation data here</p>');
expect((string) $this->withViewErrors(['terrain' => 'Pick a terrain.'])->blade('<x-group wire:model="terrain" hint="No elevation data here" hint-class="text-warning" :$options />', ['options' => $options]))
->toContain('<p class="mt-1 type-body-sm text-error">Pick a terrain.</p>')
->not->toContain('No elevation data here')
->not->toContain('text-warning');
expect((string) $this->blade('<x-button icon="format_bold" aria-label="Bold" />'))->toContain('data-md-icon-button')
->and((string) $this->blade('<x-button label="Bold" />'))->not->toContain('data-md-icon-button');
});
+177 -73
View File
@@ -1,70 +1,137 @@
<?php
/**
* The classes on the rendered button element.
*/
function buttonClasses(string $blade): string
{
preg_match('/<(?:button|a)\b[^>]*\bclass="([^"]*)"/', (string) test()->blade($blade), $matches);
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
return $matches[1] ?? '';
/**
* The attributes of the rendered button or link element, by name.
*
* @return array<string, string>
*/
function buttonAttributes(string $blade): array
{
preg_match('/<(?:button|a)\b([^>]*)>/', (string) test()->blade($blade), $tag);
preg_match_all('/([\w:.-]+)(?:="([^"]*)")?/', $tag[1] ?? '', $pairs, PREG_SET_ORDER);
return collect($pairs)->mapWithKeys(fn (array $pair): array => [$pair[1] => $pair[2] ?? ''])->all();
}
it('is a text button in the primary colour by default', function () {
expect(buttonClasses('<x-button label="Cancel" />'))
->toContain('text-primary')
->not->toContain('bg-primary');
function buttonCss(): ComponentStylesheet
{
return ComponentStylesheet::read('button');
}
it('is a text button in the primary colour by default, drawn by its stylesheet', function () {
expect(buttonAttributes('<x-button label="Cancel" />'))->toBe([
'data-md-button' => 'data-md-button',
'data-md-variant' => 'text',
'data-md-color' => 'primary',
'data-md-size' => 'sm',
'data-md-shape' => 'round',
'type' => 'button',
])
->and(buttonCss()->declarations('[data-md-button]'))->toMatchArray([
'--md-button-container' => 'transparent',
'--md-button-label' => 'var(--md-button-color)',
'--md-button-color' => 'var(--md-sys-color-primary)',
'background-color' => 'var(--md-button-container)',
'color' => 'var(--md-button-label)',
]);
});
it('draws each M3 variant', function (string $variant, string $classes) {
expect(buttonClasses("<x-button label=\"Go\" variant=\"{$variant}\" />"))->toContain($classes);
it('draws each M3 variant', function (string $variant, array $declarations) {
expect(buttonAttributes("<x-button label=\"Go\" variant=\"{$variant}\" />"))->toMatchArray(['data-md-variant' => $variant])
->and(buttonCss()->declarations("[data-md-button][data-md-variant='{$variant}']"))->toMatchArray($declarations);
})->with([
'filled' => ['filled', 'bg-primary text-on-primary'],
'tonal' => ['tonal', 'bg-secondary-container text-on-secondary-container'],
'outlined' => ['outlined', 'border-outline-variant text-on-surface-variant'],
'elevated' => ['elevated', 'bg-surface-container-low text-primary'],
'text' => ['text', 'text-primary'],
'filled' => ['filled', ['--md-button-container' => 'var(--md-button-color)', '--md-button-label' => 'var(--md-button-on-color)']],
'tonal' => ['tonal', ['--md-button-container' => 'var(--md-button-tone)', '--md-button-label' => 'var(--md-button-on-tone)']],
'outlined' => ['outlined', ['--md-button-label' => 'var(--md-button-quiet)', '--md-button-outline' => 'var(--md-sys-color-outline-variant)', 'border' => 'var(--md-button-outline-width) solid var(--md-button-outline)']],
'elevated' => ['elevated', ['--md-button-container' => 'var(--md-sys-color-surface-container-low)', '--md-button-elevation' => 'var(--md-sys-elevation-1)']],
]);
it('draws a variant in another colour role', function () {
expect(buttonClasses('<x-button label="Go" variant="filled" color="tertiary" />'))->toContain('bg-tertiary text-on-tertiary')
->and(buttonClasses('<x-button label="Go" variant="tonal" color="error" />'))->toContain('bg-error-container text-on-error-container')
->and(buttonClasses('<x-button label="Go" variant="outlined" tone="success" />'))->toContain('text-success');
it('draws primary\'s tonal button in secondary-container and its quiet ink in on-surface-variant', function () {
expect(buttonCss()->declarations('[data-md-button]'))->toMatchArray([
'--md-button-tone' => 'var(--md-sys-color-secondary-container)',
'--md-button-on-tone' => 'var(--md-sys-color-on-secondary-container)',
'--md-button-tone-selected' => 'var(--md-sys-color-secondary)',
'--md-button-quiet' => 'var(--md-sys-color-on-surface-variant)',
])
->and(buttonCss()->declarations("[data-md-button]:not([data-md-color='primary'])"))->toBe([
'--md-button-tone-selected' => 'var(--md-button-color)',
'--md-button-on-tone-selected' => 'var(--md-button-on-color)',
'--md-button-quiet' => 'var(--md-button-color)',
]);
});
it('draws a variant in another colour role', function (string $color) {
expect(buttonCss()->declarations("[data-md-button][data-md-color='{$color}']"))->toBe([
'--md-button-color' => "var(--md-sys-color-{$color})",
'--md-button-on-color' => "var(--md-sys-color-on-{$color})",
'--md-button-tone' => "var(--md-sys-color-{$color}-container)",
'--md-button-on-tone' => "var(--md-sys-color-on-{$color}-container)",
]);
})->with(['secondary', 'tertiary', 'error', 'success', 'warning', 'info']);
it('keeps the maryUI and ReStride shorthands', function () {
expect(buttonClasses('<x-button label="Save" primary />'))->toContain('bg-primary text-on-primary')
->and(buttonClasses('<x-button label="Delete" danger />'))->toContain('bg-error text-on-error')
->and(buttonClasses('<x-button label="Take down" caution />'))->toContain('bg-warning text-on-warning');
expect(buttonAttributes('<x-button label="Save" primary />'))->toMatchArray(['data-md-variant' => 'filled', 'data-md-color' => 'primary'])
->and(buttonAttributes('<x-button label="Delete" danger />'))->toMatchArray(['data-md-variant' => 'filled', 'data-md-color' => 'error'])
->and(buttonAttributes('<x-button label="Take down" caution />'))->toMatchArray(['data-md-variant' => 'filled', 'data-md-color' => 'warning'])
->and(buttonAttributes('<x-button label="Go" variant="outlined" tone="success" />'))->toMatchArray(['data-md-color' => 'success']);
});
it('falls back to the defaults for values it does not know', function () {
expect(buttonClasses('<x-button label="Go" variant="glass" color="purple" size="huge" />'))
->toContain('text-primary')
->toContain('h-10 gap-2 px-4 type-label-lg');
expect(buttonAttributes('<x-button label="Go" variant="glass" color="purple" size="huge" shape="blob" />'))
->toMatchArray(['data-md-variant' => 'text', 'data-md-color' => 'primary', 'data-md-size' => 'sm', 'data-md-shape' => 'round']);
});
it('sizes a label button on Expressive\'s scale', function (string $size, string $classes, string $icon) {
it('sizes a label button on Expressive\'s scale', function (string $size, array $geometry, string $type, int $icon) {
$html = (string) $this->blade("<x-button label=\"Upload\" icon=\"upload\" size=\"{$size}\" />");
expect($html)->toContain($classes)->toContain($icon);
expect($html)->toContain("data-md-size=\"{$size}\"")->toContain("--md-icon-size: {$icon}px")
->and(buttonCss()->declarations("[data-md-button][data-md-size='{$size}']"))->toMatchArray($geometry)
->and(buttonCss()->declarations(in_array($size, ['xs', 'sm'], true)
? "[data-md-button]:not([data-md-icon-button]):is([data-md-size='xs'], [data-md-size='sm'])"
: "[data-md-button]:not([data-md-icon-button])[data-md-size='{$size}']"))->toMatchArray(['font' => "var(--md-sys-typescale-{$type})"]);
})->with([
'xs' => ['xs', 'h-8 gap-2 px-4 type-label-lg', 'size-5'],
'sm' => ['sm', 'h-10 gap-2 px-4 type-label-lg', 'size-5'],
'md' => ['md', 'h-14 gap-2 px-6 type-title-md', 'size-6'],
'lg' => ['lg', 'h-24 gap-3 px-12 type-headline-sm', 'size-8'],
'xl' => ['xl', 'h-34 gap-4 px-16 type-headline-lg', 'size-10'],
'xs' => ['xs', ['--md-button-height' => '32px', '--md-button-padding' => 'var(--md-sys-measurement-space200)', '--md-button-gap' => 'var(--md-sys-measurement-space100)', '--md-button-icon' => '20px'], 'label-lg', 20],
'sm' => ['sm', ['--md-button-height' => '40px', '--md-button-padding' => 'var(--md-sys-measurement-space200)', '--md-button-gap' => 'var(--md-sys-measurement-space100)', '--md-button-icon' => '20px'], 'label-lg', 20],
'md' => ['md', ['--md-button-height' => '56px', '--md-button-padding' => 'var(--md-sys-measurement-space300)', '--md-button-gap' => 'var(--md-sys-measurement-space100)', '--md-button-icon' => '24px'], 'title-md', 24],
'lg' => ['lg', ['--md-button-height' => '96px', '--md-button-padding' => 'var(--md-sys-measurement-space600)', '--md-button-gap' => '12px', '--md-button-icon' => '32px'], 'headline-sm', 32],
'xl' => ['xl', ['--md-button-height' => '136px', '--md-button-padding' => 'var(--md-sys-measurement-space800)', '--md-button-gap' => 'var(--md-sys-measurement-space200)', '--md-button-icon' => '40px'], 'headline-lg', 40],
]);
it('rounds by default, squares on request, and squares off further while pressed', function () {
expect(buttonClasses('<x-button label="Go" size="md" />'))->toContain('rounded-corner-full')->toContain('active:rounded-corner-md')
->and(buttonClasses('<x-button label="Go" size="md" shape="square" />'))->toContain('rounded-corner-lg')
->and(buttonClasses('<x-button label="Go" size="xl" shape="square" />'))->toContain('rounded-corner-xl')->toContain('active:rounded-corner-lg');
it('rounds by default, squares on request, and squares off further while pressed — without specificity', function () {
expect(buttonAttributes('<x-button label="Go" size="md" shape="square" />'))->toMatchArray(['data-md-shape' => 'square'])
->and(buttonCss()->declarations(':where([data-md-button])'))->toBe(['border-radius' => 'var(--md-sys-shape-corner-full)'])
->and(buttonCss()->declarations(":where([data-md-button]):where([data-md-shape='square'], [data-md-selected='true'])"))->toBe(['border-radius' => 'var(--md-button-square)'])
->and(buttonCss()->declarations(':where([data-md-button]):where(:active)'))->toBe(['border-radius' => 'var(--md-button-pressed)'])
->and(buttonCss()->declarations("[data-md-button][data-md-size='md']"))->toMatchArray(['--md-button-square' => 'var(--md-sys-shape-corner-lg)', '--md-button-pressed' => 'var(--md-sys-shape-corner-md)'])
->and(buttonCss()->declarations("[data-md-button][data-md-size='xl']"))->toMatchArray(['--md-button-square' => 'var(--md-sys-shape-corner-xl)', '--md-button-pressed' => 'var(--md-sys-shape-corner-lg)']);
});
it('reaches a 48px touch target below the medium size', function () {
expect(buttonClasses('<x-button label="Go" size="sm" />'))->toContain('touch-target')
->and(buttonClasses('<x-button label="Go" size="md" />'))->not->toContain('touch-target');
expect(buttonCss()->declarations("[data-md-button]:is([data-md-size='xs'], [data-md-size='sm'])::after"))->toMatchArray([
'content' => "''",
'min-width' => 'var(--md-sys-measurement-space600)',
'min-height' => 'var(--md-sys-measurement-space600)',
])
->and(buttonCss()->has("[data-md-button]:is([data-md-size='md'])::after"))->toBeFalse();
});
it('draws M3\'s state layer and focus ring on the button itself', function () {
$css = buttonCss();
expect($css->declarations('[data-md-button]::before'))->toMatchArray(['background-color' => 'currentColor', 'opacity' => '0', 'border-radius' => 'inherit'])
->and($css->declarations('[data-md-button]:hover::before', ['@media (hover: hover)']))->toBe(['opacity' => 'var(--md-sys-state-hover-state-layer-opacity)'])
->and($css->declarations('[data-md-button]:focus-visible::before'))->toBe(['opacity' => 'var(--md-sys-state-focus-state-layer-opacity)'])
->and($css->declarations('[data-md-button]:active::before'))->toBe(['opacity' => 'var(--md-sys-state-pressed-state-layer-opacity)'])
->and($css->declarations('[data-md-button]:focus-visible'))->toBe(['outline' => '3px solid var(--md-sys-color-secondary)', 'outline-offset' => '2px']);
});
it('moves shape on the spatial spring and colour on the effects spring', function () {
$declarations = buttonCss()->declarations('[data-md-button]');
expect($declarations['transition-property'])->toBe('border-radius, padding, margin, bottom, background-color, color, box-shadow')
->and($declarations['transition-timing-function'])->toBe('var(--md-sys-motion-spatial-fast), var(--md-sys-motion-spatial-fast), var(--md-sys-motion-spatial-fast), var(--md-sys-motion-spatial-fast), var(--md-sys-motion-effects-fast), var(--md-sys-motion-effects-fast), var(--md-sys-motion-effects-fast)');
});
it('fills a default icon button\'s glyph, and draws a 20px one from the 20px cut', function () {
@@ -87,31 +154,39 @@ it('fills a default icon button\'s glyph, and draws a 20px one from the 20px cut
it('is an icon button named by its tooltip when it has no label', function () {
$html = (string) $this->blade('<x-button icon="close" tooltip="Close menu" />');
expect($html)
->toContain('aria-label="Close menu"')
->toContain('size-10')
->toContain('text-on-surface-variant')
->toContain('popover="manual"')
->toContain('aria-hidden="true"');
expect(buttonAttributes('<x-button icon="close" tooltip="Close menu" />'))
->toMatchArray(['data-md-icon-button' => 'data-md-icon-button', 'data-md-width' => 'default', 'aria-label' => 'Close menu'])
->and($html)->toContain('--md-icon-size: 24px')->toContain('popover="manual"')->toContain('aria-hidden="true"')
// M3's standard icon button: on-surface-variant, unless selected.
->and(buttonCss()->declarations("[data-md-button][data-md-variant='text'][data-md-icon-button]:not([data-md-selected='true'])"))->toBe(['--md-button-label' => 'var(--md-button-quiet)']);
});
it('sizes an icon button by width', function () {
expect(buttonClasses('<x-button icon="share" label="" width="wide" aria-label="Share" />'))->toContain('h-10 w-13')
->and(buttonClasses('<x-button icon="share" size="xl" width="narrow" aria-label="Share" />'))->toContain('h-34 w-26');
expect(buttonAttributes('<x-button icon="share" label="" width="wide" aria-label="Share" />'))->toMatchArray(['data-md-width' => 'wide'])
->and(buttonAttributes('<x-button icon="share" size="xl" width="narrow" aria-label="Share" />'))->toMatchArray(['data-md-width' => 'narrow', 'data-md-size' => 'xl'])
->and(buttonAttributes('<x-button label="Share" width="wide" />'))->not->toHaveKey('data-md-width')
->and(buttonCss()->declarations("[data-md-button][data-md-size='sm']"))->toMatchArray(['--md-button-narrow' => '32px', '--md-button-default' => '40px', '--md-button-wide' => '52px'])
->and(buttonCss()->declarations("[data-md-button][data-md-size='xl']"))->toMatchArray(['--md-button-narrow' => '104px', '--md-button-default' => '136px', '--md-button-wide' => '184px'])
->and(buttonCss()->declarations("[data-md-button][data-md-icon-button][data-md-width='wide']"))->toBe(['--md-button-width' => 'var(--md-button-wide)']);
});
it('toggles with aria-pressed and M3\'s selected colours and shape', function () {
expect((string) $this->blade('<x-button label="Bold" variant="filled" :selected="true" />'))->toContain('aria-pressed="true"')
->and(buttonClasses('<x-button label="Bold" variant="filled" :selected="true" />'))->toContain('bg-primary')->toContain('rounded-corner-md')
->and(buttonClasses('<x-button label="Bold" variant="filled" :selected="false" />'))->toContain('bg-surface-container text-on-surface-variant')->toContain('rounded-corner-full')
->and(buttonClasses('<x-button label="Bold" variant="tonal" :selected="true" />'))->toContain('bg-secondary text-on-secondary')
->and(buttonClasses('<x-button label="Bold" variant="outlined" :selected="true" />'))->toContain('bg-inverse-surface text-inverse-on-surface');
$css = buttonCss();
expect(buttonAttributes('<x-button label="Bold" variant="filled" :selected="true" />'))->toMatchArray(['aria-pressed' => 'true', 'data-md-selected' => 'true'])
->and(buttonAttributes('<x-button label="Bold" variant="filled" :selected="false" />'))->toMatchArray(['aria-pressed' => 'false', 'data-md-selected' => 'false'])
->and(buttonAttributes('<x-button label="Bold" variant="filled" />'))->not->toHaveKey('data-md-selected')
->and($css->declarations("[data-md-button][data-md-variant='filled'][data-md-selected='false']"))->toBe(['--md-button-container' => 'var(--md-sys-color-surface-container)', '--md-button-label' => 'var(--md-sys-color-on-surface-variant)'])
->and($css->declarations("[data-md-button][data-md-variant='tonal'][data-md-selected='true']"))->toBe(['--md-button-container' => 'var(--md-button-tone-selected)', '--md-button-label' => 'var(--md-button-on-tone-selected)'])
->and($css->declarations("[data-md-button][data-md-variant='outlined'][data-md-selected='true']"))->toBe(['--md-button-container' => 'var(--md-sys-color-inverse-surface)', '--md-button-label' => 'var(--md-sys-color-inverse-on-surface)', '--md-button-outline' => 'transparent'])
// Text buttons are not toggles in M3: a selected one takes the tonal container.
->and($css->declarations("[data-md-button][data-md-variant='text']:not([data-md-icon-button])[data-md-selected='true']"))->toBe(['--md-button-container' => 'var(--md-button-tone)', '--md-button-label' => 'var(--md-button-on-tone)']);
});
it('squares a selected round icon button and rounds a selected square one', function () {
expect(buttonClasses('<x-button icon="favorite" aria-label="Like" variant="tonal" :selected="true" />'))->toContain('rounded-corner-md')
->and(buttonClasses('<x-button icon="favorite" aria-label="Like" variant="tonal" shape="square" :selected="true" />'))->toContain('rounded-corner-full')
->and((string) $this->blade('<x-button icon="favorite" aria-label="Like" :selected="true" />'))->toContain('text-primary');
expect(buttonCss()->declarations(":where([data-md-button]):where([data-md-icon-button][data-md-shape='square'][data-md-selected='true'])"))->toBe(['border-radius' => 'var(--md-sys-shape-corner-full)'])
->and(buttonAttributes('<x-button icon="favorite" aria-label="Like" variant="tonal" shape="square" :selected="true" />'))
->toMatchArray(['data-md-icon-button' => 'data-md-icon-button', 'data-md-shape' => 'square', 'data-md-selected' => 'true']);
});
it('navigates inside the app, and leaves it for an external link', function () {
@@ -128,21 +203,31 @@ it('navigates inside the app, and leaves it for an external link', function () {
});
it('disables a button, and a link as far as a link can be', function () {
$this->blade('<x-button label="Save" variant="filled" disabled />')
->assertSee('disabled="disabled"', false)
->assertSee('disabled:bg-on-surface/10', false);
$this->blade('<x-button label="Shares" link="/admin/shares" disabled />')
->assertSee('aria-disabled="true"', false)
->assertSee('tabindex="-1"', false);
expect(buttonAttributes('<x-button label="Save" variant="filled" disabled />'))->toMatchArray(['disabled' => 'disabled'])
->and(buttonAttributes('<x-button label="Shares" link="/admin/shares" disabled />'))->toMatchArray(['aria-disabled' => 'true', 'tabindex' => '-1'])
->and(buttonCss()->declarations("[data-md-button]:is(:disabled, [aria-disabled='true'])"))->toBe([
'box-shadow' => 'none',
'color' => 'color-mix(in srgb, var(--md-sys-color-on-surface) calc(var(--md-sys-state-disabled-content-opacity) * 100%), transparent)',
])
->and(buttonCss()->declarations("[data-md-button]:is([data-md-variant='filled'], [data-md-variant='tonal'], [data-md-variant='elevated'], [data-md-variant='outlined'][data-md-selected='true']):is(:disabled, [aria-disabled='true'])"))
->toBe(['background-color' => 'color-mix(in srgb, var(--md-sys-color-on-surface) 10%, transparent)'])
->and(buttonCss()->declarations("[data-md-button]:is(:disabled, [aria-disabled='true'])::before"))->toBe(['display' => 'none'])
->and(buttonCss()->declarations("[data-md-button][aria-disabled='true']"))->toBe(['pointer-events' => 'none']);
});
it('shows the loading indicator while its own action runs, in the button\'s own ink', function () {
$this->blade('<x-button label="Save" wire:click="save" spinner />')
->assertSee('wire:loading.attr="disabled"', false)
->assertSee('wire:target="save"', false)
->assertSee('size-5 text-current', false)
->assertDontSee('text-primary"', false);
$html = (string) $this->blade('<x-button label="Save" wire:click="save" spinner />');
expect($html)
->toContain('wire:loading.attr="disabled"')
->toContain('wire:target="save"')
->toMatch('/<span wire:loading.flex wire:target="save" data-md-button-spinner>\s*<span data-md-loading="data-md-loading" aria-hidden="true">/')
->toMatch('/<span data-md-button-icon\s+wire:loading.remove wire:target="save"\s*>|<span data-md-button-label/')
->and(buttonCss()->declarations('[data-md-button-spinner] > [data-md-loading]'))->toBe([
'inline-size' => 'var(--md-button-icon)',
'block-size' => 'var(--md-button-icon)',
'color' => 'currentColor',
]);
$this->blade('<x-button label="Save" wire:click="save" spinner="upload" />')
->assertSee('wire:target="upload"', false);
@@ -150,7 +235,9 @@ it('shows the loading indicator while its own action runs, in the button\'s own
it('hides a responsive label below expanded', function () {
$this->blade('<x-button label="New share" icon="add" responsive />')
->assertSee('<span class="max-expanded:hidden">New share</span>', false);
->assertSee('<span data-md-button-label data-md-responsive >New share</span>', false);
expect(buttonCss()->declarations('[data-md-button] > [data-md-responsive]', ['@media (width < 840px)']))->toBe(['display' => 'none']);
});
it('anchors its tooltip to itself', function () {
@@ -160,17 +247,27 @@ it('anchors its tooltip to itself', function () {
expect($anchor)->not->toBeEmpty()
->and($html)->toContain("position-anchor: {$anchor[1]}")
->toContain('[position-area:bottom]')
->toContain('data-md-side="bottom"')
->not->toContain('aria-label="Saves the draft"');
});
it('is a FAB on a compact window and a filled button from medium, in one element', function () {
$html = (string) $this->blade('<x-button label="New share" icon="add" fab />');
$fab = buttonCss()->declarations('[data-md-button][data-md-compact-fab]', ['@media (width < 600px)']);
expect(substr_count($html, '<button'))->toBe(1)
->and($html)->toContain('max-medium:fixed')->toContain('max-medium:bg-primary-container')->toContain('bg-primary text-on-primary')
->and(buttonAttributes('<x-button label="New share" icon="add" fab />'))->toMatchArray(['data-md-compact-fab' => 'data-md-compact-fab', 'data-md-variant' => 'filled'])
->and($fab)->toMatchArray([
'position' => 'fixed',
'inset-inline-end' => 'var(--md-sys-measurement-space200)',
'--md-button-height' => '56px',
'border-radius' => 'var(--md-sys-shape-corner-lg)',
'background-color' => 'var(--md-sys-color-primary-container)',
'color' => 'var(--md-sys-color-on-primary-container)',
'box-shadow' => 'var(--md-sys-elevation-3)',
])
// M3 puts a snackbar above a FAB, never over one: the host publishes its height.
->toContain('max-medium:bottom-[calc(var(--material-bottom-bar,0px)+var(--material-snackbar-height,0px)+1rem)]');
->and($fab['bottom'])->toBe('calc(var(--material-bottom-bar, 0px) + var(--material-snackbar-height, 0px) + var(--md-sys-measurement-space200))');
});
it('submits a form when asked', function () {
@@ -181,6 +278,13 @@ it('submits a form when asked', function () {
it('keeps aria-pressed off a selected link, which is not a toggle', function () {
expect((string) $this->blade('<x-button label="Plans" link="/plans" :selected="true" />'))
->not->toContain('aria-pressed')
->toContain('data-md-selected="true"')
->and((string) $this->blade('<x-button label="Bold" :selected="true" />'))
->toContain('aria-pressed="true"');
});
it('lands a caller\'s class and style on the button untouched', function () {
expect(buttonAttributes('<x-button label="Save" class="w-full" style="margin: 0" tooltip="Save" />'))
->toMatchArray(['class' => 'w-full'])
->and(buttonAttributes('<x-button label="Save" class="w-full" style="margin: 0" tooltip="Save" />')['style'])->toStartWith('anchor-name: --material-button-')->toEndWith('margin: 0;');
});
+86 -32
View File
@@ -1,20 +1,54 @@
<?php
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
/**
* The attributes of the rendered FAB, by name.
*
* @return array<string, string>
*/
function fabAttributes(string $blade): array
{
preg_match('/<(?:button|a)\b([^>]*)>/', (string) test()->blade($blade), $tag);
preg_match_all('/([\w:.-]+)(?:="([^"]*)")?/', $tag[1] ?? '', $pairs, PREG_SET_ORDER);
return collect($pairs)->mapWithKeys(fn (array $pair): array => [$pair[1] => $pair[2] ?? ''])->all();
}
it('draws a FAB in its container colour, named by its tooltip', function () {
expect((string) $this->blade('<x-fab icon="add" tooltip="New share" />'))
->toContain('size-14 rounded-corner-lg')
->toContain('bg-primary-container text-on-primary-container')
->toContain('shadow-elevation-3')
->toContain('aria-label="New share"')
->toContain('popover="manual"');
$css = ComponentStylesheet::read('fab');
expect(fabAttributes('<x-fab icon="add" tooltip="New share" />'))->toMatchArray([
'data-md-fab' => 'data-md-fab',
'data-md-size' => 'sm',
'data-md-color' => 'primary',
'data-md-variant' => 'container',
'type' => 'button',
'aria-label' => 'New share',
])
->not->toHaveKey('data-md-extended')
->and((string) $this->blade('<x-fab icon="add" tooltip="New share" />'))->toContain('popover="manual"')
->and($css->declarations('[data-md-fab]'))->toMatchArray([
'background-color' => 'var(--md-fab-container)',
'color' => 'var(--md-fab-on-container)',
'box-shadow' => 'var(--md-sys-elevation-3)',
'block-size' => 'var(--md-fab-size)',
'border-radius' => 'var(--md-fab-corner)',
])
->and($css->declarations('[data-md-fab]:hover', ['@media (hover: hover)']))->toBe(['box-shadow' => 'var(--md-sys-elevation-4)'])
->and($css->declarations('[data-md-fab]:not([data-md-extended])'))->toBe(['inline-size' => 'var(--md-fab-size)']);
});
it('sizes a FAB at 56, 80 and 96px', function (string $size, string $classes, string $icon) {
expect((string) $this->blade("<x-fab icon=\"add\" size=\"{$size}\" aria-label=\"Add\" />"))->toContain($classes)->toContain($icon);
it('sizes a FAB at 56, 80 and 96px', function (string $size, string $px, string $corner, int $icon) {
expect((string) $this->blade("<x-fab icon=\"add\" size=\"{$size}\" aria-label=\"Add\" />"))->toContain("data-md-size=\"{$size}\"")->toContain("--md-icon-size: {$icon}px")
->and(ComponentStylesheet::read('fab')->declarations("[data-md-fab][data-md-size='{$size}']"))->toMatchArray([
'--md-fab-size' => $px,
'--md-fab-corner' => "var(--md-sys-shape-corner-{$corner})",
]);
})->with([
'sm' => ['sm', 'size-14 rounded-corner-lg', 'size-6'],
'md' => ['md', 'size-20 rounded-corner-lg-increased', 'size-7'],
'lg' => ['lg', 'size-24 rounded-corner-xl', 'size-8'],
'sm' => ['sm', '56px', 'lg', 24],
'md' => ['md', '80px', 'lg-increased', 28],
'lg' => ['lg', '96px', 'xl', 32],
]);
it('fills the FAB\'s glyph, as M3 asks twice over', function () {
@@ -25,32 +59,53 @@ it('fills the FAB\'s glyph, as M3 asks twice over', function () {
->and((string) $this->blade('<x-fab-menu label="New" />'))->toContain($filled);
});
it('extends with a label', function () {
expect((string) $this->blade('<x-fab icon="upload" label="Upload" size="md" color="tertiary" variant="filled" />'))
->toContain('h-20 min-w-20 gap-4 px-[26px] rounded-corner-lg-increased type-title-lg')
->toContain('bg-tertiary text-on-tertiary')
->toContain('<span>Upload</span>')
->not->toContain('aria-label');
it('extends with a label, in the colour itself when filled', function () {
expect(fabAttributes('<x-fab icon="upload" label="Upload" size="md" color="tertiary" variant="filled" />'))
->toMatchArray(['data-md-size' => 'md', 'data-md-color' => 'tertiary', 'data-md-variant' => 'filled', 'data-md-extended' => 'data-md-extended'])
->not->toHaveKey('aria-label')
->and((string) $this->blade('<x-fab icon="upload" label="Upload" />'))->toContain('<span>Upload</span>')
->and(ComponentStylesheet::read('fab')->declarations("[data-md-fab][data-md-variant='filled']"))->toBe([
'background-color' => 'var(--md-fab-color)',
'color' => 'var(--md-fab-on-color)',
])
->and(ComponentStylesheet::read('fab')->declarations("[data-md-fab][data-md-color='tertiary']"))->toMatchArray([
'--md-fab-color' => 'var(--md-sys-color-tertiary)',
'--md-fab-container' => 'var(--md-sys-color-tertiary-container)',
]);
});
it('gives the extended FAB M3\'s gaps and its 80px minimum width', function (string $size, string $classes) {
expect((string) $this->blade("<x-fab icon=\"add\" label=\"New\" size=\"{$size}\" />"))->toContain($classes);
it('gives the extended FAB M3\'s gaps and its minimum width', function (string $size, string $gap, string $padding, string $type, string $minimum) {
$css = ComponentStylesheet::read('fab');
expect($css->declarations("[data-md-fab][data-md-extended][data-md-size='{$size}']"))->toMatchArray([
'gap' => $gap,
'padding-inline' => $padding,
'font' => "var(--md-sys-typescale-{$type})",
])
->and($css->declarations("[data-md-fab][data-md-size='{$size}']"))->toMatchArray(['--md-fab-extended-min' => $minimum])
->and($css->declarations('[data-md-fab][data-md-extended]'))->toBe(['min-inline-size' => 'var(--md-fab-extended-min)']);
})->with([
'sm' => ['sm', 'h-14 min-w-20 gap-2'],
'md' => ['md', 'h-20 min-w-20 gap-4'],
'lg' => ['lg', 'h-24 min-w-24 gap-5'],
'sm' => ['sm', 'var(--md-sys-measurement-space100)', 'var(--md-sys-measurement-space200)', 'title-md', '80px'],
'md' => ['md', 'var(--md-sys-measurement-space200)', '26px', 'title-lg', '80px'],
'lg' => ['lg', '20px', '28px', 'headline-sm', '96px'],
]);
it('collapses an extended FAB to a FAB on scroll when asked', function () {
$html = (string) $this->blade('<x-fab icon="add" label="New share" size="lg" collapse-on-scroll />');
$css = ComponentStylesheet::read('fab');
expect($html)
->toContain('x-data="materialFab"')
->toContain('x-bind:data-collapsed="collapsed ? &#039;&#039; : null"')
->toContain('data-fab-collapsible')
->toContain('data-fab-size="lg"')
->toContain('x-bind:data-md-collapsed="collapsed ? &#039;&#039; : null"')
->toContain('data-md-collapse-on-scroll')
->toContain('data-md-size="lg"')
// The label is clipped, never removed, so the collapsed FAB keeps its name.
->toContain('<span data-fab-label><span>New share</span></span>');
->toContain('<span data-md-fab-label><span>New share</span></span>')
->and($css->declarations('[data-md-fab][data-md-collapse-on-scroll][data-md-collapsed]'))->toBe(['min-inline-size' => 'var(--md-fab-size)', 'gap' => '0'])
->and($css->declarations('[data-md-fab][data-md-collapse-on-scroll][data-md-collapsed] [data-md-fab-label]'))->toBe(['grid-template-columns' => '0fr', 'opacity' => '0'])
->and($css->declarations("[data-md-fab][data-md-collapse-on-scroll][data-md-size='lg'][data-md-collapsed]"))->toBe(['padding-inline' => 'var(--md-sys-measurement-space400)'])
// Width and gap on the spatial spring, colour and shadow on the effects spring.
->and($css->declarations('[data-md-fab][data-md-collapse-on-scroll]')['transition-property'])->toBe('min-inline-size, padding-inline, gap, box-shadow, background-color, color');
// A plain FAB has nothing to collapse, and an extended FAB without a glyph would collapse to nothing.
expect((string) $this->blade('<x-fab icon="add" aria-label="New" collapse-on-scroll />'))->not->toContain('materialFab')
@@ -59,15 +114,14 @@ it('collapses an extended FAB to a FAB on scroll when asked', function () {
});
it('marks its root for the places that draw a nested FAB their own way', function () {
expect((string) $this->blade('<x-fab icon="add" aria-label="New" />'))->toContain('data-fab');
expect((string) $this->blade('<x-fab icon="add" aria-label="New" />'))->toContain('data-md-fab')->not->toContain('class=');
});
it('cannot be disabled, because M3 says to remove a FAB instead', function () {
$html = (string) $this->blade('<x-fab icon="add" aria-label="New" disabled />');
// `disabled` is no longer a prop, so it falls through as a plain attribute rather than
// painting M3's disabled treatment.
expect($html)->not->toContain('disabled:bg-on-surface/10')->not->toContain('disabled:shadow-none');
// `disabled` is not a prop, so it falls through as a plain attribute, and the stylesheet
// draws no disabled treatment for it.
expect((string) $this->blade('<x-fab icon="add" aria-label="New" disabled />'))->toContain('disabled="disabled"')
->and(ComponentStylesheet::read('fab')->css)->not->toContain(':disabled');
});
it('opens a FAB menu of end-aligned actions above it', function () {
+129
View File
@@ -0,0 +1,129 @@
<?php
use Livewire\Component;
use Livewire\Livewire;
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
it('draws a choice as connected radios', function () {
$html = (string) $this->blade(<<<'BLADE'
<x-group label="Theme" name="theme" x-model="theme" :options="[
['id' => 'light', 'name' => 'Light', 'icon' => 'light_mode'],
['id' => 'dark', 'name' => 'Dark', 'disabled' => true],
]" />
BLADE);
expect($html)
->toMatch('/<fieldset data-md-group="data-md-group" data-md-size="sm" data-md-variant="tonal" data-md-shape="round">/')
->toContain('<legend data-md-group-legend>Theme</legend>')
->toContain('<div data-md-button-group="connected" data-md-size="sm" data-md-shape="round">')
->toContain('<label data-md-group-segment>')
->toContain('type="radio"')
->toContain('name="theme"')
->toContain('x-model="theme"')
->toContain('value="light"')
->toContain('disabled')
->toContain('<span data-md-group-label>Light</span>')
->not->toContain('class=')
->and(substr_count($html, '<svg'))->toBe(1);
});
it('squares a choice\'s ends, and still rounds the chosen segment', function () {
$options = [['id' => 'a', 'name' => 'A']];
expect((string) $this->blade('<x-group shape="square" name="x" :$options />', ['options' => $options]))->toContain('data-md-button-group="connected" data-md-size="sm" data-md-shape="square"')
->and((string) $this->blade('<x-group name="x" :$options />', ['options' => $options]))->toContain('data-md-shape="round"')
->and(ComponentStylesheet::read('button-group')->declarations("[data-md-button-group][data-md-shape='square']"))->toBe(['--md-button-group-outer' => 'var(--md-button-group-inner)'])
->and(ComponentStylesheet::read('button-group')->declarations("[data-md-button-group='connected'] > :is([aria-pressed='true'], :has(:checked))"))->toBe(['--md-button-group-corner' => 'var(--md-button-group-full)'])
->and(ComponentStylesheet::read('group')->imports())->toBe(['./icon.css', './button-group.css']);
});
it('keeps a 48px target and a 48px minimum width on the smallest connected segments', function () {
$css = ComponentStylesheet::read('group');
expect($css->declarations("[data-md-group]:is([data-md-size='xs'], [data-md-size='sm']) [data-md-group-segment]"))->toBe(['min-inline-size' => 'var(--md-sys-measurement-space600)'])
->and($css->declarations("[data-md-group]:is([data-md-size='xs'], [data-md-size='sm']) [data-md-group-segment]::after"))->toMatchArray([
'min-width' => 'var(--md-sys-measurement-space600)',
'min-height' => 'var(--md-sys-measurement-space600)',
])
->and($css->declarations('[data-md-group-segment]'))->toMatchArray(['min-inline-size' => '0'])
->and(ComponentStylesheet::read('button-group')->declarations("[data-md-button-group='connected']:is([data-md-size='xs'], [data-md-size='sm']) > *"))->toBe(['min-inline-size' => 'var(--md-sys-measurement-space600)']);
});
it('sizes its segments as M3\'s buttons', function (string $size, string $height, string $padding, string $type, int $icon) {
$html = (string) $this->blade("<x-group size=\"{$size}\" name=\"x\" :options=\"[['id' => 'a', 'name' => 'A', 'icon' => 'home']]\" />");
expect($html)->toContain("data-md-size=\"{$size}\"")->toContain("--md-icon-size: {$icon}px")
->and(ComponentStylesheet::read('group')->declarations("[data-md-group][data-md-size='{$size}'] [data-md-group-segment]"))->toMatchArray([
'block-size' => $height,
'padding-inline' => $padding,
'font' => "var(--md-sys-typescale-{$type})",
]);
})->with([
'xs' => ['xs', '32px', 'var(--md-sys-measurement-space200)', 'label-lg', 20],
'sm' => ['sm', '40px', 'var(--md-sys-measurement-space200)', 'label-lg', 20],
'md' => ['md', '56px', 'var(--md-sys-measurement-space300)', 'title-md', 24],
'lg' => ['lg', '96px', 'var(--md-sys-measurement-space600)', 'headline-sm', 32],
'xl' => ['xl', '136px', 'var(--md-sys-measurement-space800)', 'headline-lg', 40],
]);
it('draws several choices as checkboxes, in the toggle button\'s colours', function () {
$css = ComponentStylesheet::read('group');
expect((string) $this->blade('<x-group name="days" multiple variant="outlined" :options="[[\'id\' => \'mon\', \'name\' => \'Mon\']]" />'))
->toContain('type="checkbox"')
->toContain('name="days[]"')
->toContain('data-md-variant="outlined"')
->toContain('data-md-multiple')
->and($css->declarations('[data-md-group-segment]:has(:checked)'))->toBe(['--md-group-container' => 'var(--md-sys-color-secondary)', '--md-group-label' => 'var(--md-sys-color-on-secondary)'])
->and($css->declarations("[data-md-group][data-md-variant='filled'] [data-md-group-segment]:has(:checked)"))->toBe(['--md-group-container' => 'var(--md-sys-color-primary)', '--md-group-label' => 'var(--md-sys-color-on-primary)'])
->and($css->declarations("[data-md-group][data-md-variant='outlined'] [data-md-group-segment]:has(:checked)"))->toBe(['--md-group-container' => 'var(--md-sys-color-inverse-surface)', '--md-group-label' => 'var(--md-sys-color-inverse-on-surface)', 'border-color' => 'transparent'])
->and($css->declarations('[data-md-group-segment]:has(:disabled)'))->toMatchArray(['cursor' => 'not-allowed'])
->and($css->declarations('[data-md-group-segment]:has(:focus-visible)'))->toBe(['outline' => '3px solid var(--md-sys-color-secondary)', 'outline-offset' => '2px'])
->and((string) $this->blade('<x-group name="x" variant="glass" :options="[]" />'))->toContain('data-md-variant="tonal"');
});
it('binds to a Livewire property and shows its validation message', function () {
$component = new class extends Component
{
public string $theme = 'dark';
public function save(): void
{
$this->validate(['theme' => 'in:light'], ['theme.in' => 'Pick light.']);
}
public function render(): string
{
return <<<'BLADE'
<div>
<x-group wire:model="theme" hint="How it looks" :options="[['id' => 'light', 'name' => 'Light'], ['id' => 'dark', 'name' => 'Dark']]" />
</div>
BLADE;
}
};
Livewire::test($component)
->assertSeeHtml('wire:model="theme"')
->assertSee('How it looks')
->set('theme', 'light')
->assertSet('theme', 'light')
->set('theme', 'dark')
->call('save')
->assertSee('Pick light.')
->assertDontSee('How it looks');
});
it('adds hint-class to the hint, which a validation message still replaces', function () {
$options = [['id' => 'flat', 'name' => 'Flat'], ['id' => 'hilly', 'name' => 'Hilly']];
expect((string) $this->blade('<x-group wire:model="terrain" hint="No elevation data here" hint-class="text-warning" :$options />', ['options' => $options]))
->toContain('<p data-md-group-hint class="text-warning" >No elevation data here</p>')
->and((string) $this->blade('<x-group wire:model="terrain" hint="No elevation data here" :$options />', ['options' => $options]))
->toContain('<p data-md-group-hint >No elevation data here</p>')
->and(ComponentStylesheet::read('group')->declarations('[data-md-group-hint]'))->toBe(['color' => 'var(--md-sys-color-on-surface-variant)']);
expect((string) $this->withViewErrors(['terrain' => 'Pick a terrain.'])->blade('<x-group wire:model="terrain" hint="No elevation data here" hint-class="text-warning" :$options />', ['options' => $options]))
->toContain('<p data-md-group-error>Pick a terrain.</p>')
->not->toContain('No elevation data here')
->not->toContain('text-warning');
});
+31 -14
View File
@@ -1,30 +1,47 @@
<?php
it('is a named progressbar in the primary colour, 48px by default', function () {
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
it('is a named progressbar, drawn by its stylesheet rather than by classes', function () {
$html = (string) $this->blade('<x-loading />');
expect($html)
->toContain('data-md-loading')
->toContain('role="progressbar"')
->toContain('aria-label="Loading"')
->toContain('size-12')
->toContain('text-primary')
->toContain('<animateTransform')
->toContain('class="size-full motion-reduce:hidden"')
->toContain('class="hidden size-full motion-reduce:block"');
->toMatch('/<svg data-md-loading-animated="data-md-loading-animated" aria-hidden="true" focusable="false"/')
->toMatch('/<svg data-md-loading-still="data-md-loading-still" aria-hidden="true" focusable="false"/')
->not->toContain('class=');
});
it('sits on a primary-container circle when contained', function () {
expect((string) $this->blade('<x-loading contained class="size-8" label="Uploading" />'))
->toContain('rounded-corner-full bg-primary-container text-on-primary-container')
->toContain('size-8')
->not->toContain('size-12')
it('is 48px in the primary colour unless the caller sizes or colours it', function () {
$css = ComponentStylesheet::read('loading');
expect($css->declarations('[data-md-loading]'))
->toMatchArray(['inline-size' => '48px', 'block-size' => '48px', 'color' => 'var(--md-sys-color-primary)'])
// A caller's class lands on the root untouched, and outranks the package's layer.
->and((string) $this->blade('<x-loading class="size-24 text-tertiary" label="Uploading" />'))
->toContain('class="size-24 text-tertiary"')
->toContain('aria-label="Uploading"');
});
it('takes the caller\'s colour', function () {
expect((string) $this->blade('<x-loading class="text-tertiary" />'))
->toContain('text-tertiary')
->not->toContain('text-primary');
it('sits on a primary-container circle when contained', function () {
expect((string) $this->blade('<x-loading contained />'))->toContain('data-md-contained')
->and((string) $this->blade('<x-loading />'))->not->toContain('data-md-contained')
->and(ComponentStylesheet::read('loading')->declarations('[data-md-loading][data-md-contained]'))->toBe([
'border-radius' => 'var(--md-sys-shape-corner-full)',
'background-color' => 'var(--md-sys-color-primary-container)',
'color' => 'var(--md-sys-color-on-primary-container)',
]);
});
it('rests the same shape under reduced motion', function () {
$css = ComponentStylesheet::read('loading');
expect($css->declarations('[data-md-loading] > [data-md-loading-still]'))->toBe(['display' => 'none'])
->and($css->declarations('[data-md-loading] > [data-md-loading-animated]', ['@media (prefers-reduced-motion: reduce)']))->toBe(['display' => 'none'])
->and($css->declarations('[data-md-loading] > [data-md-loading-still]', ['@media (prefers-reduced-motion: reduce)']))->toBe(['display' => 'block']);
});
it('says nothing where something else already does', function () {
@@ -45,7 +45,7 @@ it('badges the icon with a dot or a count that screen readers hear', function ()
$dot = (string) $this->blade('<x-navigation-bar-item label="Inbox" icon="inbox" link="/inbox" :badge="true" badge-label="New mail" />');
expect($count)->toContain('999+')->toContain('<span class="sr-only">, 1200</span>')
->and($dot)->toContain('size-1.5')->toContain('<span class="sr-only">, New mail</span>')
->and($dot)->toContain('data-md-dot')->toContain('<span class="sr-only">, New mail</span>')
->and((string) $this->blade('<x-navigation-bar-item label="Inbox" icon="inbox" link="/inbox" />'))->not->toContain('sr-only');
});
@@ -132,14 +132,14 @@ it('hides a collapsible or adaptive rail entirely when told to, and only those',
});
it('flattens a FAB nested in the rail header and morphs its label', function () {
// Both rules hang off `data-fab` on <x-fab>'s root, and both are unlayered, because what they
// Both rules hang off `data-md-fab` on <x-fab>'s root, and both are unlayered, because what they
// beat — the FAB's shadow, its gap, an extended FAB's minimum width — are utilities.
expect(file_get_contents(__DIR__.'/../../../resources/css/components/navigation.css'))
// A nested FAB rests at elevation 0, not the 3 a standalone one has (N-03).
->toContain('[data-navigation-rail-header] [data-fab],')
->toContain('[data-navigation-rail-header] [data-fab]:hover {')
->toContain('[data-navigation-rail-header] [data-md-fab],')
->toContain('[data-navigation-rail-header] [data-md-fab]:hover {')
// One FAB whose label springs shut, not two swapped by display (N-23).
->toContain('[data-navigation-rail-header] [data-fab] > span {')
->toContain('[data-navigation-rail-header] [data-md-fab] > span {')
->toMatch('/@variant rail-collapsed \{\s+min-width: 0;\s+aspect-ratio: 1;\s+gap: 0;/');
});
+45 -20
View File
@@ -1,5 +1,7 @@
<?php
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
it('puts the action on the leading button and the menu on the trailing one', function () {
$html = (string) $this->blade(<<<'BLADE'
<x-split-button label="Download all" icon="download" wire:click="downloadZip" menu-label="Download options" class="mt-4">
@@ -8,36 +10,59 @@ it('puts the action on the leading button and the menu on the trailing one', fun
BLADE);
expect($html)
->toContain('data-button-group="split"')
->toContain('mt-4')
->toContain('data-split="leading"')
->toContain('wire:click="downloadZip"')
->toContain('data-split="trailing"')
->toContain('aria-label="Download options"')
->toStartWith('<div data-md-split-button data-md-size="sm" class="mt-4">')
->toMatch('/<button data-md-button="data-md-button"[^>]*data-md-split="leading" wire:click="downloadZip">/')
->toMatch('/<button data-md-button="data-md-button"[^>]*data-md-icon-button="data-md-icon-button"[^>]*aria-label="Download options"[^>]*data-md-split="trailing">/')
->toContain('role="menu"')
->toContain('As a ZIP')
->and(substr_count($html, 'wire:click="downloadZip"'))->toBe(1);
});
it('leaves the corners to the group', function () {
$html = (string) $this->blade('<x-split-button label="Save"><x-menu-item label="Draft" /></x-split-button>');
it('leaves the corners to the pair, growing the inner ones under the finger', function () {
$css = ComponentStylesheet::read('split-button');
preg_match_all('/<button\b[^>]*data-split="[^"]*"[^>]*>/', $html, $halves);
expect($halves[0])->toHaveCount(2);
foreach ($halves[0] as $half) {
expect($half)->not->toContain('rounded-corner-full')->not->toContain('active:rounded-corner');
}
expect($css->declarations('[data-md-split-button] [data-md-split]'))->toBe([
'--md-split-button-corner' => 'var(--md-split-button-inner)',
'border-start-start-radius' => 'var(--md-split-button-corner)',
'border-end-start-radius' => 'var(--md-split-button-corner)',
'border-start-end-radius' => 'var(--md-split-button-corner)',
'border-end-end-radius' => 'var(--md-split-button-corner)',
])
->and($css->declarations('[data-md-split-button] [data-md-split]:active'))->toBe(['--md-split-button-corner' => 'var(--md-split-button-inner-pressed)'])
->and($css->declarations("[data-md-split-button] [data-md-split='trailing'][aria-expanded='true']"))->toBe(['--md-split-button-corner' => 'var(--md-split-button-full)'])
->and($css->declarations("[data-md-split-button][data-md-size='xl']"))->toBe([
'--md-split-button-inner' => 'var(--md-sys-shape-corner-md)',
'--md-split-button-inner-pressed' => 'var(--md-sys-shape-corner-lg-increased)',
'--md-split-button-full' => '68px',
'--md-split-button-icon' => '50px',
'--md-split-button-nudge' => '6px',
])
->and($css->imports())->toBe(['./button.css']);
});
it('is filled unless another container variant is asked for', function () {
expect((string) $this->blade('<x-split-button label="Save" variant="text"><x-menu-item label="Draft" /></x-split-button>'))->toContain('bg-primary text-on-primary')
->and((string) $this->blade('<x-split-button label="Save" variant="tonal"><x-menu-item label="Draft" /></x-split-button>'))->toContain('bg-secondary-container');
expect((string) $this->blade('<x-split-button label="Save" variant="text"><x-menu-item label="Draft" /></x-split-button>'))->toContain('data-md-variant="filled"')->not->toContain('data-md-variant="text"')
->and((string) $this->blade('<x-split-button label="Save" variant="tonal"><x-menu-item label="Draft" /></x-split-button>'))->toContain('data-md-variant="tonal"');
});
it('gives the two smallest sizes their narrower inner padding and 48px trailing button', function () {
expect((string) $this->blade('<x-split-button label="Save" size="xs"><x-menu-item label="Draft" /></x-split-button>'))
->toContain('pe-2.5')
->toContain('w-12');
$css = ComponentStylesheet::read('split-button');
expect((string) $this->blade('<x-split-button label="Save" size="xs"><x-menu-item label="Draft" /></x-split-button>'))->toContain('data-md-split-button data-md-size="xs"')
->and($css->declarations("[data-md-split-button][data-md-size='xs'] [data-md-split='leading']"))->toBe(['padding-inline-end' => 'var(--md-sys-measurement-space125)'])
->and($css->declarations("[data-md-split-button][data-md-size='sm'] [data-md-split='leading']"))->toBe(['padding-inline-end' => '12px'])
->and($css->declarations("[data-md-split-button]:is([data-md-size='xs'], [data-md-size='sm']) [data-md-split='trailing']"))->toBe(['inline-size' => 'var(--md-sys-measurement-space600)']);
});
it('nudges its chevron towards the leading half and turns it over on the standard scheme', function () {
$css = ComponentStylesheet::read('split-button');
expect($css->declarations("[data-md-split-button] [data-md-split='trailing'] [data-md-icon]"))->toBe([
'inline-size' => 'var(--md-split-button-icon)',
'block-size' => 'var(--md-split-button-icon)',
'margin-inline-start' => 'calc(-1 * var(--md-split-button-nudge))',
'margin-inline-end' => 'var(--md-split-button-nudge)',
'transition' => 'rotate var(--md-sys-motion-duration-short) var(--md-sys-motion-easing-standard)',
])
->and($css->declarations("[data-md-split-button] [data-md-split='trailing'][aria-expanded='true'] [data-md-icon]"))->toBe(['rotate' => '180deg']);
});
+40 -11
View File
@@ -1,5 +1,7 @@
<?php
use NoNameWeb\LivewireMaterial\Tests\Support\ComponentStylesheet;
it('wraps a trigger and anchors the bubble to it', function () {
$html = (string) $this->blade('<x-tooltip text="Copy link"><button>Copy</button></x-tooltip>');
@@ -7,22 +9,49 @@ it('wraps a trigger and anchors the bubble to it', function () {
expect($anchor)->not->toBeEmpty()
->and($html)
->toContain('<button>Copy</button>')
->toContain('popover="manual"')
->toContain('x-data="materialTooltip"')
->toContain("position-anchor: {$anchor[1]}")
->toContain('bg-inverse-surface')
->toContain('[position-area:top]');
->toMatch('/<span data-md-tooltip-anchor style="anchor-name: --material-tooltip-[a-z0-9]+">\s*<button>Copy<\/button>/')
->toMatch('/<span\s+popover="manual"\s+aria-hidden="true"\s+x-data="materialTooltip"\s+data-md-tooltip\s+data-md-side="top"\s+style="position-anchor: '.preg_quote($anchor[1], '/').'"\s*>Copy link<\/span>/')
->not->toContain('class=');
});
it('places the bubble on the side asked for, flipping when there is no room', function (string $side, string $classes) {
expect((string) $this->blade("<x-tooltip text=\"Hi\" side=\"{$side}\"><span>x</span></x-tooltip>"))->toContain($classes);
it('places the bubble on the side asked for, 4px out, flipping when there is no room', function (string $side, string $axis, string $margin, string $flip) {
$css = ComponentStylesheet::read('tooltip');
expect((string) $this->blade("<x-tooltip text=\"Hi\" side=\"{$side}\"><span>x</span></x-tooltip>"))->toContain("data-md-side=\"{$side}\"")
->and($css->declarations("[data-md-tooltip][data-md-side='{$side}']"))->toBe(['position-area' => $side])
->and($css->declarations("[data-md-tooltip]:is({$axis})"))->toBe([$margin => 'var(--md-sys-measurement-space50)', 'position-try-fallbacks' => $flip]);
})->with([
'bottom' => ['bottom', '[position-area:bottom] [position-try-fallbacks:flip-block]'],
'left' => ['left', '[position-area:left] [position-try-fallbacks:flip-inline]'],
'right' => ['right', '[position-area:right] [position-try-fallbacks:flip-inline]'],
'top' => ['top', "[data-md-side='top'], [data-md-side='bottom']", 'margin-block', 'flip-block'],
'bottom' => ['bottom', "[data-md-side='top'], [data-md-side='bottom']", 'margin-block', 'flip-block'],
'left' => ['left', "[data-md-side='left'], [data-md-side='right']", 'margin-inline', 'flip-inline'],
'right' => ['right', "[data-md-side='left'], [data-md-side='right']", 'margin-inline', 'flip-inline'],
]);
it('falls back to the top for a side it does not know', function () {
expect((string) $this->blade('<x-tooltip text="Hi" side="middle"><span>x</span></x-tooltip>'))->toContain('data-md-side="top"');
});
it('draws M3\'s plain tooltip in the inverse surface, and fades on the effects spring', function () {
$css = ComponentStylesheet::read('tooltip');
expect($css->declarations('[data-md-tooltip]'))->toMatchArray([
'max-inline-size' => '200px',
'border-radius' => 'var(--md-sys-shape-corner-xs)',
'padding-block' => 'var(--md-sys-measurement-space50)',
'padding-inline' => 'var(--md-sys-measurement-space100)',
'background-color' => 'var(--md-sys-color-inverse-surface)',
'color' => 'var(--md-sys-color-inverse-on-surface)',
'font' => 'var(--md-sys-typescale-body-sm)',
'pointer-events' => 'none',
'opacity' => '0',
'transition-duration' => 'var(--md-sys-motion-effects-fast-duration)',
'transition-timing-function' => 'var(--md-sys-motion-effects-fast)',
'transition-behavior' => 'allow-discrete',
])
->and($css->declarations('[data-md-tooltip]:popover-open'))->toBe(['opacity' => '1'])
->and($css->declarations('[data-md-tooltip]:popover-open', ['@starting-style']))->toBe(['opacity' => '0']);
});
it('escapes its text', function () {
$this->blade('<x-tooltip text="<b>bold</b>"><span>x</span></x-tooltip>')
->assertSee('&lt;b&gt;bold&lt;/b&gt;', false);
+299
View File
@@ -0,0 +1,299 @@
<?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 dirname(__DIR__, 2)."/resources/css/components/{$name}.css";
}
/**
* 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(
fn (string $statement): ?string => preg_match('/^@import\s+([\'"])(.+?)\1;$/', $statement, $match) === 1 ? $match[2] : null,
$this->statements,
)));
}
/**
* 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;
}
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));
}
private 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.
*
* @return list<array{statement: string}|array{prelude: string, body: string}>
*/
private 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;
}
}