Skip to content

Instantly share code, notes, and snippets.

@erictraut
Created September 4, 2017 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erictraut/0f7da096537f39470552ba40a6bfedd9 to your computer and use it in GitHub Desktop.
Save erictraut/0f7da096537f39470552ba40a6bfedd9 to your computer and use it in GitHub Desktop.
React service that manages a queue of toasts to be displayed
/**
* ToastService.ts
*
* Service to show in in-app status.
*/
import _ = require('lodash');
import RX = require('reactxp');
export interface ToastMessageParams {
key: string;
textMessage: string;
bottomMargin?: number;
duration?: number;
icon?: string;
color?: string;
textColor?: string;
onPress?: () => void;
}
export class ToastMessage {
params: ToastMessageParams;
constructor(params: ToastMessageParams) {
this.params = params;
}
}
class ToastService {
showToastEvent = new RX.Types.SubscribableEvent<(message: ToastMessage) => void>();
private _currentMessages: ToastMessage[] = [];
private _displayedMessageKey: string = null;
private _keyCount = 0;
scheduleMessage(params: ToastMessageParams): void {
this._currentMessages.push(new ToastMessage(params));
this._showToastMessage();
}
scheduleTextMessage(textMessage: string): void {
this.scheduleMessage({ key: 'key' + this._keyCount++, textMessage });
}
removeToastMessage(key: string): void {
// If we are currently showing the associated toast, move on to the next toast.
// Otherwise just remove it from the queue.
if (this._displayedMessageKey === key) {
this.toastDismissed();
} else {
_.remove(this._currentMessages, message => message.params.key === key);
}
}
toastDismissed(): void {
this._displayedMessageKey = null;
this._showToastMessage();
}
private _showToastMessage(): void {
const message = _.head(this._currentMessages);
const isForeground = RX.App.getActivationState() === RX.Types.AppActivationState.Active;
if (message && isForeground && !this._displayedMessageKey) {
this.showToastEvent.fire(message);
this._currentMessages.shift();
this._displayedMessageKey = message.params.key;
}
}
}
export default new ToastService();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment