Skip to content

Instantly share code, notes, and snippets.

@bericp1
Created September 20, 2019 17:13
Show Gist options
  • Save bericp1/38a7360c88a3614d4095b4312c5ab57e to your computer and use it in GitHub Desktop.
Save bericp1/38a7360c88a3614d4095b4312c5ab57e to your computer and use it in GitHub Desktop.
An alert module
import { flatten } from 'ramda';
/**
* The default alert message type.
*
* @constant
* @type {string}
*/
export const DEFAULT_ALERT_TYPE = 'info';
/**
* Get the default title for specific error types.
*
* @param {string} type
* @return {string}
*/
export function getDefaultTitleForAlertType(type) {
switch (type) {
case 'success':
return 'Success!';
case 'error':
return 'Uh oh!';
case 'info': // Intentional fall through
default:
return 'Heads up!'
}
}
/**
* Send one-off alerts to the user.
*
* Accepts an array of either strings or objects (or variadically provide strings or objects as arguments).
*
* Available message types are:
*
* - `'info'` (default)
* - `'success'` (default)
* - `'error'` (default)
*
* @param {(string|{message: string, type?: string, title?: string})[]} rawMessages
*/
export function alert(...rawMessages) {
// Flatten down the arguments so we get an array of either strings or objects
flatten(rawMessages)
// Parse each string or object into a well-defined message object
.map((rawMessage) => {
if (typeof rawMessage === 'string') {
return {
type: DEFAULT_ALERT_TYPE,
title: getDefaultTitleForAlertType(DEFAULT_ALERT_TYPE),
message: rawMessage,
};
} else {
const type = rawMessage.type || DEFAULT_ALERT_TYPE;
return {
type,
title: rawMessage.title || getDefaultTitleForAlertType(type),
message: rawMessage.message || '',
};
}
})
.forEach(({ title, message }) => {
// For now we ignore `type` but in the future we'll use it to style a dropdown, etc.
Alert.alert(title, message, [{ text: 'Close' }]);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment