Add sticky toasts, action events and toast hooks
A sticky toast stays until it is dismissed or its action pressed, for a
question that must be answered ("A new version is ready" with Reload).
It is kept aside rather than queued, so it never holds up ordinary
toasts: one that arrives while it shows takes its place, and the sticky
toast comes back once the queue is empty. One is kept at a time; a newer
sticky toast replaces it. Every other toast keeps today's queue.
An action's `event` names a window event dispatched when it is pressed,
beside `handler`, for toasts whose detail cannot carry a function. The
snackbar now closes before either runs, so a toast they show is not the
one dismissed.
`data-toast` and `data-toast-action` give applications stable hooks for
their tests.
The queue now forgets a cleared timer in next(): a toast dismissed by a
click that neither hovered nor focused it first, as a screen reader
activates a button, left its timer running and cut the next toast short.
The showcase's snackbar buttons had no Alpine scope and did nothing; they
are wrapped in one, with a sticky example.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RHoXZSHc8gGpZjFmA5fPc2
This commit is contained in:
co-authored by
Claude Opus 5
parent
53bb000425
commit
07e008d942
@@ -313,6 +313,16 @@ materialToast('Share deleted', { type: 'success', description: null, timeout: 40
|
|||||||
|
|
||||||
`type` (`success`, `error`, `warning`, `info`) adds the state icon; `timeout: 0` keeps it until dismissed; a toast with an action or no timeout gets a close button. Hover or focus pauses the timer.
|
`type` (`success`, `error`, `warning`, `info`) adds the state icon; `timeout: 0` keeps it until dismissed; a toast with an action or no timeout gets a close button. Hover or focus pauses the timer.
|
||||||
|
|
||||||
|
- `action`: `label`, plus `handler` (a function) and/or `event` (a name). Pressing it closes the snackbar, calls `handler`, then dispatches `new CustomEvent(event)` on `window`; give both and both run. Use `event` where a function cannot travel, such as a toast built from JSON.
|
||||||
|
- `sticky: true` keeps a toast until it is dismissed or its action is pressed (any `timeout` is ignored), without holding the queue up: a toast dispatched meanwhile shows in its place, and the sticky one comes back once the queue is empty. One sticky toast is kept at a time; a newer one replaces it. Use it for a question that must be answered, not for news:
|
||||||
|
|
||||||
|
```js
|
||||||
|
window.dispatchEvent(new CustomEvent('toast', { detail: { type: 'info', title: 'A new version is ready', sticky: true, action: { label: 'Reload', event: 'app:update' } } }))
|
||||||
|
window.addEventListener('app:update', () => location.reload())
|
||||||
|
```
|
||||||
|
|
||||||
|
- Hooks: `data-toast` on the snackbar on screen, `data-toast-action` on its action button (`[data-toast]` is absent while nothing shows). Target these in tests, not classes.
|
||||||
|
|
||||||
### `<x-progress>`
|
### `<x-progress>`
|
||||||
|
|
||||||
M3 Expressive's progress indicator: linear (as wide as its container) or `circular` (40px, 48px wavy, unless a `size-*` class is passed), flat or `wavy`, determinate with a `value` or indeterminate without one.
|
M3 Expressive's progress indicator: linear (as wide as its container) or `circular` (40px, 48px wavy, unless a `size-*` class is passed), flat or `wavy`, determinate with a `value` or indeterminate without one.
|
||||||
|
|||||||
@@ -4,6 +4,11 @@
|
|||||||
* One snackbar at a time, as M3 shows them. Each waits its turn, stays for its timeout (paused
|
* One snackbar at a time, as M3 shows them. Each waits its turn, stays for its timeout (paused
|
||||||
* while hovered or focused, so it is never pulled away from someone reading or reaching for its
|
* while hovered or focused, so it is never pulled away from someone reading or reaching for its
|
||||||
* action) and is replaced by the next.
|
* action) and is replaced by the next.
|
||||||
|
*
|
||||||
|
* A `sticky` toast ("A new version is ready" with a Reload action) stays until it is answered, but
|
||||||
|
* never holds the queue up: it is kept aside rather than queued, a toast that arrives while it shows
|
||||||
|
* takes its place, and it comes back once the queue is empty. Only one is kept — a newer sticky
|
||||||
|
* toast replaces it. Dismissing it, or pressing its action, lets it go.
|
||||||
*/
|
*/
|
||||||
const DEFAULT_TIMEOUT_MS = 4000
|
const DEFAULT_TIMEOUT_MS = 4000
|
||||||
|
|
||||||
@@ -25,6 +30,7 @@ document.addEventListener('alpine:init', () => {
|
|||||||
window.Alpine.data('materialSnackbar', () => ({
|
window.Alpine.data('materialSnackbar', () => ({
|
||||||
queue: [],
|
queue: [],
|
||||||
current: null,
|
current: null,
|
||||||
|
sticky: null,
|
||||||
timer: null,
|
timer: null,
|
||||||
remaining: 0,
|
remaining: 0,
|
||||||
startedAt: 0,
|
startedAt: 0,
|
||||||
@@ -44,24 +50,43 @@ document.addEventListener('alpine:init', () => {
|
|||||||
// Livewire dispatches named arguments as the detail object; a positional dispatch
|
// Livewire dispatches named arguments as the detail object; a positional dispatch
|
||||||
// arrives as an array whose first entry is that object.
|
// arrives as an array whose first entry is that object.
|
||||||
const toast = Array.isArray(detail) ? detail[0] : detail
|
const toast = Array.isArray(detail) ? detail[0] : detail
|
||||||
|
const sticky = toast.sticky === true
|
||||||
|
|
||||||
this.queue.push({
|
const entry = {
|
||||||
id: ++sequence,
|
id: ++sequence,
|
||||||
type: toast.type ?? null,
|
type: toast.type ?? null,
|
||||||
title: toast.title ?? '',
|
title: toast.title ?? '',
|
||||||
description: toast.description ?? null,
|
description: toast.description ?? null,
|
||||||
timeout: toast.timeout === 0 || toast.timeout === null ? 0 : (toast.timeout ?? DEFAULT_TIMEOUT_MS),
|
timeout: sticky || toast.timeout === 0 || toast.timeout === null ? 0 : (toast.timeout ?? DEFAULT_TIMEOUT_MS),
|
||||||
action: toast.action ?? null,
|
action: toast.action ?? null,
|
||||||
})
|
sticky,
|
||||||
|
}
|
||||||
|
|
||||||
if (!this.current) {
|
if (sticky) {
|
||||||
|
const showing = !this.current || this.current === this.sticky
|
||||||
|
this.sticky = entry
|
||||||
|
|
||||||
|
if (showing) {
|
||||||
|
this.next()
|
||||||
|
}
|
||||||
|
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
this.queue.push(entry)
|
||||||
|
|
||||||
|
// A sticky toast steps aside for it, and comes back from next() once the queue is empty.
|
||||||
|
if (!this.current || this.current === this.sticky) {
|
||||||
this.next()
|
this.next()
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
next() {
|
next() {
|
||||||
|
// Cleared and forgotten here, so a toast dismissed early never leaves its timer running
|
||||||
|
// to cut the next one short.
|
||||||
clearTimeout(this.timer)
|
clearTimeout(this.timer)
|
||||||
this.current = this.queue.shift() ?? null
|
this.timer = null
|
||||||
|
this.current = this.queue.shift() ?? this.sticky
|
||||||
|
|
||||||
if (this.current?.timeout) {
|
if (this.current?.timeout) {
|
||||||
this.remaining = this.current.timeout
|
this.remaining = this.current.timeout
|
||||||
@@ -92,13 +117,24 @@ document.addEventListener('alpine:init', () => {
|
|||||||
},
|
},
|
||||||
|
|
||||||
dismiss() {
|
dismiss() {
|
||||||
this.timer = null
|
if (this.current && this.current === this.sticky) {
|
||||||
|
this.sticky = null
|
||||||
|
}
|
||||||
|
|
||||||
this.next()
|
this.next()
|
||||||
},
|
},
|
||||||
|
|
||||||
|
// Closed before the handler and the event run, so a toast either of them shows is not the
|
||||||
|
// one dismissed.
|
||||||
act() {
|
act() {
|
||||||
this.current?.action?.handler?.()
|
const action = this.current?.action
|
||||||
|
|
||||||
this.dismiss()
|
this.dismiss()
|
||||||
|
action?.handler?.()
|
||||||
|
|
||||||
|
if (typeof action?.event === 'string' && action.event !== '') {
|
||||||
|
window.dispatchEvent(new CustomEvent(action.event))
|
||||||
|
}
|
||||||
},
|
},
|
||||||
|
|
||||||
icon(type) {
|
icon(type) {
|
||||||
|
|||||||
@@ -5,9 +5,18 @@
|
|||||||
|
|
||||||
It shows every `toast` browser event — what `NoNameWeb\LivewireMaterial\Concerns\Toasts`
|
It shows every `toast` browser event — what `NoNameWeb\LivewireMaterial\Concerns\Toasts`
|
||||||
dispatches from a Livewire component — and for `window.materialToast(title, options)` from
|
dispatches from a Livewire component — and for `window.materialToast(title, options)` from
|
||||||
JavaScript (`{ type, description, timeout, action: { label, handler } }`). Toasts queue and
|
JavaScript (`{ type, description, timeout, sticky, action: { label, handler, event } }`).
|
||||||
show in turn, each for its `timeout` (4s by default; M3 asks for 4–10s), paused while the
|
Toasts queue and show in turn, each for its `timeout` (4s by default; M3 asks for 4–10s),
|
||||||
pointer or focus is on it. A toast with an action or no timeout gets a close button.
|
paused while the pointer or focus is on it. A toast with an action or no timeout gets a close
|
||||||
|
button. Pressing the action closes the snackbar, calls `handler` and dispatches `event` (a
|
||||||
|
name) on `window`; both may be given.
|
||||||
|
|
||||||
|
`sticky: true` keeps a toast until it is dismissed or its action pressed, without holding up
|
||||||
|
the queue: a toast that arrives meanwhile shows in its place, and the sticky one comes back
|
||||||
|
once the queue is empty. One is kept at a time; a newer sticky toast replaces it.
|
||||||
|
|
||||||
|
Hooks for tests and styling: `data-toast` on the snackbar on screen, `data-toast-action` on its
|
||||||
|
action button.
|
||||||
|
|
||||||
`@persist` keeps the host across wire:navigate, so a toast dispatched with `redirectTo` is
|
`@persist` keeps the host across wire:navigate, so a toast dispatched with `redirectTo` is
|
||||||
still on screen when the next page arrives.
|
still on screen when the next page arrives.
|
||||||
@@ -32,6 +41,7 @@
|
|||||||
<template x-if="current">
|
<template x-if="current">
|
||||||
<div
|
<div
|
||||||
x-bind:key="current.id"
|
x-bind:key="current.id"
|
||||||
|
data-toast
|
||||||
x-bind:role="current.type === 'error' || current.type === 'warning' ? 'alert' : 'status'"
|
x-bind:role="current.type === 'error' || current.type === 'warning' ? 'alert' : 'status'"
|
||||||
aria-live="polite"
|
aria-live="polite"
|
||||||
x-on:mouseenter="pause()"
|
x-on:mouseenter="pause()"
|
||||||
@@ -60,7 +70,7 @@
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<template x-if="current.action">
|
<template x-if="current.action">
|
||||||
<button type="button" class="state-layer focus-ring h-10 shrink-0 rounded-corner-full px-3 type-label-lg text-inverse-primary" x-text="current.action.label" x-on:click="act()"></button>
|
<button type="button" data-toast-action class="state-layer focus-ring h-10 shrink-0 rounded-corner-full px-3 type-label-lg text-inverse-primary" x-text="current.action.label" x-on:click="act()"></button>
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<template x-if="current.action || ! current.timeout">
|
<template x-if="current.action || ! current.timeout">
|
||||||
|
|||||||
@@ -10,10 +10,13 @@
|
|||||||
<x-badge value="Pro" outline />
|
<x-badge value="Pro" outline />
|
||||||
BLADE,
|
BLADE,
|
||||||
'Snackbars' => <<<'BLADE'
|
'Snackbars' => <<<'BLADE'
|
||||||
<x-button label="Saved" variant="tonal" x-on:click="materialToast('Settings saved', { type: 'success' })" />
|
<div x-data class="flex flex-wrap items-center gap-4">
|
||||||
<x-button label="With a description" variant="tonal" x-on:click="materialToast('Upload failed', { type: 'error', description: 'The file is larger than 4 GB.' })" />
|
<x-button label="Saved" variant="tonal" x-on:click="materialToast('Settings saved', { type: 'success' })" />
|
||||||
<x-button label="With an action" variant="tonal" x-on:click="materialToast('Share deleted', { action: { label: 'Undo', handler: () => materialToast('Share restored', { type: 'info' }) } })" />
|
<x-button label="With a description" variant="tonal" x-on:click="materialToast('Upload failed', { type: 'error', description: 'The file is larger than 4 GB.' })" />
|
||||||
<x-button label="Until dismissed" variant="tonal" x-on:click="materialToast('Your storage is almost full', { type: 'warning', timeout: 0 })" />
|
<x-button label="With an action" variant="tonal" x-on:click="materialToast('Share deleted', { action: { label: 'Undo', handler: () => materialToast('Share restored', { type: 'info' }) } })" />
|
||||||
|
<x-button label="Until dismissed" variant="tonal" x-on:click="materialToast('Your storage is almost full', { type: 'warning', timeout: 0 })" />
|
||||||
|
<x-button label="Sticky, with an event" variant="tonal" x-on:click="materialToast('A new version is ready', { type: 'info', sticky: true, action: { label: 'Reload', event: 'showcase:reload' } })" x-on:showcase:reload.window="materialToast('Reloading…')" />
|
||||||
|
</div>
|
||||||
BLADE,
|
BLADE,
|
||||||
'Plain tooltips' => <<<'BLADE'
|
'Plain tooltips' => <<<'BLADE'
|
||||||
<x-button icon="content_copy" tooltip="Copy link" />
|
<x-button icon="content_copy" tooltip="Copy link" />
|
||||||
|
|||||||
@@ -2,6 +2,8 @@
|
|||||||
|
|
||||||
const SNACKBAR = "document.querySelector('[x-data=\"materialSnackbar\"] [aria-live]')";
|
const SNACKBAR = "document.querySelector('[x-data=\"materialSnackbar\"] [aria-live]')";
|
||||||
|
|
||||||
|
const TOAST = "document.querySelector('[data-toast]')";
|
||||||
|
|
||||||
it('shows a toast as a snackbar, then the next in turn', function () {
|
it('shows a toast as a snackbar, then the next in turn', function () {
|
||||||
$page = visit('/material/communication')->waitForEvent('networkidle')
|
$page = visit('/material/communication')->waitForEvent('networkidle')
|
||||||
->assertScript("document.readyState === 'complete' && typeof window.Alpine !== 'undefined' && typeof window.Livewire !== 'undefined'");
|
->assertScript("document.readyState === 'complete' && typeof window.Alpine !== 'undefined' && typeof window.Livewire !== 'undefined'");
|
||||||
@@ -39,6 +41,65 @@ it('runs a toast\'s action and dismisses it', function () {
|
|||||||
->assertScript(SNACKBAR.' === null');
|
->assertScript(SNACKBAR.' === null');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('does not let a toast dismissed early cut the next one short', function () {
|
||||||
|
$page = visit('/material/communication')->waitForEvent('networkidle')
|
||||||
|
->assertScript("document.readyState === 'complete' && typeof window.Alpine !== 'undefined' && typeof window.Livewire !== 'undefined'");
|
||||||
|
|
||||||
|
$page->script("window.eval(\"materialToast('Share deleted', { timeout: 800, action: { label: 'Undo' } }); materialToast('Link copied', { timeout: 2500 })\")");
|
||||||
|
|
||||||
|
// A click with no hover or focus before it, as a screen reader activates a button: nothing has
|
||||||
|
// paused the first toast's timer.
|
||||||
|
$page->script("document.querySelector('[data-toast] button[aria-label=\"Dismiss\"]').click()");
|
||||||
|
|
||||||
|
$page->assertScript(TOAST."?.textContent.includes('Link copied')")
|
||||||
|
->wait(1.2);
|
||||||
|
|
||||||
|
$page->assertScript(TOAST."?.textContent.includes('Link copied')");
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps a sticky toast aside while a passing one shows, brings back the newest, and lets it go once dismissed', function () {
|
||||||
|
$page = visit('/material/communication')->waitForEvent('networkidle')
|
||||||
|
->assertScript("document.readyState === 'complete' && typeof window.Alpine !== 'undefined' && typeof window.Livewire !== 'undefined'");
|
||||||
|
|
||||||
|
// As an application dispatches it; built in the page's realm (see above).
|
||||||
|
$page->script("window.eval(\"window.dispatchEvent(new CustomEvent('toast', { detail: { type: 'info', title: 'A new version is ready', sticky: true, timeout: 300, action: { label: 'Reload', event: 'material:test-reload' } } }))\")");
|
||||||
|
|
||||||
|
$page->assertScript(TOAST."?.textContent.includes('A new version is ready')")
|
||||||
|
->wait(0.6);
|
||||||
|
|
||||||
|
$page->assertScript(TOAST."?.textContent.includes('A new version is ready')");
|
||||||
|
|
||||||
|
$page->script("window.eval(\"materialToast('Settings saved', { type: 'success', timeout: 900 }); materialToast('Version 2 is ready', { sticky: true })\")");
|
||||||
|
|
||||||
|
$page->assertScript(TOAST."?.textContent.includes('Settings saved')")
|
||||||
|
->wait(1.3);
|
||||||
|
|
||||||
|
$page->assertScript(TOAST."?.textContent.includes('Version 2 is ready')");
|
||||||
|
|
||||||
|
$page->click('[data-toast] button[aria-label="Dismiss"]')
|
||||||
|
->assertScript(TOAST.' === null');
|
||||||
|
|
||||||
|
// Dismissed rather than left to time out: the pointer still rests where the snackbar appears,
|
||||||
|
// and hovering pauses it.
|
||||||
|
$page->script("window.eval(\"materialToast('Link copied', { timeout: 0 })\")");
|
||||||
|
|
||||||
|
$page->assertScript(TOAST."?.textContent.includes('Link copied')")
|
||||||
|
->click('[data-toast] button[aria-label="Dismiss"]')
|
||||||
|
->assertScript(TOAST.' === null');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('dispatches a toast action\'s window event alongside its handler, and closes', function () {
|
||||||
|
$page = visit('/material/communication')->waitForEvent('networkidle')
|
||||||
|
->assertScript("document.readyState === 'complete' && typeof window.Alpine !== 'undefined' && typeof window.Livewire !== 'undefined'");
|
||||||
|
|
||||||
|
$page->script("window.eval(\"window.reloads = 0; window.handled = 0; window.addEventListener('material:test-reload', () => window.reloads++); materialToast('A new version is ready', { sticky: true, action: { label: 'Reload', event: 'material:test-reload', handler: () => window.handled++ } })\")");
|
||||||
|
|
||||||
|
$page->click('[data-toast-action]')
|
||||||
|
->assertScript(TOAST.' === null')
|
||||||
|
->assertScript("window.eval('window.reloads') === 1")
|
||||||
|
->assertScript("window.eval('window.handled') === 1");
|
||||||
|
});
|
||||||
|
|
||||||
it('opens a persistent rich tooltip on press', function () {
|
it('opens a persistent rich tooltip on press', function () {
|
||||||
$bubble = "document.querySelector('#communication [role=\"dialog\"][popover]')";
|
$bubble = "document.querySelector('#communication [role=\"dialog\"][popover]')";
|
||||||
|
|
||||||
|
|||||||
@@ -13,3 +13,11 @@ it('hosts the snackbar queue, kept across wire:navigate', function () {
|
|||||||
it('can sit at the start', function () {
|
it('can sit at the start', function () {
|
||||||
expect((string) $this->blade('<x-toast position="bottom-start" />'))->toContain('justify-start');
|
expect((string) $this->blade('<x-toast position="bottom-start" />'))->toContain('justify-start');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('marks the snackbar and its action for tests and styling', function () {
|
||||||
|
$html = (string) $this->blade('<x-toast />');
|
||||||
|
|
||||||
|
expect($html)
|
||||||
|
->toMatch('/<div\s[^>]*\bdata-toast\b[^>]*aria-live="polite"/')
|
||||||
|
->toMatch('/<button\s[^>]*\bdata-toast-action\b[^>]*x-on:click="act\(\)"/');
|
||||||
|
});
|
||||||
|
|||||||
Reference in New Issue
Block a user