From 18c1676c010f92712cd40d9656a62f419a3c1631 Mon Sep 17 00:00:00 2001 From: Taso Date: Wed, 3 Mar 2021 17:53:36 -0500 Subject: [PATCH] tweak(phone/utils): Refactored image validation to promise from cb --- .../apps/twitter/components/AddTweetModal.tsx | 7 ++++--- phone/src/apps/twitter/utils/images.ts | 21 +++++++++++-------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/phone/src/apps/twitter/components/AddTweetModal.tsx b/phone/src/apps/twitter/components/AddTweetModal.tsx index f0613e9..a2f8d34 100644 --- a/phone/src/apps/twitter/components/AddTweetModal.tsx +++ b/phone/src/apps/twitter/components/AddTweetModal.tsx @@ -4,8 +4,7 @@ import { v4 as uuidv4 } from 'uuid'; import Nui from '../../../os/nui-events/utils/Nui'; import Modal from '../../../ui/components/Modal'; -import { IMAGE_DELIMITER } from '../utils/images'; -import { withValidImage } from '../utils/images'; +import { IMAGE_DELIMITER, isImageValid } from '../utils/images'; import { useModal } from '../hooks/useModal'; import EmojiSelect from './EmojiSelect'; import ImageDisplay from './images/ImageDisplay'; @@ -129,7 +128,9 @@ export const AddTweetModal = () => { // other users see this image on their TweetList it will be // from the database and should already have passed through // this logic - withValidImage(cleanedLink, () => setImages([...images, image])); + isImageValid(cleanedLink) + .then(() => setImages([...images, image])) + .catch((e) => console.error(e)); setShowImagePrompt(false); setLink(''); diff --git a/phone/src/apps/twitter/utils/images.ts b/phone/src/apps/twitter/utils/images.ts index 6a8fbe9..6bd1144 100644 --- a/phone/src/apps/twitter/utils/images.ts +++ b/phone/src/apps/twitter/utils/images.ts @@ -6,15 +6,18 @@ export const IMAGE_DELIMITER = '||!||'; /** - * Validate that the URL successfully loads in the browser + * Returns a Promise that validates that the URL successfully + * loads in the browser. If the URL doesn't load the promise is + * rejected. * @param {string} link - a URL we are trying to validate - * @param {func} onSuccess - callback if the link is valid + * @returns {Promise} link - Will resolve the promise with the link string + * if valid. Will reject if failed. */ -export function withValidImage(link: string, onSuccess: any): void { - const image = new Image(); - image.onload = onSuccess; - image.onerror = () => { - console.warn(`Invalid image submitted: ${link}`); - }; - image.src = link; +export function isImageValid(link: string): Promise { + return new Promise((res, rej) => { + const image = new Image(); + image.src = link; + image.onerror = () => rej(`Invalid image, ${link}`); + image.onload = () => res(link); + }); }