Created
September 20, 2019 17:13
-
-
Save bericp1/38a7360c88a3614d4095b4312c5ab57e to your computer and use it in GitHub Desktop.
An alert module
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
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