From 8afd1cc5d0fc4b1eb384be4aa03160fda2facb49 Mon Sep 17 00:00:00 2001 From: Birk Johansson Date: Mon, 21 Oct 2024 16:30:23 +0200 Subject: [PATCH] fix(ImageField): add image preview --- .../organisationUnits/form/ImageField.tsx | 100 ++++++++++++------ 1 file changed, 68 insertions(+), 32 deletions(-) diff --git a/src/pages/organisationUnits/form/ImageField.tsx b/src/pages/organisationUnits/form/ImageField.tsx index aba41a9d..42aafeda 100644 --- a/src/pages/organisationUnits/form/ImageField.tsx +++ b/src/pages/organisationUnits/form/ImageField.tsx @@ -1,14 +1,25 @@ -import { useDataEngine } from '@dhis2/app-runtime' +import { useConfig, useDataEngine } from '@dhis2/app-runtime' import i18n from '@dhis2/d2-i18n' import { FileInput, FileInputChangeHandler, FileList, FileListItem, - Label, + Field as UIField, } from '@dhis2/ui' -import React from 'react' -import { Field as FieldRFF, useField } from 'react-final-form' +import React, { useState } from 'react' +import { useField } from 'react-final-form' +import css from './ImageField.module.css' + +const fileToBase64 = (file: File): Promise => { + const reader = new FileReader() + + return new Promise((resolve, reject) => { + reader.readAsDataURL(file) + reader.onload = () => resolve(reader.result as string) + reader.onerror = reject + }) +} export function ImageField() { const dataEngine = useDataEngine() @@ -17,6 +28,8 @@ export function ImageField() { const currentFile: { name?: string; id?: string } | undefined = input.value || undefined + const [fileBase64, setFileBase64] = useState() + const uploadFile = async (fileToUpload: File) => { const fileToUploadDetails = { name: fileToUpload.name, @@ -61,45 +74,68 @@ export function ImageField() { input.onBlur() } const deleteFile = () => { + setFileBase64(undefined) input.onChange(undefined) input.onBlur() } - const handleChange: FileInputChangeHandler = ({ files }) => { + const handleChange: FileInputChangeHandler = async ({ files }) => { const newFile = files[0] if (newFile instanceof File) { uploadFile(newFile) + const file64 = await fileToBase64(newFile) + setFileBase64(file64) } } return ( - name={fieldName}> - {() => ( - <> - + +
+ + +
- + {currentFile?.id && ( + - - - {currentFile?.id && ( - - )} - - - )} - + )} + +
) } + +const ImagePreview = ({ + fileBase64, + fileResource, +}: { + fileBase64?: string + fileResource?: { id: string } +}) => { + const baseUrl = useConfig().baseUrl + + if (fileBase64) { + return {i18n.t('Preview + } + + if (fileResource && fileResource.id) { + const src = `${baseUrl}/fileResources/${fileResource.id}/data` + + return {i18n.t('Preview + } + return null +}