Fix: Make Alert SSR compatible

pull/2359/head
Christian Schilling 2025-01-31 10:03:11 +01:00
rodzic 6761fdceca
commit aed5e02058
1 zmienionych plików z 19 dodań i 8 usunięć

Wyświetl plik

@ -13,8 +13,6 @@ import SlIconButton from '../icon-button/icon-button.component.js';
import styles from './alert.styles.js';
import type { CSSResultGroup } from 'lit';
const toastStack = Object.assign(document.createElement('div'), { className: 'sl-toast-stack' });
/**
* @summary Alerts are used to display important messages inline or as toast notifications.
* @documentation https://shoelace.style/components/alert
@ -50,6 +48,19 @@ export default class SlAlert extends ShoelaceElement {
private readonly hasSlotController = new HasSlotController(this, 'icon', 'suffix');
private readonly localize = new LocalizeController(this);
private static currentToastStack: HTMLDivElement;
private static get toastStack() {
console.log('called');
if (!this.currentToastStack) {
this.currentToastStack = Object.assign(document.createElement('div'), {
className: 'sl-toast-stack'
});
console.log('created');
}
return this.currentToastStack;
}
@query('[part~="base"]') base: HTMLElement;
@query('.alert__countdown-elapsed') countdownElement: HTMLElement;
@ -195,11 +206,11 @@ export default class SlAlert extends ShoelaceElement {
async toast() {
return new Promise<void>(resolve => {
this.handleCountdownChange();
if (toastStack.parentElement === null) {
document.body.append(toastStack);
if (SlAlert.toastStack.parentElement === null) {
document.body.append(SlAlert.toastStack);
}
toastStack.appendChild(this);
SlAlert.toastStack.appendChild(this);
// Wait for the toast stack to render
requestAnimationFrame(() => {
@ -211,12 +222,12 @@ export default class SlAlert extends ShoelaceElement {
this.addEventListener(
'sl-after-hide',
() => {
toastStack.removeChild(this);
SlAlert.toastStack.removeChild(this);
resolve();
// Remove the toast stack from the DOM when there are no more alerts
if (toastStack.querySelector('sl-alert') === null) {
toastStack.remove();
if (SlAlert.toastStack.querySelector('sl-alert') === null) {
SlAlert.toastStack.remove();
}
},
{ once: true }