/* global Runtime */
import { Fragment, h } from 'preact';
import { useReducer, useEffect, useState } from 'preact/hooks';
import { generateMainImage } from '../actions';
import { validateFileInputs } from '../../packs/validateFileInputs';
import { addSnackbarItem } from '../../Snackbar';
import { ClipboardButton } from './ClipboardButton';
import { ButtonNew as Button, Spinner, Icon } from '@crayons';
import ImageIcon from '@images/image.svg';
import CancelIcon from '@images/x.svg';
const SpinnerOrCancel = () => (
);
function imageUploaderReducer(state, action) {
const { type, payload } = action;
switch (type) {
case 'uploading_image':
return {
...state,
uploadErrorMessage: null,
uploadingImage: true,
insertionImageUrls: [],
};
case 'upload_error':
return {
...state,
insertionImageUrls: [],
uploadErrorMessage: payload.errorMessage,
uploadingImage: false,
};
case 'upload_image_success':
return {
...state,
insertionImageUrls: payload.insertionImageUrls,
uploadingImage: false,
uploadErrorMessage: null,
};
default:
return state;
}
}
function initNativeImagePicker(e) {
e.preventDefault();
window.ForemMobile?.injectNativeMessage('imageUpload', {
action: 'imageUpload',
});
}
const NativeIosV1ImageUpload = ({ uploadingImage }) => (
{!uploadingImage && (
)}
);
/**
* The V2 editor uses a toolbar button press to trigger a visually hidden file input.
*
* @param {object} props
* @param {object} props.buttonProps Any props to be added to the trigger button
* @param {function} props.handleInsertionImageUpload Callback to handle image upload
* @param {boolean} props.uploadingImage Is an image currently being uploaded
* @param {boolean} props.useNativeUpload Should iOS native upload functionality be used
* @param {function} props.handleNativeMessage Callback for iOS native upload message handling
* @param {string} props.uploadErrorMessage Error message to be displayed
*
*/
const V2EditorImageUpload = ({
buttonProps,
handleInsertionImageUpload,
uploadingImage,
useNativeUpload,
handleNativeMessage,
uploadErrorMessage,
}) => {
useEffect(() => {
if (uploadErrorMessage) {
addSnackbarItem({
message: uploadErrorMessage,
addCloseButton: true,
});
}
}, [uploadErrorMessage]);
const [abortRequestController, setAbortRequestController] = useState(null);
const startNewRequest = (e) => {
const controller = new AbortController();
setAbortRequestController(controller);
handleInsertionImageUpload(e, controller.signal);
};
const cancelRequest = () => {
abortRequestController.abort();
setAbortRequestController(null);
};
const { tooltip: actionTooltip } = buttonProps;
return (
{useNativeUpload ? (
) : (
)}
{uploadingImage ? (
) : (
);
};
/**
* The V1 Editor uses a more detailed image upload UI, displaying errors and markdown text inline
*
* @param {object} props
* @param {boolean} props.uploadingImage Is an image currently being uploaded
* @param {boolean} props.useNativeUpload Should iOS native upload functionality be used
* @param {function} props.handleNativeMessage Callback for iOS native upload message handling
* @param {function} props.handleInsertionImageUpload Callback to handle image upload
* @param {string[]} props.insertionImageUrls URLs of successfully uploaded images
* @param {string} props.uploadErrorMessage Error message to be displayed
*
* @returns
*/
const V1EditorImageUpload = ({
uploadingImage,
useNativeUpload,
handleNativeMessage,
handleInsertionImageUpload,
insertionImageUrls,
uploadErrorMessage,
}) => {
const [showCopiedImageText, setShowCopiedImageText] = useState(false);
useEffect(() => {
if (uploadingImage) {
setShowCopiedImageText(false);
}
}, [uploadingImage]);
const copyText = () => {
const imageMarkdownInput = document.getElementById(
'image-markdown-copy-link-input',
);
Runtime.copyToClipboard(imageMarkdownInput.value)
.then(() => {
setShowCopiedImageText(true);
})
.catch((error) => {
addSnackbarItem({
message: error,
addCloseButton: true,
});
Honeybadger.notify(error);
});
};
return (
{uploadingImage && (
Uploading...
)}
{useNativeUpload ? (
) : uploadingImage ? null : (
)}
{insertionImageUrls.length > 0 && (
)}
{uploadErrorMessage ? (
{uploadErrorMessage}
) : null}
);
};
/**
* Image Uploader feature for editor forms
*
* @param {object} props
* @param {string} props.editorVersion The current editor version being used
* @param {object} props.buttonProps Any additional props to be added to upload image button (v2 editor only)
* @param {function} props.onImageUploadStart Callback for when image upload begins
* @param {function} props.onImageUploadSuccess Callback for when image upload succeeds
* @param {function} props.onImageUploadError Callback for when image upload fails
*
*/
export const ImageUploader = ({
editorVersion = 'v2',
buttonProps = {},
onImageUploadStart,
onImageUploadSuccess,
onImageUploadError,
}) => {
const [state, dispatch] = useReducer(imageUploaderReducer, {
insertionImageUrls: [],
uploadErrorMessage: null,
uploadingImage: false,
});
const { uploadingImage, uploadErrorMessage, insertionImageUrls } = state;
function onUploadError(error) {
onImageUploadError?.();
dispatch({
type: 'upload_error',
payload: { errorMessage: error.message },
});
}
function handleInsertionImageUpload(e, abortSignal) {
const { files } = e.target;
if (files.length > 0 && validateFileInputs()) {
const payload = { image: files };
dispatch({
type: 'uploading_image',
});
onImageUploadStart?.();
generateMainImage({
payload,
successCb: handleInsertImageUploadSuccess,
failureCb: onUploadError,
signal: abortSignal,
});
}
}
function handleInsertImageUploadSuccess(response) {
dispatch({
type: 'upload_image_success',
payload: { insertionImageUrls: response.links },
});
onImageUploadSuccess?.(``);
document.getElementById('upload-success-info').innerText =
'image upload complete';
}
function handleNativeMessage(e) {
const message = JSON.parse(e.detail);
if (message.namespace !== 'imageUpload') {
return;
}
switch (message.action) {
case 'uploading':
onImageUploadStart?.();
dispatch({
type: 'uploading_image',
});
break;
case 'error':
dispatch({
type: 'upload_error',
payload: { errorMessage: message.error },
});
break;
case 'success':
onImageUploadSuccess?.(``);
dispatch({
type: 'upload_image_success',
payload: { insertionImageUrls: [message.link] },
});
break;
}
}
// When the component is rendered in an environment that supports a native
// image picker for image upload we want to add the aria-label attr and the
// onClick event to the UI button. This event will kick off the native UX.
// The props are unwrapped (using spread operator) in the button below
//
//
//
// This namespace is not implemented in the native side. This allows us to
// deploy our refactor and wait until our iOS app is approved by AppStore
// review. The old web implementation will be the fallback until then.
const useNativeUpload = Runtime.isNativeIOS('imageUpload_disabled');
// Native Bridge messages come through ForemMobile events
document.addEventListener('ForemMobile', handleNativeMessage);
return (
{editorVersion === 'v2' ? (
) : (
)}
);
};
ImageUploader.displayName = 'ImageUploader';