Created
September 25, 2023 06:36
-
-
Save dliebner/2522ed79191c8944c57f9aa4b438ab25 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** Example usage */ | |
SlAlertWrapper.create({ | |
duration: 10000, | |
renderTemplate: function() { | |
/** @param {MouseEvent} e */ | |
const _handleLinkClick = e => { | |
e.preventDefault(); | |
LightboxUtils.spawnMultiPageLightbox( AccountLightbox ); | |
this.hide(); | |
}; | |
return html` | |
Spoiler preview visibility can be toggled in <a class="link" href="#" @click=${_handleLinkClick}>account settings</a>. | |
`; | |
} | |
}); | |
/** A simple vessel for `<sl-alert>`s */ | |
class SlAlertWrapper extends LightElement { | |
static properties = { | |
variant: {}, | |
icon: {}, | |
duration: {type: Number}, | |
renderTemplate: {state: true}, | |
}; | |
autoremove = true; | |
/** | |
* @param {Object} props | |
* @param {string} [props.variant] | |
* @param {string} [props.icon] | |
* @param {number} [props.duration] | |
* @param {(...any) => TemplateResult} [props.renderTemplate] | |
*/ | |
static create( props, { | |
toastImmediately = true, | |
} = {}) { | |
const slAlert = Object.assign(new this(), props ?? {}); | |
if( toastImmediately ) { | |
document.body.append( slAlert ); | |
slAlert.ready().then(() => slAlert.toast()); | |
} | |
return slAlert; | |
} | |
constructor() { | |
super(); | |
/** @type {string} */ | |
this.variant = 'primary'; | |
/** @type {string|undefined} */ | |
this.icon = 'info-circle'; | |
/** @type {number} */ | |
this.duration = 3000; | |
/** @type {(...any) => TemplateResult} */ | |
this.renderTemplate; | |
} | |
/** @type {HTMLElement} */ | |
slAlert; | |
_slAlertRef( val ) { | |
this.slAlert = val; | |
} | |
toast() { this.slAlert?.toast(); } | |
show() { this.slAlert?.show(); } | |
hide() { this.slAlert?.hide(); } | |
_handleAfterHide() { | |
if( this.autoremove ) this.remove(); | |
} | |
render() { | |
return html` | |
<sl-alert | |
variant=${this.variant} | |
duration=${this.duration} | |
closable | |
@sl-after-hide=${this._handleAfterHide} | |
${Lit.ref(this._slAlertRef)} | |
> | |
${this.icon ? html` | |
<sl-icon slot="icon" name="${this.icon}"></sl-icon> | |
`:''} | |
${this.renderTemplate?.call(this) ?? Lit.nothing} | |
</sl-alert> | |
`; | |
} | |
} | |
SlAlertWrapper.registerTag('sl-alert-wrapper'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment