Add M3 text fields, selects and selection controls
tests / feature (8.4) (push) Successful in 1m5s
tests / feature (8.5) (push) Successful in 1m4s
tests / lint (push) Successful in 59s
tests / browser (chrome, chromium) (push) Successful in 2m54s
tests / browser (firefox, firefox) (push) Successful in 3m3s
tests / browser (safari, webkit) (push) Successful in 4m13s

Outlined and filled text fields (input, password, auto-growing textarea,
native select with the customizable select menu, file), checkbox with an
indeterminate state, radio buttons, the M3 switch and form, ported from
ReStride and extended. The first half of Phase 6.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01V9NnLxnPp8vaaurb3Z1MFy
This commit is contained in:
Andreas Reinhold / reini
2026-09-13 07:53:14 +02:00
co-authored by Claude Opus 5
parent ad724662ca
commit 7f92f1cb29
24 changed files with 2296 additions and 1 deletions
+15
View File
@@ -34,6 +34,21 @@ return [
'legacy_keys' => [], 'legacy_keys' => [],
], ],
/*
|--------------------------------------------------------------------------
| Fields
|--------------------------------------------------------------------------
|
| Text fields, selects and pickers come in M3's two styles: 'outlined' (a
| notched outline) and 'filled' (a tinted box with an indicator line). This
| is the style a field takes when its `variant` is not given.
|
*/
'fields' => [
'variant' => 'outlined',
],
/* /*
|-------------------------------------------------------------------------- |--------------------------------------------------------------------------
| Node | Node
@@ -361,6 +361,45 @@ An M3 bottom sheet, bound like `<x-modal>`: modal by default (scrim, inert page,
A row of items that change size between M3's keylines as it scrolls (native scroll snap; items are masked, content keeps its size). `<x-carousel>`: `layout` (`multi-browse` default, `hero`, `uncontained`, `full-screen`), `item-width` (px or any CSS length; the large size multi-browse aims for, the fixed size uncontained keeps, the cap for hero; 186 by default), `height` (205px), `padding` (px at the ends, 0), `centered` (hero), `label` (the region's name, "Carousel" by default), `controls` (previous/next buttons: default fine pointers only, `true` always, `false` never). `<x-carousel-item>`: slot is an `<img>` (fills and crops) or an element sized `size-full`; `label` overlays a line of text. A focusable `region` of `slide` groups named "n of m"; arrow keys move one item while the row has focus, Home/End to the ends. Works after a Livewire morph, in RTL and under reduced motion. Give items a `wire:key` in a loop. A row of items that change size between M3's keylines as it scrolls (native scroll snap; items are masked, content keeps its size). `<x-carousel>`: `layout` (`multi-browse` default, `hero`, `uncontained`, `full-screen`), `item-width` (px or any CSS length; the large size multi-browse aims for, the fixed size uncontained keeps, the cap for hero; 186 by default), `height` (205px), `padding` (px at the ends, 0), `centered` (hero), `label` (the region's name, "Carousel" by default), `controls` (previous/next buttons: default fine pointers only, `true` always, `false` never). `<x-carousel-item>`: slot is an `<img>` (fills and crops) or an element sized `size-full`; `label` overlays a line of text. A focusable `region` of `slide` groups named "n of m"; arrow keys move one item while the row has focus, Home/End to the ends. Works after a Livewire morph, in RTL and under reduced motion. Give items a `wire:key` in a loop.
### `<x-form>`
A one-column grid of fields with an `actions` slot at the foot (the slot takes its own `class`); `separator` draws a divider above the actions.
```blade
<x-form wire:submit="save">
<x-input label="Share name" wire:model="name" required />
<x-select label="Expires after" wire:model="hours" :options="$expiryOptions" />
<x-slot:actions>
<x-button label="Cancel" wire:click="cancel" />
<x-button label="Create share" variant="filled" type="submit" spinner="save" />
</x-slot:actions>
</x-form>
```
### `<x-field>`, `<x-input>`, `<x-password>`, `<x-textarea>`, `<x-select>`, `<x-file>`
M3 text fields. `variant`: `outlined` or `filled`; without it, `config('livewire-material.fields.variant')` (`outlined`). All take `label`, `hint`, `variant`, and read their errors from the bag under the `wire:model` name (the error replaces the hint, sets `aria-invalid`). `class` lands on the field's outer element (margins, widths); every other attribute (`wire:model`, `type`, `required`, `readonly`, `autocomplete`) reaches the control. Never pass `placeholder` expecting it to show while a label rests in the field: it shows once the field has focus.
- `<x-input>`: `icon`, `icon-right`, `prefix`, `suffix`, `clearable`, `copyable` (copies the value, confirms with a snackbar), `size` (`sm` 40px, `xs` 32px — for unlabelled toolbar controls; give them `aria-label`), `mono`.
- `<x-password>`: a reveal button; `icon`, `size`.
- `<x-textarea>`: grows from `rows` (3) to `max-rows`, then scrolls; `:autogrow="false"` for a fixed, hand-resizable one.
- `<x-select>`: native `<select>` (M3 menu where the browser supports customizable selects). `options` as `['id' => …, 'name' => …, 'disabled' => bool]`, `option-value`, `option-label`, `placeholder` + `placeholder-value`, or `<option>`s in the slot; `icon`, `size`.
- `<x-file>`: native file input; errors from `photos` and `photos.*`. Show previews of what was chosen yourself.
- `<x-field id="…" label="…" :messages="$messages">` wraps a custom control given `class="field-control"`; only for controls the package does not have.
### `<x-checkbox>`, `<x-radio>`, `<x-toggle>`
M3 selection controls on native inputs; the whole row is the label.
- `<x-checkbox label hint right indeterminate />``indeterminate` for a "select all" whose items are partly ticked (bind it to a server expression; it follows every render).
- `<x-radio label wire:model :options inline />` — options `['id', 'name', 'hint', 'disabled']` (`option-value`, `option-label`, `option-hint`); `value` checks an option without `wire:model`; `name` names an unbound group.
- `<x-toggle label hint right icons />` — M3 switch (`role="switch"`); `icons` puts a check and a cross on the handle, `icons="selected"` only the check. Without `label`, pass `aria-label`.
```blade
<x-checkbox label="All files" :checked="count($selected) === $files->count()" :indeterminate="$selected && count($selected) < $files->count()" wire:click="toggleAll" />
<x-toggle label="Notify me on download" wire:model.live="notify" right />
```
## Testing the design ## Testing the design
```php ```php
+516
View File
@@ -0,0 +1,516 @@
/*
* M3's text fields — the chrome every form control here shares: outlined (the default) and filled.
*
* The states are selectors rather than classes: whether the label rests in the field or floats is a
* question about the control's value and focus, and `:has()` asks it without JavaScript, so it is
* right before Alpine starts, in a test, and after a Livewire morph rewrites the value underneath.
*
* The outlined field's notch is MUI's technique: a `<fieldset>` draws the outline and a hidden
* `<legend>`, carrying the label at its floated size, cuts the gap the label sits in, so the gap is
* right on any background. The filled field has no outline: a surface-container-highest box with
* extra-small top corners and an active indicator line, the label floating inside it
* (FilledTextFieldTokens / OutlinedTextFieldTokens, androidx Compose Material 3, Apache-2.0).
*
* Anatomy (resources/views/components/field.blade.php):
*
* .field the whole thing; `class` from the call site lands here; data-variant, data-size
* .field-box the 56px row: icon, prefix, control, suffix, trailing
* .field-control the <input>, <select> or <textarea>
* .field-outline the fieldset and its legend (the filled field's indicator line)
* .field-label the visible label
* .field-support the hint, or the error in its place
*
* A select's open list is not part of the field: it is the dropdown menu in components/menu.css.
*/
@layer components {
.field {
--field-height: 3.5rem;
--field-pad: 1rem;
--field-icon: 1.5rem;
--field-gap: 1rem;
--field-start: var(--field-pad);
--field-edge: var(--md-sys-color-outline);
--field-ink: var(--md-sys-color-on-surface-variant);
display: flex;
flex-direction: column;
min-width: 0;
}
/* A filled field's resting indicator line is on-surface-variant, where an outline is outline. */
.field[data-variant="filled"] {
--field-edge: var(--md-sys-color-on-surface-variant);
}
.field[data-size="sm"] {
--field-height: 2.5rem;
--field-pad: 0.75rem;
--field-icon: 1.25rem;
--field-gap: 0.5rem;
}
.field[data-size="xs"] {
--field-height: 2rem;
--field-pad: 0.625rem;
--field-icon: 1rem;
--field-gap: 0.375rem;
}
.field:has(.field-icon) {
--field-start: calc(var(--field-pad) + var(--field-icon) + var(--field-gap));
}
.field-box {
position: relative;
display: flex;
align-items: center;
gap: var(--field-gap);
min-height: var(--field-height);
padding-inline: var(--field-pad);
border-radius: var(--md-sys-shape-corner-xs);
cursor: text;
}
.field-control {
flex: 1 1 0%;
min-width: 0;
align-self: stretch;
background: transparent;
color: var(--md-sys-color-on-surface);
caret-color: var(--md-sys-color-primary);
outline: none;
font: var(--md-sys-typescale-body-lg);
letter-spacing: var(--md-sys-typescale-body-lg-tracking);
}
.field[data-size="xs"] .field-control {
font: var(--md-sys-typescale-body-md);
letter-spacing: var(--md-sys-typescale-body-md-tracking);
}
.field[data-mono] .field-control {
font-family: var(--font-mono, ui-monospace, SFMono-Regular, Menlo, monospace);
}
.field-control::placeholder {
color: var(--md-sys-color-on-surface-variant);
opacity: 1;
}
/* Autofill paints its own background, which on a card is a pale block in the
wrong colour. Delaying the transition for a week keeps the field's own. */
.field-control:-webkit-autofill {
-webkit-text-fill-color: var(--md-sys-color-on-surface);
transition: background-color 604800s, color 604800s;
}
/* The browser draws the resize grip in the textarea's own corner, so the
textarea reaches to just inside the outline's end and bottom — the grip sits
in the field's corner, not on the bottom outline a padding in from it — and
its padding puts the text back where it was. */
textarea.field-control {
--field-grip: 0.25rem;
/* The first half-line of the top offset is a margin, not padding: text scrolled up in a full
textarea disappears under the edge instead of running through the label. */
--textarea-clear: 0.5rem;
--textarea-pad-top: calc((var(--field-height) - 1.5rem) / 2 - var(--textarea-clear));
--textarea-pad-bottom: calc((var(--field-height) - 1.5rem) / 2 - var(--field-grip));
margin-block: var(--textarea-clear) var(--field-grip);
margin-inline-end: calc(var(--field-grip) - var(--field-pad));
padding-block: var(--textarea-pad-top) var(--textarea-pad-bottom);
padding-inline-end: calc(var(--field-pad) - var(--field-grip));
resize: vertical;
}
/* `<x-textarea>` grows with what is typed, from `rows` lines up to `max-rows`. Where the browser
cannot size a field to its content, resources/js/field.js sets the height instead. */
textarea.field-control[data-autogrow] {
field-sizing: content;
min-block-size: calc(var(--field-rows, 3) * 1.5rem + var(--textarea-pad-top) + var(--textarea-pad-bottom));
max-block-size: calc(var(--field-max-rows, 1000) * 1.5rem + var(--textarea-pad-top) + var(--textarea-pad-bottom));
resize: none;
}
/* A select covers its whole field — out over the padding and the leading icon at
the start, under the arrow to the end — and its own padding puts the value back
where it was. So a press anywhere on the field opens it, and the list, which
the browser anchors to the select, is the field's width (components/menu.css). */
select.field-control {
--field-end: calc(var(--field-icon) + var(--field-gap) + var(--field-pad));
appearance: none;
cursor: pointer;
margin-inline: calc(-1 * var(--field-start)) calc(-1 * var(--field-end));
padding-inline: var(--field-start) var(--field-end);
}
select.field-control:disabled {
cursor: default;
}
/* Where the browser has a customizable select, the closed select is its own
button: without the border, padding and arrow that button brings, it is the
same field as before. While its list is open the field reads as focused —
said from `:open`, because focus inside the list is in the top layer — and
the arrow turns over, as the searchable choices' does. */
@supports (appearance: base-select) {
select.field-control {
display: flex;
align-items: center;
border: 0;
padding-block: 0;
border-radius: 0;
background: transparent;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
select.field-control::picker-icon {
display: none;
}
.field-box:has(select.field-control:open) {
--field-edge: var(--md-sys-color-primary);
--field-ink: var(--md-sys-color-primary);
.field-outline {
border-width: 2px;
}
}
.field:has(select.field-control:open) .field-arrow {
rotate: 180deg;
}
}
/* `<x-file>`: the browser's own "No file chosen" line is transparent (the caller shows what was
chosen), and its button is a tonal pill — the thing to press. */
input[type="file"].field-control {
align-self: center;
color: transparent;
cursor: pointer;
}
input[type="file"].field-control::file-selector-button {
height: 2rem;
margin-inline-end: 0.75rem;
padding-inline: 1rem;
border: 0;
border-radius: var(--md-sys-shape-corner-full);
background-color: var(--md-sys-color-secondary-container);
color: var(--md-sys-color-on-secondary-container);
cursor: pointer;
font: var(--md-sys-typescale-label-lg);
letter-spacing: var(--md-sys-typescale-label-lg-tracking);
transition: background-color var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
@media (hover: hover) {
input[type="file"].field-control:hover::file-selector-button {
background-color: color-mix(in srgb, var(--md-sys-color-on-secondary-container) 8%, var(--md-sys-color-secondary-container));
}
}
input[type="file"].field-control:disabled::file-selector-button {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface) 12%, transparent);
color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
cursor: default;
}
.field-arrow {
transition: rotate var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
.field-icon,
.field-trailing {
flex: none;
width: var(--field-icon);
height: var(--field-icon);
color: var(--md-sys-color-on-surface-variant);
}
.field-icon,
.field-arrow {
pointer-events: none;
}
/* A trailing button — clear, copy, reveal — is an icon button: the icon in a 40px state layer. */
.field-button {
position: relative;
display: grid;
place-items: center;
margin-inline-end: -0.25rem;
border-radius: var(--md-sys-shape-corner-full);
cursor: pointer;
outline: none;
}
.field-button::before {
content: "";
position: absolute;
inset: 50% auto auto 50%;
width: calc(var(--field-icon) + 1rem);
height: calc(var(--field-icon) + 1rem);
translate: -50% -50%;
border-radius: inherit;
transition: background-color var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
@media (hover: hover) {
.field-button:hover::before {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface-variant) 8%, transparent);
}
}
.field-button:focus-visible::before {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface-variant) 10%, transparent);
outline: 3px solid var(--md-sys-color-secondary);
outline-offset: 2px;
}
.field-button:active::before {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface-variant) 10%, transparent);
}
.field-affix {
flex: none;
color: var(--md-sys-color-on-surface-variant);
font: var(--md-sys-typescale-body-lg);
letter-spacing: var(--md-sys-typescale-body-lg-tracking);
}
.field[data-size="xs"] .field-affix {
font: var(--md-sys-typescale-body-md);
}
.field-outline {
position: absolute;
inset: -0.3125rem 0 0;
margin: 0;
padding: 0 calc(var(--field-pad) - 0.25rem);
border: 1px solid var(--field-edge);
border-radius: inherit;
pointer-events: none;
min-width: 0;
transition: border-color var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
.field-outline > legend {
display: block;
width: auto;
max-width: 100%;
height: 0.6875rem;
padding: 0;
overflow: hidden;
visibility: hidden;
white-space: nowrap;
font: var(--md-sys-typescale-body-sm);
letter-spacing: var(--md-sys-typescale-body-sm-tracking);
transition: max-width var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
.field-outline > legend > span {
display: inline-block;
padding-inline: 0.25rem;
}
.field-label {
position: absolute;
inset-inline-start: var(--field-pad);
top: 0;
max-width: calc(100% - 2 * var(--field-pad));
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
translate: 0 -50%;
color: var(--field-ink);
font: var(--md-sys-typescale-body-sm);
letter-spacing: var(--md-sys-typescale-body-sm-tracking);
pointer-events: none;
transition-property: top, inset-inline-start, font-size, line-height, color;
transition-duration: var(--md-sys-motion-effects-fast-duration);
transition-timing-function: var(--md-sys-motion-effects-fast);
}
/* `required` is marked from the control itself, in the label and in the notch,
so the gap is cut for the asterisk too. */
.field:has(.field-control:required) .field-label::after,
.field:has(.field-control:required) .field-outline > legend > span::after {
content: " *";
}
/* Resting: a label, an empty control, and no focus. The label sits where the
text will go, at the text's size; the notch closes; the placeholder and the
prefix wait, because the label is standing where they would be. A select and
a date always hold a value, so they mark themselves `data-floated`. */
.field:not([data-floated]):has(.field-label):has(.field-control:placeholder-shown):not(:focus-within) {
.field-label {
top: 50%;
inset-inline-start: var(--field-start);
font: var(--md-sys-typescale-body-lg);
letter-spacing: var(--md-sys-typescale-body-lg-tracking);
}
.field-outline > legend {
max-width: 0.01px;
}
.field-affix {
visibility: hidden;
}
}
.field[data-size="xs"]:not([data-floated]):has(.field-label):has(.field-control:placeholder-shown):not(:focus-within) .field-label {
font: var(--md-sys-typescale-body-md);
}
/* A textarea's label rests on its first line, not in the middle of the box. */
.field:not([data-floated]):has(.field-label):has(textarea.field-control:placeholder-shown):not(:focus-within) .field-label {
top: calc(var(--field-height) / 2);
}
.field:has(.field-label):not(:focus-within) .field-control::placeholder {
color: transparent;
}
/* Clearing is offered only once there is something to clear. */
.field:has(.field-control:placeholder-shown) .field-clear {
display: none;
}
.field-box:hover {
--field-edge: var(--md-sys-color-on-surface);
}
.field-box:focus-within {
--field-edge: var(--md-sys-color-primary);
--field-ink: var(--md-sys-color-primary);
}
.field-box:focus-within .field-outline {
border-width: 2px;
}
.field[data-invalid] {
--field-edge: var(--md-sys-color-error);
--field-ink: var(--md-sys-color-error);
}
.field[data-invalid] .field-box:hover {
--field-edge: var(--md-sys-color-on-error-container);
}
.field[data-invalid] .field-box:focus-within {
--field-edge: var(--md-sys-color-error);
--field-ink: var(--md-sys-color-error);
}
/* Dashed for a field the caller made read-only — marked on the field, not read off the control,
because a date picker makes its own input read-only too. */
.field[data-readonly] .field-outline {
border-style: dashed;
}
.field:has(.field-control:disabled) {
--field-edge: color-mix(in srgb, var(--md-sys-color-on-surface) 12%, transparent);
--field-ink: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
.field-box {
cursor: default;
}
.field-control,
.field-icon,
.field-affix,
.field-trailing {
color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
}
}
.field-support {
padding: 0.25rem var(--field-pad) 0;
color: var(--md-sys-color-on-surface-variant);
font: var(--md-sys-typescale-body-sm);
letter-spacing: var(--md-sys-typescale-body-sm-tracking);
}
.field[data-invalid] .field-support {
color: var(--md-sys-color-error);
}
/* ---- The filled text field ---------------------------------------------------------------- */
.field[data-variant="filled"] .field-box {
border-radius: var(--md-sys-shape-corner-xs) var(--md-sys-shape-corner-xs) 0 0;
background-color: var(--md-sys-color-surface-container-highest);
transition: background-color var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
@media (hover: hover) {
.field[data-variant="filled"] .field-box:hover {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface) 8%, var(--md-sys-color-surface-container-highest));
}
}
/* The outline becomes the active indicator: one line along the bottom. */
.field[data-variant="filled"] .field-outline {
inset: auto 0 0;
padding: 0;
border: 0;
border-block-end: 1px solid var(--field-edge);
border-radius: 0;
}
.field[data-variant="filled"] .field-outline > legend {
display: none;
}
.field[data-variant="filled"] .field-box:focus-within .field-outline {
border-block-end-width: 2px;
}
/* The label floats inside the box, above the value, and the value sits below it. */
.field[data-variant="filled"] .field-label {
top: 1rem;
inset-inline-start: var(--field-start);
max-width: calc(100% - var(--field-start) - var(--field-pad));
}
.field[data-variant="filled"]:has(.field-label) .field-control {
padding-block: 1.5rem 0.5rem;
}
.field[data-variant="filled"]:has(.field-label) textarea.field-control {
--textarea-clear: 1.5rem;
--textarea-pad-top: 0rem;
--textarea-pad-bottom: calc(0.5rem - var(--field-grip));
padding-block: var(--textarea-pad-top) var(--textarea-pad-bottom);
}
/* A file picker's button is taller than a line of text: it sits lower, and a little smaller. */
.field[data-variant="filled"]:has(.field-label) input[type="file"].field-control {
padding-block: 1.375rem 0.375rem;
}
.field[data-variant="filled"] input[type="file"].field-control::file-selector-button {
height: 1.75rem;
}
.field[data-variant="filled"]:has(.field-label) .field-affix {
align-self: stretch;
padding-block: 1.5rem 0.5rem;
}
.field[data-variant="filled"]:has(.field-control:disabled) {
--field-edge: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
.field-box {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface) 4%, transparent);
}
}
}
+170
View File
@@ -0,0 +1,170 @@
/*
* The exposed dropdown menu — the list a field drops open.
*
* Two lists wear it, so a form reads as one family:
*
* - `<x-select>`'s: the native <select>, opted into the browser's customizable select
* (`appearance: base-select`). `::picker(select)` is the menu and each <option> a row, while the
* keyboard, type-to-find, the screen reader and the form value stay the browser's own.
* - `<x-choices searchable>`'s listbox, which Alpine draws, as `.field-menu` and `.field-option`.
*
* M3's menu as its tokens have it: surface-container at elevation 2, extra-small corner, 48px rows in
* body-large, the chosen row in secondary-container with a tick at its end (so it is not told by colour
* alone), and the state layer on hover (only where a pointer can hover) and focus.
*
* Unlayered, as the rest of the package's component CSS, so a utility on the call site cannot half-undo
* a row.
*
* Where the browser has no customizable select, the select keeps its native list, which
* `color-scheme` themes. Every rule for the select's own rows is inside `@supports`: a browser that
* paints option colours into its native list would otherwise show a half-painted one.
*/
.field-menu {
max-block-size: 18rem;
overflow-y: auto;
padding-block: 0.5rem;
border-radius: var(--md-sys-shape-corner-xs);
background: var(--md-sys-color-surface-container);
box-shadow: var(--md-sys-elevation-2);
}
.field-option {
display: flex;
align-items: center;
gap: 0.75rem;
min-block-size: 3rem;
padding-inline: 1rem;
color: var(--md-sys-color-on-surface);
font: var(--md-sys-typescale-body-lg);
letter-spacing: var(--md-sys-typescale-body-lg-tracking);
cursor: pointer;
}
/* `data-active` is the row the arrow keys or the pointer are on. */
.field-option[data-active] {
background: color-mix(in srgb, var(--md-sys-color-on-surface) 8%, transparent);
}
.field-option[aria-selected="true"] {
background: var(--md-sys-color-secondary-container);
color: var(--md-sys-color-on-secondary-container);
}
.field-option[aria-selected="true"][data-active] {
background: color-mix(in srgb, var(--md-sys-color-on-secondary-container) 8%, var(--md-sys-color-secondary-container));
}
.field-check {
margin-inline-start: auto;
}
.field-option:not([aria-selected="true"]) .field-check {
visibility: hidden;
}
@supports (appearance: base-select) {
select.field-control,
select.field-control::picker(select) {
appearance: base-select;
}
/* The menu. The browser anchors it to the select; the select covers its whole
field (field.css), so the menu is at least the field's width. It hangs under
the field and goes above only when it does not fit there — the browser's own
order tries the roomier side first, which opened a menu upwards with room to
spare under it. It opens with a fade and a grow on the spatial spring and
closes with a fade, as `<x-menu>` does. */
select.field-control::picker(select) {
position-try-order: normal;
max-block-size: 18rem;
max-inline-size: calc(100vw - 2rem);
margin-block: 0.25rem;
padding-block: 0.5rem;
border: 0;
border-radius: var(--md-sys-shape-corner-xs);
background: var(--md-sys-color-surface-container);
color: var(--md-sys-color-on-surface);
box-shadow: var(--md-sys-elevation-2);
opacity: 0;
transform-origin: top;
transition-property: opacity, display, overlay;
transition-duration: var(--md-sys-motion-effects-fast-duration);
transition-timing-function: var(--md-sys-motion-effects-fast);
transition-behavior: allow-discrete;
}
select.field-control:open::picker(select) {
opacity: 1;
transition-property: opacity, scale, display, overlay;
transition-duration: var(--md-sys-motion-spatial-fast-duration);
transition-timing-function: var(--md-sys-motion-spatial-fast);
}
@starting-style {
select.field-control:open::picker(select) {
opacity: 0;
scale: 0.95;
}
}
select.field-control option {
display: flex;
align-items: center;
gap: 0.75rem;
min-block-size: 3rem;
padding-block: 0;
padding-inline: 1rem;
background: transparent;
color: var(--md-sys-color-on-surface);
font: var(--md-sys-typescale-body-lg);
letter-spacing: var(--md-sys-typescale-body-lg-tracking);
outline: none;
cursor: pointer;
}
@media (hover: hover) {
select.field-control option:hover {
background: color-mix(in srgb, var(--md-sys-color-on-surface) 8%, transparent);
}
}
select.field-control option:focus-visible {
background: color-mix(in srgb, var(--md-sys-color-on-surface) 10%, transparent);
}
select.field-control option:checked {
background: var(--md-sys-color-secondary-container);
color: var(--md-sys-color-on-secondary-container);
}
@media (hover: hover) {
select.field-control option:checked:hover {
background: color-mix(in srgb, var(--md-sys-color-on-secondary-container) 8%, var(--md-sys-color-secondary-container));
}
}
select.field-control option:checked:focus-visible {
background: color-mix(in srgb, var(--md-sys-color-on-secondary-container) 10%, var(--md-sys-color-secondary-container));
}
select.field-control option:disabled {
background: transparent;
color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
cursor: default;
}
/* The tick, at the row's end: the browser draws it before the label, and hides
it on every row but the chosen one. The Material Symbol, as a mask, so it
takes the row's ink. */
select.field-control option::checkmark {
content: "";
order: 1;
flex: none;
inline-size: 1.5rem;
block-size: 1.5rem;
margin-inline-start: auto;
background-color: currentColor;
mask: url("../../svg/symbols/outlined/check.svg") center / contain no-repeat;
}
}
+344
View File
@@ -0,0 +1,344 @@
/*
* M3's selection controls: the checkbox, the radio button and the switch (CheckboxTokens,
* RadioButtonTokens, SwitchTokens, androidx Compose Material 3, Apache-2.0).
*
* Each is a real `<input>` with its appearance removed and drawn over, so focus, the keyboard
* (Space; the arrow keys between radios), the form value, `wire:model` and what a screen reader
* announces stay the browser's. The row around it is a `<label>`, so its text is pressable too.
* Hooks are data attributes, not class names: `checkbox`, `radio` and `toggle` are daisyUI's, which
* the design guard rejects.
*
* [data-selection] the <label> row; `data-invalid` when the server has an error for it
* [data-checkbox] the 18px box, its state layer a 40px circle around it
* input, [data-check], [data-mixed]
* [data-radio] the 20px ring and its 10px dot
* input, [data-dot]
* [data-switch] the 52×32 track; `data-icons` = "both" or "selected"
* input, [data-handle] (with [data-on] and [data-off] icons)
*
* Every state layer is on-surface when unselected and primary when selected, 8% on hover (only
* where a pointer can hover) and 10% on focus and press; the focus indicator is the package's
* secondary ring. A disabled control is on-surface at 38% and has no state layer.
*/
@layer components {
[data-selection] {
cursor: pointer;
-webkit-tap-highlight-color: transparent;
}
[data-selection]:has(input:disabled) {
cursor: default;
}
[data-selection]:has(input:disabled) [data-selection-label] {
color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
}
[data-checkbox],
[data-radio] {
position: relative;
display: grid;
flex: none;
place-items: center;
}
[data-checkbox] > *,
[data-radio] > * {
grid-area: 1 / 1;
}
[data-checkbox]::before,
[data-radio]::before,
[data-handle]::before {
content: "";
position: absolute;
border-radius: var(--md-sys-shape-corner-full);
pointer-events: none;
transition: background-color var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
[data-checkbox] input,
[data-radio] input,
[data-switch] input {
margin: 0;
appearance: none;
cursor: inherit;
outline: none;
transition-property: background-color, border-color;
transition-duration: var(--md-sys-motion-effects-fast-duration);
transition-timing-function: var(--md-sys-motion-effects-fast);
}
/* The state layer. `--selection-ink` is what it is tinted with. */
[data-selection] {
--selection-ink: var(--md-sys-color-on-surface);
}
[data-selection]:has(input:checked),
[data-selection]:has(input:indeterminate) {
--selection-ink: var(--md-sys-color-primary);
}
[data-selection][data-invalid] {
--selection-ink: var(--md-sys-color-error);
}
@media (hover: hover) {
[data-selection]:hover:not(:has(input:disabled)) :is([data-checkbox], [data-radio], [data-handle])::before {
background-color: color-mix(in srgb, var(--selection-ink) 8%, transparent);
}
}
[data-selection]:has(input:focus-visible) :is([data-checkbox], [data-radio], [data-handle])::before,
[data-selection]:not(:has(input:disabled)):active :is([data-checkbox], [data-radio], [data-handle])::before {
background-color: color-mix(in srgb, var(--selection-ink) 10%, transparent);
}
[data-checkbox]:has(input:focus-visible)::before,
[data-radio]:has(input:focus-visible)::before {
outline: 3px solid var(--md-sys-color-secondary);
}
/* ---- Checkbox ---------------------------------------------------------------------------- */
[data-checkbox] {
width: 1.125rem;
height: 1.125rem;
}
[data-checkbox]::before {
inset: -0.6875rem;
}
[data-checkbox] input {
width: 1.125rem;
height: 1.125rem;
border: 2px solid var(--md-sys-color-on-surface-variant);
border-radius: 2px;
}
[data-checkbox] input:is(:checked, :indeterminate) {
border-color: var(--md-sys-color-primary);
background-color: var(--md-sys-color-primary);
}
[data-checkbox] :is([data-check], [data-mixed]) {
color: var(--md-sys-color-on-primary);
opacity: 0;
scale: 0.5;
pointer-events: none;
transition-property: opacity, scale;
transition-duration: var(--md-sys-motion-spatial-fast-duration);
transition-timing-function: var(--md-sys-motion-spatial-fast);
}
[data-checkbox] input:checked:not(:indeterminate) ~ [data-check],
[data-checkbox] input:indeterminate ~ [data-mixed] {
opacity: 1;
scale: 1;
}
[data-selection][data-invalid] [data-checkbox] input {
border-color: var(--md-sys-color-error);
}
[data-selection][data-invalid] [data-checkbox] input:is(:checked, :indeterminate) {
background-color: var(--md-sys-color-error);
}
[data-selection][data-invalid] [data-checkbox] :is([data-check], [data-mixed]) {
color: var(--md-sys-color-on-error);
}
[data-checkbox] input:disabled {
border-color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
}
[data-checkbox] input:disabled:is(:checked, :indeterminate) {
border-color: transparent;
background-color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
}
[data-checkbox] input:disabled ~ :is([data-check], [data-mixed]) {
color: var(--md-sys-color-surface);
}
/* ---- Radio button ------------------------------------------------------------------------ */
[data-radio] {
width: 1.25rem;
height: 1.25rem;
}
[data-radio]::before {
inset: -0.625rem;
}
[data-radio] input {
width: 1.25rem;
height: 1.25rem;
border: 2px solid var(--md-sys-color-on-surface-variant);
border-radius: var(--md-sys-shape-corner-full);
}
[data-radio] [data-dot] {
width: 0.625rem;
height: 0.625rem;
border-radius: var(--md-sys-shape-corner-full);
background-color: var(--md-sys-color-primary);
scale: 0;
pointer-events: none;
transition: scale var(--md-sys-motion-spatial-fast-duration) var(--md-sys-motion-spatial-fast);
}
[data-radio] input:checked {
border-color: var(--md-sys-color-primary);
}
[data-radio] input:checked ~ [data-dot] {
scale: 1;
}
[data-selection][data-invalid] [data-radio] input {
border-color: var(--md-sys-color-error);
}
[data-selection][data-invalid] [data-radio] [data-dot] {
background-color: var(--md-sys-color-error);
}
[data-radio] input:disabled {
border-color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
}
[data-radio] input:disabled ~ [data-dot] {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
}
/* ---- Switch -------------------------------------------------------------------------------
*
* The handle's centre is 16px from the track's start unselected and 36px selected; it is 16px
* across unselected, 24px with an icon or selected, and 28px while pressed. The positions below
* are those centres less half the size, measured inside the track's 2px outline. */
[data-switch] {
position: relative;
display: grid;
flex: none;
width: 3.25rem;
height: 2rem;
}
[data-switch] input {
width: 100%;
height: 100%;
border: 2px solid var(--md-sys-color-outline);
border-radius: var(--md-sys-shape-corner-full);
background-color: var(--md-sys-color-surface-container-highest);
}
[data-switch] input:focus-visible {
outline: 3px solid var(--md-sys-color-secondary);
outline-offset: 2px;
}
[data-handle] {
--handle: 1rem;
position: absolute;
top: 50%;
inset-inline-start: calc(1rem - var(--handle) / 2);
display: grid;
place-items: center;
width: var(--handle);
height: var(--handle);
translate: 0 -50%;
border-radius: var(--md-sys-shape-corner-full);
background-color: var(--md-sys-color-outline);
color: var(--md-sys-color-surface-container-highest);
pointer-events: none;
transition-property: inset-inline-start, width, height, background-color;
transition-duration: var(--md-sys-motion-spatial-fast-duration);
transition-timing-function: var(--md-sys-motion-spatial-fast);
}
[data-handle]::before {
inset: 50% auto auto 50%;
width: 2.5rem;
height: 2.5rem;
translate: -50% -50%;
}
[data-handle] > svg {
grid-area: 1 / 1;
opacity: 0;
transition: opacity var(--md-sys-motion-effects-fast-duration) var(--md-sys-motion-effects-fast);
}
[data-switch][data-icons="both"] [data-handle] {
--handle: 1.5rem;
}
[data-switch][data-icons="both"] input:not(:checked) ~ [data-handle] [data-off],
[data-switch][data-icons] input:checked ~ [data-handle] [data-on] {
opacity: 1;
}
[data-switch] input:checked {
border-color: var(--md-sys-color-primary);
background-color: var(--md-sys-color-primary);
}
[data-switch] input:checked ~ [data-handle] {
--handle: 1.5rem;
inset-inline-start: calc(2.25rem - var(--handle) / 2);
background-color: var(--md-sys-color-on-primary);
color: var(--md-sys-color-on-primary-container);
}
[data-selection]:active [data-switch] input:not(:disabled) ~ [data-handle] {
--handle: 1.75rem;
}
@media (hover: hover) {
[data-selection]:hover [data-switch] input:not(:disabled) ~ [data-handle] {
background-color: var(--md-sys-color-on-surface-variant);
}
[data-selection]:hover [data-switch] input:checked:not(:disabled) ~ [data-handle] {
background-color: var(--md-sys-color-primary-container);
}
}
[data-switch] input:focus-visible ~ [data-handle],
[data-selection]:active [data-switch] input:not(:disabled) ~ [data-handle] {
background-color: var(--md-sys-color-on-surface-variant);
}
[data-switch] input:checked:focus-visible ~ [data-handle],
[data-selection]:active [data-switch] input:checked:not(:disabled) ~ [data-handle] {
background-color: var(--md-sys-color-primary-container);
}
[data-switch] input:disabled {
border-color: color-mix(in srgb, var(--md-sys-color-on-surface) 12%, transparent);
background-color: color-mix(in srgb, var(--md-sys-color-surface-container-highest) 12%, transparent);
}
[data-switch] input:disabled ~ [data-handle] {
background-color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
color: color-mix(in srgb, var(--md-sys-color-surface-container-highest) 38%, transparent);
}
[data-switch] input:disabled:checked {
border-color: transparent;
background-color: color-mix(in srgb, var(--md-sys-color-on-surface) 12%, transparent);
}
[data-switch] input:disabled:checked ~ [data-handle] {
background-color: var(--md-sys-color-surface);
color: color-mix(in srgb, var(--md-sys-color-on-surface) 38%, transparent);
}
}
+3
View File
@@ -22,6 +22,9 @@
@import './tokens/state.css'; @import './tokens/state.css';
@import './components/groups.css'; @import './components/groups.css';
@import './components/list.css'; @import './components/list.css';
@import './components/field.css';
@import './components/menu.css';
@import './components/selection.css';
@layer base { @layer base {
html { html {
+83
View File
@@ -0,0 +1,83 @@
/**
* What the form controls need from script, which is little: both are kept off Alpine so they work
* in any markup and before Alpine starts.
*
* `<x-textarea>` grows with its text. CSS does that where the browser can size a field to its
* content (`field-sizing: content`, components/field.css); elsewhere the height is set here from
* the scroll height, on every input and whenever a Livewire render or navigation puts a new value
* in.
*
* `<x-checkbox indeterminate>`: HTML has no attribute for a checkbox's mixed state, only the
* `indeterminate` property, so the component marks the input `data-indeterminate` and this keeps
* the property in step with the mark — when the page loads, and when a render adds or removes the
* mark. A person pressing the box clears the property as the browser always does; the mark stays
* until the server decides again.
*/
const GROWING = 'textarea[data-autogrow]'
const MIXED = 'input[type="checkbox"][data-indeterminate]'
const growsByItself = window.CSS?.supports?.('field-sizing', 'content') ?? false
function grow(textarea) {
textarea.style.height = 'auto'
textarea.style.height = `${textarea.scrollHeight + textarea.offsetHeight - textarea.clientHeight}px`
}
function growAll(root) {
if (! growsByItself) {
root.querySelectorAll(GROWING).forEach(grow)
}
}
function markAll(root) {
root.querySelectorAll(MIXED).forEach((input) => (input.indeterminate = true))
}
if (! growsByItself) {
document.addEventListener('input', (event) => {
if (event.target instanceof HTMLTextAreaElement && event.target.matches(GROWING)) {
grow(event.target)
}
})
document.addEventListener('livewire:init', () => {
// A render that only puts a new value in a textarea changes no attribute or node.
window.Livewire.hook('morphed', ({ el }) => growAll(el))
})
}
new MutationObserver((records) => {
for (const record of records) {
if (record.type === 'attributes') {
if (record.attributeName === 'data-indeterminate' && record.target instanceof HTMLInputElement) {
record.target.indeterminate = record.target.hasAttribute('data-indeterminate')
} else if (! growsByItself && record.target.matches(GROWING)) {
grow(record.target)
}
continue
}
for (const node of record.addedNodes) {
if (node.nodeType !== Node.ELEMENT_NODE) {
continue
}
for (const input of [node, ...node.querySelectorAll(MIXED)].filter((element) => element.matches(MIXED))) {
input.indeterminate = true
}
if (! growsByItself) {
;[node, ...node.querySelectorAll(GROWING)].filter((element) => element.matches(GROWING)).forEach(grow)
}
}
}
}).observe(document.documentElement, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['data-indeterminate', 'data-autogrow'],
})
markAll(document)
growAll(document)
+1
View File
@@ -17,3 +17,4 @@ import './progress.js'
import './list-rows.js' import './list-rows.js'
import './bottom-sheet.js' import './bottom-sheet.js'
import './carousel.js' import './carousel.js'
import './field.js'
@@ -0,0 +1,62 @@
{{-- A checkbox, M3's: an 18px box that fills with primary when ticked, in a 40px state layer.
The label and its hint sit beside it and are its accessible name — the whole row is the
`<label>`, so either can be pressed. `right` puts the box at the end of the row, for a setting
read left to right. `indeterminate` shows the mixed state of a "select all" whose items are
partly ticked: HTML has no attribute for it, so the input is marked `data-indeterminate` and
resources/js/field.js keeps the property in step, on load and after every morph. Errors are
read from the bag under the `wire:model` name. Every other attribute reaches the `<input>`
(resources/css/components/selection.css). --}}
@props([
'label' => null,
'hint' => null,
'right' => false,
'indeterminate' => false,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$id = $attributes->get('id') ?? 'check-'.substr(md5($model.'|'.$label.'|'.$attributes->get('value')), 0, 12);
$messages = $model !== null && isset($errors) ? \Illuminate\Support\Arr::flatten($errors->get($model)) : [];
@endphp
<div {{ $attributes->only(['class', 'wire:key'])->class(['min-w-0']) }}>
<label for="{{ $id }}" data-selection @if ($messages !== []) data-invalid @endif @class([
'flex gap-4',
'items-start' => filled($hint),
'items-center' => blank($hint),
'flex-row-reverse justify-between' => $right,
])>
<span data-checkbox @class(['mt-[3px]' => filled($hint)])>
<input
{{ $attributes->except(['class', 'id', 'wire:key']) }}
id="{{ $id }}"
type="checkbox"
@if ($indeterminate) data-indeterminate @endif
@if ($messages !== []) aria-invalid="true" aria-describedby="{{ $id }}-support" @endif
/>
<x-icon name="check" class="size-4" data-check />
<x-icon name="remove" class="size-4" data-mixed />
</span>
@if (filled($label) || filled($hint))
<span class="min-w-0">
@if (filled($label))
<span class="block type-body-lg text-on-surface" data-selection-label>{{ $label }}</span>
@endif
@if (filled($hint))
<span class="mt-0.5 block type-body-sm text-on-surface-variant">{{ $hint }}</span>
@endif
</span>
@endif
</label>
@if ($messages !== [])
<div id="{{ $id }}-support" class="mt-1 type-body-sm text-error" role="alert">
@foreach ($messages as $message)
<p>{{ $message }}</p>
@endforeach
</div>
@endif
</div>
@@ -0,0 +1,82 @@
{{-- The chrome of M3's text fields, around whichever control is in the slot.
Not used at call sites: `<x-input>`, `<x-password>`, `<x-textarea>`, `<x-select>`, `<x-file>`
and the pickers wrap their control in it, so a form reads as one family. The states — the
label resting or floating, the notch, focus, disabled, required — are selectors in
resources/css/components/field.css, which explains the anatomy; the only state this file
decides is `data-invalid`, because only the server knows that.
`variant` is M3's two: `outlined` (a notched outline) and `filled` (a surface-container-highest
box with an indicator line); without it, `config('livewire-material.fields.variant')`. A field
with a label is a form field, M3's 56px. A field without one is a control in a toolbar or an
editor row, and is given `size="sm"` (40px, a button's height) or `size="xs"` (32px). The
error replaces the hint rather than stacking under it, as M3 has it.
`class` from the call site lands on the outermost element, never the control, so a margin or
a width is safe here. --}}
@props([
'id',
'label' => null,
'hint' => null,
'hintClass' => null,
'messages' => [],
'icon' => null,
'prefix' => null,
'suffix' => null,
'size' => 'md',
'variant' => null,
'floated' => false,
'mono' => false,
])
@php
$variant = in_array($variant, ['outlined', 'filled'], true)
? $variant
: (config('livewire-material.fields.variant') === 'filled' ? 'filled' : 'outlined');
@endphp
<div
{{ $attributes->class(['field']) }}
data-variant="{{ $variant }}"
data-size="{{ in_array($size, ['sm', 'xs'], true) ? $size : 'md' }}"
@if ($messages !== []) data-invalid @endif
@if ($floated) data-floated @endif
@if ($mono) data-mono @endif
>
<div class="field-box">
@if ($icon)
<x-icon :name="$icon" class="field-icon size-(--field-icon)" />
@endif
@if (filled($prefix))
<span class="field-affix">{{ $prefix }}</span>
@endif
{{ $slot }}
@if (filled($suffix))
<span class="field-affix">{{ $suffix }}</span>
@endif
{{ $trailing ?? '' }}
<fieldset aria-hidden="true" class="field-outline">
<legend>@if (filled($label))<span>{{ $label }}</span>@endif</legend>
</fieldset>
@if (filled($label))
<label for="{{ $id }}" class="field-label">{{ $label }}</label>
@endif
</div>
@if ($messages !== [])
<div id="{{ $id }}-support" class="field-support" role="alert">
@foreach ($messages as $message)
<p>{{ $message }}</p>
@endforeach
</div>
@elseif (filled($hint))
<p id="{{ $id }}-support" @class(array_filter(['field-support', $hintClass]))>{{ $hint }}</p>
@endif
</div>
+38
View File
@@ -0,0 +1,38 @@
{{-- A file picker, in the text field's chrome (resources/views/components/field.blade.php).
M3 has no file field, and building one would redo what the browser's input already does the
picker, a file dropped on it, the keyboard, what a screen reader announces, the `change` a
Livewire upload listens for. So the input stays native, its label always floats (the button
stands where a resting label would), and only its `::file-selector-button` is restyled: a tonal
pill, so it reads as the thing to press (resources/css/components/field.css).
The browser's own line beside the button ("No file chosen", "3 files") is drawn transparent:
it cannot be truncated or wrapped, and the caller shows what was chosen anyway, as previews. A
screen reader still hears it. The errors are the model's and, for a `multiple` input, each
file's (`photos.*`): a file refused for its size belongs under this field as much as the
batch's own count does. `label`, `hint`, `variant`; every other attribute reaches the `<input>`. --}}
@props([
'label' => null,
'hint' => null,
'variant' => null,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$id = $attributes->get('id') ?? 'field-'.substr(md5('file|'.$model.'|'.$label), 0, 12);
$messages = $model !== null && isset($errors)
? array_values(array_unique(\Illuminate\Support\Arr::flatten([$errors->get($model), $errors->get($model.'.*')])))
: [];
@endphp
<x-field :$id :$label :$hint :$messages :$variant floated :class="$attributes->get('class')">
<input
{{ $attributes->except(['class', 'id', 'type']) }}
type="file"
id="{{ $id }}"
@if ($messages !== []) aria-invalid="true" @endif
@if ($messages !== [] || filled($hint)) aria-describedby="{{ $id }}-support" @endif
class="field-control"
/>
</x-field>
+26
View File
@@ -0,0 +1,26 @@
{{-- A form: its fields in one column, and its actions at the foot.
`gap-4` between fields, because a text field floats its label half above its outline: any less
and the hint under one field runs into the label of the next. The `actions` slot takes a class
of its own; `separator` draws a divider above it.
`grid-cols-1`, because a bare `grid` has no columns and its implicit one floors at the
content's min-content: on a phone a wide field would push the form past its column. --}}
@props([
'separator' => false,
])
<form {{ $attributes->class(['grid grid-cols-1 auto-rows-min gap-4']) }}>
{{ $slot }}
@isset($actions)
@if ($separator)
<x-divider />
@endif
<div {{ $actions->attributes->class(['flex flex-wrap items-center justify-end gap-2']) }}>
{{ $actions }}
</div>
@endisset
</form>
@@ -0,0 +1,79 @@
{{-- A text field: M3's outlined or filled one (resources/views/components/field.blade.php).
`label`, `hint`, leading `icon`, trailing `icon-right`, `prefix` and `suffix` (text beside the
value, such as a currency or a unit), `variant`, `size` for unlabelled controls in toolbars,
and `mono` for a field that holds code. `clearable` adds a trailing button that empties the
field once it holds something; `copyable` one that copies its value and says so in a snackbar
(a share link, a token). Every other attribute reaches the `<input>`: `type`, `min`, `step`,
`readonly`, `wire:model` and the rest. Errors are read from the bag under the `wire:model` name.
The placeholder is a single space when none is given, because the label can only tell an
empty field from a filled one through `:placeholder-shown`. With a label, a real placeholder
shows only while the field has focus — until then the label stands where it would be. --}}
@props([
'label' => null,
'hint' => null,
'hintClass' => null,
'icon' => null,
'iconRight' => null,
'prefix' => null,
'suffix' => null,
'clearable' => false,
'copyable' => false,
'size' => 'md',
'variant' => null,
'mono' => false,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$placeholder = filled($attributes->get('placeholder')) ? $attributes->get('placeholder') : ' ';
$id = $attributes->get('id') ?? 'field-'.substr(md5($model.'|'.$label.'|'.$placeholder), 0, 12);
$messages = $model !== null && isset($errors) ? \Illuminate\Support\Arr::flatten($errors->get($model)) : [];
@endphp
<x-field :$id :$label :$hint :hint-class="$hintClass" :$messages :$icon :$prefix :$suffix :$size :$variant :$mono :class="$attributes->get('class')" :data-readonly="$attributes->get('readonly') ? '' : null">
<input
{{ $attributes->except(['class', 'id', 'placeholder'])->merge(['type' => 'text']) }}
id="{{ $id }}"
placeholder="{{ $placeholder }}"
@if ($messages !== []) aria-invalid="true" @endif
@if ($messages !== [] || filled($hint)) aria-describedby="{{ $id }}-support" @endif
class="field-control"
/>
@if ($clearable || $copyable || $iconRight)
<x-slot:trailing>
@if ($clearable)
<button
type="button"
x-data
x-on:click="const control = $el.closest('.field').querySelector('.field-control'); control.value = ''; control.dispatchEvent(new Event('input', { bubbles: true })); control.dispatchEvent(new Event('change', { bubbles: true })); control.focus();"
class="field-trailing field-clear field-button"
aria-label="{{ __('Clear') }}"
data-field-clear
>
<x-icon name="close" class="size-(--field-icon)" />
</button>
@endif
@if ($copyable)
<button
type="button"
x-data
x-on:click="navigator.clipboard.writeText($el.closest('.field').querySelector('.field-control').value).then(() => window.materialToast(@js(__('Copied to the clipboard')), { type: 'success' }))"
class="field-trailing field-button"
aria-label="{{ __('Copy') }}"
data-field-copy
>
<x-icon name="content_copy" class="size-(--field-icon)" />
</button>
@endif
@if ($iconRight)
<x-icon :name="$iconRight" class="field-trailing size-(--field-icon)" />
@endif
</x-slot:trailing>
@endif
</x-field>
@@ -0,0 +1,50 @@
{{-- A password field, with M3's trailing eye to show what was typed.
The eye flips the control's `type` and nothing else, so the value never leaves the field and a
password manager still sees a password input on load. Its label says what pressing it will do.
`label`, `hint`, `icon`, `variant`, `size`; every other attribute reaches the `<input>`
(`autocomplete="current-password"`, `wire:model`). --}}
@props([
'label' => null,
'hint' => null,
'hintClass' => null,
'icon' => null,
'size' => 'md',
'variant' => null,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$id = $attributes->get('id') ?? 'field-'.substr(md5($model.'|'.$label.'|password'), 0, 12);
$messages = $model !== null && isset($errors) ? \Illuminate\Support\Arr::flatten($errors->get($model)) : [];
@endphp
<x-field :$id :$label :$hint :hint-class="$hintClass" :$messages :$icon :$size :$variant :class="$attributes->get('class')" x-data="{ shown: false }">
<input
{{ $attributes->except(['class', 'id', 'type', 'placeholder']) }}
id="{{ $id }}"
type="password"
x-bind:type="shown ? 'text' : 'password'"
placeholder="{{ filled($attributes->get('placeholder')) ? $attributes->get('placeholder') : ' ' }}"
@if ($messages !== []) aria-invalid="true" @endif
@if ($messages !== [] || filled($hint)) aria-describedby="{{ $id }}-support" @endif
class="field-control"
/>
<x-slot:trailing>
<button
type="button"
x-on:click="shown = ! shown"
x-bind:aria-label="shown ? @js(__('Hide password')) : @js(__('Show password'))"
x-bind:aria-pressed="shown"
aria-label="{{ __('Show password') }}"
aria-pressed="false"
class="field-trailing field-button"
data-field-reveal
>
<x-icon name="visibility" class="size-(--field-icon)" x-show="! shown" />
<x-icon name="visibility_off" class="size-(--field-icon)" x-show="shown" x-cloak />
</button>
</x-slot:trailing>
</x-field>
@@ -0,0 +1,78 @@
{{-- One choice from a few, each with room for a line of explanation: M3's radio buttons.
A `<fieldset>` whose legend is the question, so a screen reader reads the group's name with each
option, and native radios sharing a name, so the arrow keys move between them. `options` as
`['id' => …, 'name' => …, 'hint' => …]` (`'disabled' => true` greys one out), `option-value`,
`option-label` and `option-hint` to read other keys, `inline` to lay them in a row from `sm`, and
`value` for the option chosen when the page loads (with `wire:model`, Livewire sets it).
Errors are read from the bag under the `wire:model` name
(resources/css/components/selection.css). --}}
@props([
'label' => null,
'hint' => null,
'options' => [],
'optionValue' => 'id',
'optionLabel' => 'name',
'optionHint' => 'hint',
'inline' => false,
'value' => null,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$name = $attributes->get('name') ?? $model ?? 'radio-'.substr(md5($label.'|'.json_encode($options)), 0, 12);
$id = 'radio-'.substr(md5($name.'|'.$label), 0, 12);
$messages = $model !== null && isset($errors) ? \Illuminate\Support\Arr::flatten($errors->get($model)) : [];
@endphp
<fieldset
{{ $attributes->only(['class', 'wire:key'])->class(['min-w-0']) }}
@if ($messages !== [] || filled($hint)) aria-describedby="{{ $id }}-support" @endif
>
@if (filled($label))
<legend class="mb-3 type-label-lg text-on-surface-variant">{{ $label }}</legend>
@endif
<div @class(['grid gap-4', 'sm:flex sm:flex-wrap sm:gap-x-6' => $inline])>
@foreach ($options as $option)
@php($optionHintText = data_get($option, $optionHint))
<label data-selection @if ($messages !== []) data-invalid @endif @class([
'flex gap-4',
'items-start' => filled($optionHintText),
'items-center' => blank($optionHintText),
])>
<span data-radio @class(['mt-0.5' => filled($optionHintText)])>
<input
{{ $attributes->except(['class', 'wire:key', 'name', 'id']) }}
type="radio"
name="{{ $name }}"
value="{{ data_get($option, $optionValue) }}"
@disabled(data_get($option, 'disabled'))
@checked($value !== null && (string) $value === (string) data_get($option, $optionValue))
@if ($messages !== []) aria-invalid="true" @endif
/>
<span data-dot></span>
</span>
<span class="min-w-0">
<span class="block type-body-lg text-on-surface" data-selection-label>{{ data_get($option, $optionLabel) }}</span>
@if (filled($optionHintText))
<span class="mt-0.5 block type-body-sm text-on-surface-variant">{{ $optionHintText }}</span>
@endif
</span>
</label>
@endforeach
</div>
@if ($messages !== [])
<div id="{{ $id }}-support" class="mt-2 type-body-sm text-error" role="alert">
@foreach ($messages as $message)
<p>{{ $message }}</p>
@endforeach
</div>
@elseif (filled($hint))
<p id="{{ $id }}-support" class="mt-2 type-body-sm text-on-surface-variant">{{ $hint }}</p>
@endif
</fieldset>
@@ -0,0 +1,57 @@
{{-- A select: the native `<select>`, drawn as M3's exposed dropdown menu.
Native on purpose: the keyboard, type-to-find, the screen reader and the form value are the
browser's, and `wire:model` binds to it as to any select. Where the browser has the
customizable select (`appearance: base-select`) its open list is M3's menu, under the field
and as wide (resources/css/components/menu.css); elsewhere the native list stands in. So the
options stay plain text: the native list could show nothing more. A select always shows a
value, so its label always floats.
`options` as a list of `['id' => …, 'name' => …]` (`'disabled' => true` greys one out),
`option-value` and `option-label` to read other keys, and a `placeholder` that becomes the
first option, valued `placeholder-value` (empty by default). Or pass `<option>`s in the slot.
`label`, `hint`, `icon`, `variant`, `size`. --}}
@props([
'label' => null,
'hint' => null,
'hintClass' => null,
'icon' => null,
'options' => [],
'optionValue' => 'id',
'optionLabel' => 'name',
'placeholder' => null,
'placeholderValue' => null,
'size' => 'md',
'variant' => null,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$id = $attributes->get('id') ?? 'field-'.substr(md5($model.'|'.$label.'|select'), 0, 12);
$messages = $model !== null && isset($errors) ? \Illuminate\Support\Arr::flatten($errors->get($model)) : [];
@endphp
<x-field :$id :$label :$hint :hint-class="$hintClass" :$messages :$icon :$size :$variant floated :class="$attributes->get('class')">
<select
{{ $attributes->except(['class', 'id']) }}
id="{{ $id }}"
@if ($messages !== []) aria-invalid="true" @endif
@if ($messages !== [] || filled($hint)) aria-describedby="{{ $id }}-support" @endif
class="field-control"
>
@if (filled($placeholder))
<option value="{{ $placeholderValue }}">{{ $placeholder }}</option>
@endif
@foreach ($options as $option)
<option value="{{ data_get($option, $optionValue) }}" @disabled(data_get($option, 'disabled'))>{{ data_get($option, $optionLabel) }}</option>
@endforeach
{{ $slot }}
</select>
<x-slot:trailing>
<x-icon name="arrow_drop_down" class="field-trailing field-arrow size-(--field-icon)" />
</x-slot:trailing>
</x-field>
@@ -0,0 +1,39 @@
{{-- A multi-line field: the text field, grown to its content.
It starts at `rows` lines (3) and grows with what is typed up to `max-rows`, then scrolls;
`:autogrow="false"` keeps it at `rows` and lets it be resized by hand, vertically only, so a
form's column never moves. The label rests on the first line rather than in the middle of the
box. `label`, `hint`, `variant`; every other attribute reaches the `<textarea>`. --}}
@props([
'label' => null,
'hint' => null,
'hintClass' => null,
'variant' => null,
'rows' => 3,
'maxRows' => null,
'autogrow' => true,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$placeholder = filled($attributes->get('placeholder')) ? $attributes->get('placeholder') : ' ';
$id = $attributes->get('id') ?? 'field-'.substr(md5($model.'|'.$label.'|textarea'), 0, 12);
$messages = $model !== null && isset($errors) ? \Illuminate\Support\Arr::flatten($errors->get($model)) : [];
@endphp
<x-field :$id :$label :$hint :hint-class="$hintClass" :$messages :$variant :class="$attributes->get('class')" :data-readonly="$attributes->get('readonly') ? '' : null">
<textarea
{{ $attributes->except(['class', 'id', 'placeholder']) }}
id="{{ $id }}"
rows="{{ (int) $rows }}"
placeholder="{{ $placeholder }}"
@if ($autogrow)
data-autogrow
style="--field-rows: {{ (int) $rows }};@if ($maxRows) --field-max-rows: {{ (int) $maxRows }};@endif"
@endif
@if ($messages !== []) aria-invalid="true" @endif
@if ($messages !== [] || filled($hint)) aria-describedby="{{ $id }}-support" @endif
class="field-control"
></textarea>
</x-field>
@@ -0,0 +1,56 @@
{{-- A switch, M3's: a 52×32 track whose handle grows and slides across when it turns on.
On a real checkbox with `role="switch"`, so it is focusable, announced as on or off, and takes
Space from the keyboard; the handle is drawn beside it. `label` and `hint` sit beside it and are
its name — a switch without `label` needs an `aria-label`. `right` puts it at the end of the
row, where a setting's switch usually is. `icons` draws a check on the handle when on and a
cross when off; `icons="selected"` only the check. Every other attribute reaches the `<input>`
(resources/css/components/selection.css). --}}
@props([
'label' => null,
'hint' => null,
'right' => false,
'icons' => false,
])
@php
$model = $attributes->whereStartsWith('wire:model')->first();
$id = $attributes->get('id') ?? 'switch-'.substr(md5($model.'|'.$label), 0, 12);
$icons = $icons === 'selected' ? 'selected' : ($icons ? 'both' : null);
@endphp
<div {{ $attributes->only(['class', 'wire:key'])->class(['min-w-0']) }}>
<label for="{{ $id }}" data-selection @class([
'flex gap-4',
'items-start' => filled($hint),
'items-center' => blank($hint),
'flex-row-reverse justify-between' => $right,
])>
<span data-switch @if ($icons) data-icons="{{ $icons }}" @endif>
<input
{{ $attributes->except(['class', 'id', 'wire:key']) }}
id="{{ $id }}"
type="checkbox"
role="switch"
/>
<span data-handle>
@if ($icons)
<x-icon name="check" class="size-4" data-on />
<x-icon name="close" class="size-4" data-off />
@endif
</span>
</span>
@if (filled($label) || filled($hint))
<span class="min-w-0">
@if (filled($label))
<span class="block type-body-lg text-on-surface" data-selection-label>{{ $label }}</span>
@endif
@if (filled($hint))
<span class="mt-0.5 block type-body-sm text-on-surface-variant">{{ $hint }}</span>
@endif
</span>
@endif
</label>
</div>
+1
View File
@@ -18,5 +18,6 @@
@include('livewire-material::showcase.sections.progress') @include('livewire-material::showcase.sections.progress')
@include('livewire-material::showcase.sections.containment') @include('livewire-material::showcase.sections.containment')
@include('livewire-material::showcase.sections.carousel') @include('livewire-material::showcase.sections.carousel')
@include('livewire-material::showcase.sections.fields')
</main> </main>
@endsection @endsection
+1 -1
View File
@@ -18,7 +18,7 @@
<a href="{{ route('livewire-material.showcase') }}" class="shrink-0 type-title-lg max-sm:hidden">Livewire Material</a> <a href="{{ route('livewire-material.showcase') }}" class="shrink-0 type-title-lg max-sm:hidden">Livewire Material</a>
<nav class="-my-2 flex min-w-0 flex-1 gap-x-4 overflow-x-auto py-2 whitespace-nowrap type-label-lg text-on-surface-variant [scrollbar-width:none]" aria-label="Sections"> <nav class="-my-2 flex min-w-0 flex-1 gap-x-4 overflow-x-auto py-2 whitespace-nowrap type-label-lg text-on-surface-variant [scrollbar-width:none]" aria-label="Sections">
@foreach (['colour' => 'Colour', 'type' => 'Type', 'shape' => 'Shape', 'elevation' => 'Elevation', 'motion' => 'Motion', 'icons' => 'Icons', 'buttons' => 'Buttons', 'menus' => 'Menus', 'communication' => 'Communication', 'progress' => 'Progress', 'containment' => 'Containment', 'carousel' => 'Carousel'] as $anchor => $section) @foreach (['colour' => 'Colour', 'type' => 'Type', 'shape' => 'Shape', 'elevation' => 'Elevation', 'motion' => 'Motion', 'icons' => 'Icons', 'buttons' => 'Buttons', 'menus' => 'Menus', 'communication' => 'Communication', 'progress' => 'Progress', 'containment' => 'Containment', 'carousel' => 'Carousel', 'fields' => 'Fields'] as $anchor => $section)
<a href="#{{ $anchor }}" class="rounded-corner-xs hover:text-on-surface focus-ring">{{ $section }}</a> <a href="#{{ $anchor }}" class="rounded-corner-xs hover:text-on-surface focus-ring">{{ $section }}</a>
@endforeach @endforeach
</nav> </nav>
@@ -0,0 +1,130 @@
@php
$examples = [
'Outlined and filled text fields' => <<<'BLADE'
<div class="grid w-full gap-6 md:grid-cols-2">
<div class="grid content-start gap-4">
<x-input label="Share name" hint="Recipients see this name" />
<x-input label="Recipient" icon="mail" type="email" placeholder="name@example.com" clearable value="anna@example.com" />
<x-input label="Price" prefix="CHF" suffix="per month" type="number" value="12" />
<x-input label="Share link" value="https://sealshare.test/s/8f3k2" readonly copyable />
<x-password label="Password" hint="At least 12 characters" />
<x-input label="Disabled" value="Not editable" disabled />
</div>
<div class="grid content-start gap-4">
<x-input variant="filled" label="Share name" hint="Recipients see this name" />
<x-input variant="filled" label="Recipient" icon="mail" type="email" placeholder="name@example.com" clearable value="anna@example.com" />
<x-input variant="filled" label="Price" prefix="CHF" suffix="per month" type="number" value="12" />
<x-input variant="filled" label="Search" icon="search" icon-right="mic" />
<x-password variant="filled" label="Password" hint="At least 12 characters" />
<x-input variant="filled" label="Disabled" value="Not editable" disabled />
</div>
</div>
BLADE,
'Errors, required and sizes' => <<<'BLADE'
<div class="grid w-full gap-6 md:grid-cols-2">
<div class="grid content-start gap-4">
<x-input label="Email" required />
<x-field id="showcase-error" label="Expiry" :messages="['Choose a date in the future.']">
<input id="showcase-error" class="field-control" value="2020-01-01" aria-invalid="true" />
</x-field>
</div>
<div class="grid content-start gap-4">
<x-field id="showcase-error-filled" variant="filled" label="Expiry" :messages="['Choose a date in the future.']">
<input id="showcase-error-filled" class="field-control" value="2020-01-01" aria-invalid="true" />
</x-field>
<div class="flex flex-wrap items-center gap-3">
<x-input size="sm" icon="search" placeholder="Filter" aria-label="Filter" class="w-48" />
<x-input size="xs" placeholder="Find" aria-label="Find" class="w-36" />
</div>
</div>
</div>
BLADE,
'Textarea and select' => <<<'BLADE'
<div class="grid w-full gap-6 md:grid-cols-2">
<div class="grid content-start gap-4">
<x-textarea label="Message" hint="Grows as you type, up to six lines" rows="2" max-rows="6" />
<x-select label="Expires after" :options="[['id' => 1, 'name' => '1 hour'], ['id' => 24, 'name' => '1 day'], ['id' => 168, 'name' => '7 days'], ['id' => 720, 'name' => '30 days', 'disabled' => true]]" />
<x-file label="Attachments" multiple hint="Up to 2 GB" />
</div>
<div class="grid content-start gap-4">
<x-textarea variant="filled" label="Message" hint="Grows as you type, up to six lines" rows="2" max-rows="6" />
<x-select variant="filled" label="Expires after" icon="schedule" placeholder="Choose…" :options="[['id' => 1, 'name' => '1 hour'], ['id' => 24, 'name' => '1 day'], ['id' => 168, 'name' => '7 days']]" />
<x-file variant="filled" label="Attachments" multiple />
</div>
</div>
BLADE,
'Checkboxes' => <<<'BLADE'
<div class="grid w-full gap-6 md:grid-cols-3">
<div class="grid content-start gap-4">
<x-checkbox label="Notify me on download" checked />
<x-checkbox label="Select all files" indeterminate />
<x-checkbox label="Burn after reading" hint="The share is deleted after its first download" />
</div>
<div class="grid content-start gap-4">
<x-checkbox label="Disabled" disabled />
<x-checkbox label="Disabled and ticked" checked disabled />
<x-checkbox label="Disabled, partly ticked" indeterminate disabled />
</div>
<div class="grid content-start gap-4">
<x-checkbox label="Show in the dashboard" right />
<x-checkbox aria-label="Unlabelled" />
</div>
</div>
BLADE,
'Radio buttons' => <<<'BLADE'
<div class="grid w-full gap-6 md:grid-cols-2">
<x-radio label="Who can open the link" name="showcase-audience" value="password" :options="[['id' => 'anyone', 'name' => 'Anyone with the link'], ['id' => 'password', 'name' => 'Anyone with the password', 'hint' => 'Share the password separately'], ['id' => 'team', 'name' => 'My team only', 'disabled' => true]]" />
<x-radio label="Theme" name="showcase-radio-theme" value="system" inline :options="[['id' => 'light', 'name' => 'Light'], ['id' => 'dark', 'name' => 'Dark'], ['id' => 'system', 'name' => 'System']]" hint="Inline from sm" />
</div>
BLADE,
'Switches' => <<<'BLADE'
<div class="grid w-full gap-6 md:grid-cols-3">
<div class="grid content-start gap-4">
<x-toggle label="Email notifications" checked />
<x-toggle label="Weekly summary" />
</div>
<div class="grid content-start gap-4">
<x-toggle label="With icons" icons checked />
<x-toggle label="With icons, off" icons />
<x-toggle label="Only the check" icons="selected" checked />
</div>
<div class="grid content-start gap-4">
<x-toggle label="Disabled" disabled />
<x-toggle label="Disabled, on" checked disabled icons />
<x-toggle label="Public link" hint="Anyone with the link can open it" right />
</div>
</div>
BLADE,
'A form' => <<<'BLADE'
<x-card variant="outlined" class="w-full max-w-xl">
<x-form x-on:submit.prevent="materialToast('Share created', { type: 'success' })" separator>
<x-input label="Share name" required />
<x-textarea label="Message for recipients" />
<x-select label="Expires after" :options="[['id' => 24, 'name' => '1 day'], ['id' => 168, 'name' => '7 days']]" />
<x-toggle label="Protect with a password" right />
<x-slot:actions>
<x-button label="Cancel" type="reset" />
<x-button label="Create share" variant="filled" type="submit" />
</x-slot:actions>
</x-form>
</x-card>
BLADE,
];
@endphp
<section id="fields" class="scroll-mt-24 space-y-6">
<h2 class="type-headline-md">Text fields and selection</h2>
<p class="max-w-3xl type-body-md text-on-surface-variant">
<code>&lt;x-input&gt;</code>, <code>&lt;x-password&gt;</code>, <code>&lt;x-textarea&gt;</code>, <code>&lt;x-select&gt;</code>, <code>&lt;x-file&gt;</code>
(all on <code>&lt;x-field&gt;</code>, outlined or filled), <code>&lt;x-checkbox&gt;</code>, <code>&lt;x-radio&gt;</code>, <code>&lt;x-toggle&gt;</code> and <code>&lt;x-form&gt;</code>.
</p>
@foreach ($examples as $title => $code)
<x-showcase::example :$title :$code />
@endforeach
</section>
+185
View File
@@ -0,0 +1,185 @@
<?php
use Illuminate\Support\Facades\Blade;
use Illuminate\Support\Facades\Route;
use Livewire\Component;
use Livewire\Livewire;
class FieldProbe extends Component
{
public string $name = '';
public string $hours = '24';
/** @var list<string> */
public array $files = [];
public string $audience = 'anyone';
public bool $public = false;
public string $message = '';
public function save(): void
{
$this->validate(['name' => 'required']);
}
public function render(): string
{
return <<<'BLADE'
<div class="grid max-w-md gap-4 p-4">
<p>name: <span id="name">{{ $name }}</span></p>
<p>hours: <span id="hours">{{ $hours }}</span></p>
<p>files: <span id="files">{{ implode(',', $files) }}</span></p>
<p>audience: <span id="audience">{{ $audience }}</span></p>
<p>public: <span id="public-state">{{ var_export($public, true) }}</span></p>
<x-input id="name-field" label="Share name" wire:model.live="name" clearable copyable />
<x-password id="password-field" label="Password" />
<x-select id="hours-field" label="Expires" wire:model.live="hours" :options="[['id' => '1', 'name' => '1 hour'], ['id' => '24', 'name' => '1 day']]" />
<x-checkbox id="all" label="All files" :indeterminate="count($files) > 0 && count($files) < 3" />
@foreach (['a', 'b', 'c'] as $file)
<x-checkbox id="file-{{ $file }}" :label="'File '.$file" value="{{ $file }}" wire:model.live="files" wire:key="file-{{ $file }}" />
@endforeach
<x-radio label="Audience" wire:model.live="audience" :options="[['id' => 'anyone', 'name' => 'Anyone'], ['id' => 'team', 'name' => 'Team']]" />
<x-toggle id="public" label="Public" wire:model.live="public" />
<x-textarea id="message" label="Message" rows="2" max-rows="4" wire:model="message" />
<x-button label="Save" wire:click="save" />
</div>
BLADE;
}
}
function fieldProbe()
{
Livewire::component('field-probe', FieldProbe::class);
Route::middleware('web')->get('/field-probe', fn () => Blade::render(<<<'BLADE'
<!DOCTYPE html>
<html>
<head>
<x-theme-script />
@vite(config('livewire-material.showcase.vite'))
@livewireStyles
</head>
<body class="bg-surface">
<livewire:field-probe />
<x-toast />
@livewireScripts
</body>
</html>
BLADE));
return visit('/field-probe')->waitForEvent('networkidle')
->assertScript("document.readyState === 'complete' && typeof window.Alpine !== 'undefined' && typeof window.Livewire !== 'undefined'");
}
it('floats the label while the field has focus or holds a value', function () {
$label = "getComputedStyle(document.querySelector('label[for=\"name-field\"]')).fontSize";
$page = fieldProbe()->assertScript("{$label} === '16px'");
$page->click('#name-field')->assertScript("{$label} === '12px'");
$page->type('#name-field', 'Holiday')
->assertSeeIn('#name', 'Holiday');
$page->click('#password-field')->assertScript("{$label} === '12px'");
});
it('clears a field and tells Livewire', function () {
fieldProbe()
->type('#name-field', 'Holiday')
->assertSeeIn('#name', 'Holiday')
->click('[data-field-clear]')
->assertScript("document.querySelector('#name-field').value === ''")
->assertScript("document.querySelector('#name').textContent === ''")
->assertScript("document.activeElement.id === 'name-field'");
});
it('copies a field\'s value and says so', function () {
$page = fieldProbe()->type('#name-field', 'Holiday');
$page->script("window.eval(\"Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async (text) => { window.copied = text } } })\")");
$page->click('[data-field-copy]')
->assertScript("window.copied === 'Holiday'")
->assertSee('Copied to the clipboard');
});
it('shows and hides a password', function () {
fieldProbe()
->type('#password-field', 'secret')
->click('[data-field-reveal]')
->assertScript("document.querySelector('#password-field').type === 'text'")
->assertAttribute('[data-field-reveal]', 'aria-pressed', 'true')
->click('[data-field-reveal]')
->assertScript("document.querySelector('#password-field').type === 'password'");
});
it('shows the server\'s error in place of the hint', function () {
fieldProbe()
->click('button:has-text("Save")')
->assertSee('The name field is required.')
->assertAttribute('#name-field', 'aria-invalid', 'true')
->assertScript("document.querySelector('#name-field').closest('.field').hasAttribute('data-invalid')");
});
it('binds a select to Livewire', function () {
fieldProbe()
->select('#hours-field', '1')
->assertSeeIn('#hours', '1');
});
it('keeps a partly ticked checkbox in step with the server', function () {
$all = "document.querySelector('#all')";
$page = fieldProbe()->assertScript("! {$all}.indeterminate");
$page->click('label[for="file-a"]')
->assertSeeIn('#files', 'a')
->assertScript("{$all}.hasAttribute('data-indeterminate') && {$all}.indeterminate");
$page->click('label[for="file-b"]')
->click('label[for="file-c"]')
->assertSeeIn('#files', 'a,b,c')
->assertScript("! {$all}.hasAttribute('data-indeterminate') && ! {$all}.indeterminate");
});
it('moves between radio buttons with the arrow keys', function () {
fieldProbe()
->keys('input[type="radio"][value="anyone"]', 'ArrowDown')
->assertSeeIn('#audience', 'team')
->assertScript("document.querySelector('input[type=\"radio\"][value=\"team\"]').checked");
});
it('turns a switch on from the keyboard and from its label', function () {
$page = fieldProbe()
->keys('#public', 'Space')
->assertSeeIn('#public-state', 'true');
$page->click('label[for="public"]')
->assertSeeIn('#public-state', 'false')
->assertAttribute('#public', 'role', 'switch');
});
it('grows a textarea with its text up to its maximum', function () {
$height = "document.querySelector('#message').getBoundingClientRect().height";
$page = fieldProbe();
$rows = $page->script("({$height})");
$page->type('#message', "one\ntwo\nthree")
->assertScript("({$height}) > {$rows}");
$three = $page->script("({$height})");
$page->type('#message', "one\ntwo\nthree\nfour\nfive\nsix\nseven")
->assertScript("Math.abs(({$height}) - ({$three} + 24)) < 2")
->assertScript("document.querySelector('#message').scrollHeight > document.querySelector('#message').clientHeight");
});
+149
View File
@@ -0,0 +1,149 @@
<?php
it('draws an outlined field with a notched label unless told otherwise', function () {
$html = (string) $this->blade('<x-input label="Share name" />');
expect($html)
->toContain('data-variant="outlined"')
->toContain('<legend><span>Share name</span></legend>')
->toMatch('/<label for="(field-[0-9a-f]{12})" class="field-label">Share name<\/label>/')
->toContain('placeholder=" "')
->toContain('class="field-control"');
});
it('draws a filled field on request, or by the application\'s default', function () {
expect((string) $this->blade('<x-input label="Name" variant="filled" />'))->toContain('data-variant="filled"');
config(['livewire-material.fields.variant' => 'filled']);
expect((string) $this->blade('<x-input label="Name" />'))->toContain('data-variant="filled"')
->and((string) $this->blade('<x-input label="Name" variant="outlined" />'))->toContain('data-variant="outlined"')
->and((string) $this->blade('<x-input label="Name" variant="glass" />'))->toContain('data-variant="filled"');
});
it('ties the label, the hint and the control together', function () {
$html = (string) $this->blade('<x-input id="share-name" label="Share name" hint="Recipients see this name" wire:model="name" />');
expect($html)
->toContain('<label for="share-name" class="field-label">')
->toContain('id="share-name"')
->toContain('aria-describedby="share-name-support"')
->toContain('<p id="share-name-support" class="field-support">Recipients see this name</p>')
->toContain('wire:model="name"')
->not->toContain('aria-invalid');
});
it('replaces the hint with the errors for its model', function () {
$html = (string) $this->withViewErrors(['email' => ['Enter a valid email address.']])
->blade('<x-input id="email" label="Email" hint="We never share it" wire:model.live="email" />');
expect($html)
->toContain('data-invalid')
->toContain('aria-invalid="true"')
->toContain('aria-describedby="email-support"')
->toContain('Enter a valid email address.')
->not->toContain('We never share it');
});
it('puts icons, affixes and the size on the field, and every other attribute on the input', function () {
$html = (string) $this->blade('<x-input label="Price" icon="payments" icon-right="info" prefix="CHF" suffix="per month" size="sm" type="number" min="0" class="w-40" mono readonly />');
expect($html)
->toContain('class="field w-40"')
->toContain('data-size="sm"')
->toContain('data-mono')
->toContain('data-readonly')
->toContain('<span class="field-affix">CHF</span>')
->toContain('<span class="field-affix">per month</span>')
->toContain('type="number"')
->toContain('min="0"')
->and(substr_count($html, '<svg'))->toBe(2);
});
it('offers to clear and to copy the value', function () {
$html = (string) $this->blade('<x-input label="Link" clearable copyable />');
expect($html)
->toContain('data-field-clear')
->toContain('aria-label="Clear"')
->toContain('data-field-copy')
->toContain('navigator.clipboard.writeText')
->toContain('aria-label="Copy"');
});
it('lets a password be shown and hidden again', function () {
$html = (string) $this->blade('<x-password label="Password" autocomplete="current-password" type="text" />');
expect($html)
->toContain('type="password"')
->not->toContain('type="text"')
->toContain('x-bind:type="shown ? \'text\' : \'password\'"')
->toContain('data-field-reveal')
->toContain('aria-pressed="false"')
->toContain('autocomplete="current-password"');
});
it('grows a textarea from its rows up to its maximum, or leaves it to be resized', function () {
expect((string) $this->blade('<x-textarea label="Message" rows="2" max-rows="6" />'))
->toContain('rows="2"')
->toContain('data-autogrow')
->toContain('--field-rows: 2;')
->toContain('--field-max-rows: 6;')
->and((string) $this->blade('<x-textarea label="Message" :autogrow="false" />'))
->toContain('rows="3"')
->not->toContain('data-autogrow');
});
it('draws a native select whose label always floats', function () {
$html = (string) $this->blade(<<<'BLADE'
<x-select label="Expires" wire:model="hours" placeholder="Choose…" option-value="hours" option-label="label" :options="[
['hours' => 1, 'label' => '1 hour'],
['hours' => 720, 'label' => '30 days', 'disabled' => true],
]" />
BLADE);
expect($html)
->toContain('data-floated')
->toContain('<select')
->toContain('wire:model="hours"')
->toContain('<option value="">Choose…</option>')
->toContain('<option value="1" >1 hour</option>')
->toContain('<option value="720" disabled>30 days</option>')
->toContain('field-arrow');
});
it('takes a select\'s options from its slot as well', function () {
expect((string) $this->blade('<x-select label="Size"><option value="s">Small</option></x-select>'))
->toContain('<option value="s">Small</option>');
});
it('collects a file field\'s own errors and each file\'s', function () {
$html = (string) $this->withViewErrors([
'photos' => ['Choose at most 10 photos.'],
'photos.0' => ['photo.jpg is larger than 2 GB.'],
])->blade('<x-file label="Photos" wire:model="photos" multiple />');
expect($html)
->toContain('type="file"')
->toContain('multiple')
->toContain('data-floated')
->toContain('Choose at most 10 photos.')
->toContain('photo.jpg is larger than 2 GB.');
});
it('lays out a form with its actions under an optional divider', function () {
$html = (string) $this->blade(<<<'BLADE'
<x-form wire:submit="save" separator>
<x-input label="Name" />
<x-slot:actions class="justify-between"><button>Save</button></x-slot:actions>
</x-form>
BLADE);
expect($html)
->toContain('<form class="grid grid-cols-1 auto-rows-min gap-4" wire:submit="save">')
->toContain('role="separator"')
->toContain('justify-between')
->toContain('<button>Save</button>')
->and((string) $this->blade('<x-form><x-slot:actions><button>Save</button></x-slot:actions></x-form>'))
->not->toContain('role="separator"');
});
@@ -0,0 +1,92 @@
<?php
it('draws a checkbox whose row is its label', function () {
$html = (string) $this->blade('<x-checkbox id="notify" label="Notify me" hint="On every download" wire:model="notify" class="mt-2" />');
expect($html)
->toContain('<div class="min-w-0 mt-2">')
->toContain('<label for="notify" data-selection')
->toContain('data-checkbox')
->toContain('type="checkbox"')
->toContain('wire:model="notify"')
->toContain('data-check')
->toContain('data-mixed')
->toContain('Notify me')
->toContain('On every download')
->not->toContain('data-indeterminate');
});
it('marks a checkbox that is partly ticked', function () {
expect((string) $this->blade('<x-checkbox label="Select all" indeterminate />'))->toContain('data-indeterminate');
});
it('puts a checkbox at the end of its row on request', function () {
expect((string) $this->blade('<x-checkbox label="Show" right />'))->toContain('flex-row-reverse justify-between');
});
it('shows a checkbox\'s errors', function () {
$html = (string) $this->withViewErrors(['terms' => ['Accept the terms to continue.']])
->blade('<x-checkbox id="terms" label="I accept the terms" wire:model="terms" />');
expect($html)
->toContain('data-invalid')
->toContain('aria-invalid="true"')
->toContain('aria-describedby="terms-support"')
->toContain('Accept the terms to continue.');
});
it('draws radio buttons in a fieldset named by its question', function () {
$html = (string) $this->blade(<<<'BLADE'
<x-radio label="Who can open it" wire:model.live="audience" :options="[
['id' => 'anyone', 'name' => 'Anyone with the link'],
['id' => 'password', 'name' => 'Anyone with the password', 'hint' => 'Share it separately'],
['id' => 'team', 'name' => 'My team', 'disabled' => true],
]" />
BLADE);
expect($html)
->toContain('<fieldset')
->toContain('Who can open it</legend>')
->and(substr_count($html, 'type="radio"'))->toBe(3)
->and(substr_count($html, 'name="audience"'))->toBe(3)
->and(substr_count($html, 'wire:model.live="audience"'))->toBe(3)
->and($html)->toContain('value="password"')
->toContain('Share it separately')
->toMatch('/value="team"\s+disabled/');
});
it('names unbound radios after their group and checks the given value', function () {
$html = (string) $this->blade('<x-radio name="theme" value="dark" inline :options="[[\'id\' => \'light\', \'name\' => \'Light\'], [\'id\' => \'dark\', \'name\' => \'Dark\']]" />');
expect($html)
->toContain('sm:flex')
->and(substr_count($html, 'name="theme"'))->toBe(2)
->and($html)->toMatch('/value="dark"\s+checked/')
->not->toMatch('/value="light"\s+checked/');
});
it('shows the errors of a radio group', function () {
expect((string) $this->withViewErrors(['audience' => ['Choose who can open it.']])
->blade('<x-radio wire:model="audience" :options="[[\'id\' => \'a\', \'name\' => \'A\']]" />'))
->toContain('data-invalid')
->toContain('Choose who can open it.');
});
it('draws a switch on a checkbox with the switch role', function () {
$html = (string) $this->blade('<x-toggle id="public" label="Public link" wire:model.live="public" right />');
expect($html)
->toContain('<label for="public" data-selection')
->toContain('data-switch')
->toContain('role="switch"')
->toContain('type="checkbox"')
->toContain('wire:model.live="public"')
->toContain('data-handle')
->toContain('flex-row-reverse')
->not->toContain('data-icons');
});
it('puts icons on a switch\'s handle', function () {
expect((string) $this->blade('<x-toggle label="Wi-Fi" icons />'))->toContain('data-icons="both"')->toContain('data-on')->toContain('data-off')
->and((string) $this->blade('<x-toggle label="Wi-Fi" icons="selected" />'))->toContain('data-icons="selected"');
});