Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

18-Photo Component Improvements #77

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@
"react-router-bootstrap": "^0.26.2",
"react-router-dom": "^6.12.0",
"react-simple-code-editor": "^0.13.1",
"react-uuid": "^2.0.0",
"remark": "^14.0.2",
"remark-gfm": "^3.0.1",
"resolve": "^1.20.0",
Expand Down
18 changes: 15 additions & 3 deletions src/components/photo.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {isEmpty} from 'lodash'
import React, {FC, useEffect, useState} from 'react'
import {Button, Card, Image} from 'react-bootstrap'
import {Button, Card, Image, Modal, ModalBody, Popover} from 'react-bootstrap'


import GpsCoordStr from './gps_coord_str'
Expand All @@ -13,6 +13,7 @@ interface PhotoProps {
metadata: PhotoMetadata,
photo: Blob | undefined,
required: boolean,
deletePhoto?: (id: string) => void,
}

/**
Expand All @@ -27,8 +28,8 @@ interface PhotoProps {
* photo attachement in the data store with the given id. When set, the Photo component
* will always show and the Photo component will indicate when the photo is missing.
*/
const Photo: FC<PhotoProps> = ({description, label, metadata, photo, required}) => {

const Photo: FC<PhotoProps> = ({description, label, metadata, photo, required, deletePhoto, id}) => {
const [showDeleteModal, setShowDeleteModal] = useState(false)
return (photo || required)? (
<>
<Card style={{breakInside: 'avoid-page', marginBottom: '1rem'}}>
Expand All @@ -55,7 +56,18 @@ const Photo: FC<PhotoProps> = ({description, label, metadata, photo, required})
<span><GpsCoordStr {...metadata.geolocation.latitude} /> <GpsCoordStr {...metadata.geolocation.longitude} /></span> :
<span>Missing</span>
}
<br />
{deletePhoto && <button onClick={() => setShowDeleteModal(true)} style={{cursor: 'pointer', color: 'red', borderWidth: '1px', borderRadius: '6px'}}> Delete Photo </button>}
</small>
{deletePhoto && <Modal show={showDeleteModal}>
<ModalBody>
<p>Are you sure you want to delete this photo?</p>
<div style={{display: 'flex', alignItems: 'center', justifyContent:'space-between'}}>
<Button onClick={() => setShowDeleteModal(false)}>Cancel</Button>
<Button onClick={() => {deletePhoto(id); setShowDeleteModal(false)}} style={{cursor: 'pointer', color: 'red', borderWidth: '1px', borderRadius: '6px'}}>Delete</Button>
</div>
</ModalBody >
</Modal>}
</>
) : required && (
<em>Missing Photo</em>
Expand Down
149 changes: 63 additions & 86 deletions src/components/photo_input.tsx
Original file line number Diff line number Diff line change
@@ -1,127 +1,104 @@
import React, { ChangeEvent, FC, MouseEvent, useEffect, useRef, useState } from 'react'
import { Button, Card, Image } from 'react-bootstrap'
import { TfiCamera, TfiGallery } from 'react-icons/tfi'
import Collapsible from './collapsible'
import ImageBlobReduce from 'image-blob-reduce'
import {isEmpty} from 'lodash'
import React, {ChangeEvent, FC, MouseEvent, useEffect, useRef, useState} from 'react'
import {Button, Card, Image} from 'react-bootstrap'
import {TfiGallery} from 'react-icons/tfi'

import Photo from './photo'
import PhotoMetadata from '../types/photo_metadata.type'

import Collapsible from './collapsible'
import GpsCoordStr from './gps_coord_str'
import PhotoMetaData from '../types/photo_metadata.type'

interface PhotoInputProps {
children: React.ReactNode,
label: string,
metadata: PhotoMetaData,
photo: Blob | undefined,
upsertPhoto: (file: Blob) => void,
children: React.ReactNode
label: string
photos: {id: string, data: {blob: Blob, metadata: PhotoMetadata}}[]
upsertPhoto: (file: Blob, id: string) => void
removeAttachment: (id: string) => void
id: string
}

// TODO: Determine whether or not the useEffect() method is needed.
// We don't seem to need a separate camera button on an Android phone.
// However, we may need to request access to the camera
// before it can me used. Then clean up the corresponding code that is currently
// commented out.

/**
* Component for photo input
*
* @param children Content (most commonly markdown text) describing the photo requirement
* @param label Label for the photo requirement
* @param metadata Abreviated photo metadata including timestamp and geolocation
* @param photo Blob containing the photo itself
* @param upsertPhoto Function used to update/insert a photo into the store
*/
const PhotoInput: FC<PhotoInputProps> = ({children, label, metadata, photo, upsertPhoto}) => {
// Create references to the hidden file inputs
const hiddenPhotoCaptureInputRef = useRef<HTMLInputElement>(null)
const PhotoInput: FC<PhotoInputProps> = ({ children, label, photos, upsertPhoto, removeAttachment, id }) => {
const hiddenPhotoUploadInputRef = useRef<HTMLInputElement>(null)

const [cameraAvailable, setCameraAvailable] = useState(false)

// Handle button clicks
const handlePhotoCaptureButtonClick = (event: MouseEvent<HTMLButtonElement>) => {
hiddenPhotoCaptureInputRef.current && hiddenPhotoCaptureInputRef.current.click()
}
const hiddenCameraInputRef = useRef<HTMLInputElement>(null)
const photoIds = [photos.map((photo) => photo.id.split('~').pop())]
const [photoId, setPhotoId] = useState(photoIds.length > 0 ? Math.max(photoIds as any as number) : 0)
const isMobile = /Mobi/.test(navigator.userAgent)
const handlePhotoGalleryButtonClick = (event: MouseEvent<HTMLButtonElement>) => {
if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
}
hiddenPhotoUploadInputRef.current && hiddenPhotoUploadInputRef.current.click()
}

useEffect(() => {
if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({ video: true })
.then(() => {
setCameraAvailable(true)
});
}
const handleCameraButtonClick = (event: MouseEvent<HTMLButtonElement>) => {
hiddenCameraInputRef.current && hiddenCameraInputRef.current.click()
}

})
const handleFileInputChange = async (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files && event.target.files.length > 0) {
const files = Array.from(event.target.files)
for (const file of files) {
const imageBlobReduce = new ImageBlobReduce()
setPhotoId(photoId + 1)
const blob = await imageBlobReduce.toBlob(file)
const blobId = `${id}~${photoId.toString()}`
upsertPhoto(blob, blobId)
}

const handleFileInputChange = (event: ChangeEvent<HTMLInputElement>) => {
if (event.target.files) {
const file = event.target.files[0]
upsertPhoto(file)
event.target.value = ''
}
}

const handleFileDelete = (id: string) => {
removeAttachment(id)
}

return (
<>
<Card style={{pageBreakBefore: 'always', marginBottom: '1rem'}}>
<Card style={{ pageBreakBefore: 'always', marginBottom: '1rem' }}>
<Card.Body>
<Collapsible header={label}>
{/* Card.Text renders a <p> by defult. The children come from markdown
and may be a <p>. Nested <p>s are not allowed, so we use a <div>*/}
<Card.Text as="div">
{children}
</Card.Text>
<Card.Text as="div">{children}</Card.Text>
</Collapsible>
<div>
{/* {(cameraAvailable || cameraAvailable) &&
<Button onClick={handlePhotoCaptureButtonClick}
variant="outline-primary">
<TfiCamera/> Camera</Button>
} */}
<Button onClick={handlePhotoGalleryButtonClick}
variant="outline-primary"><TfiGallery/> Add Photo</Button>
{( isMobile &&
<Button onClick={handleCameraButtonClick} variant="outline-primary">
<TfiCamera /> Camera
</Button>
)}
<Button onClick={handlePhotoGalleryButtonClick} variant="outline-primary">
<TfiGallery /> Add Photo
</Button>
</div>
{/* <input
<input
accept="image/jpeg"
capture="environment"
onChange={handleFileInputChange}
ref={hiddenPhotoCaptureInputRef}
style={{display: 'none'}}
ref={hiddenCameraInputRef}
style={{ display: 'none' }}
type="file"
/> */}
capture="environment"
/>
<input
accept="image/jpeg"
multiple
onChange={handleFileInputChange}
ref={hiddenPhotoUploadInputRef}
style={{display: 'none'}}
style={{ display: 'none' }}
type="file"
/>
{photo && (
{photos.length > 0 && (
<>
<Image src={URL.createObjectURL(photo)} thumbnail />
<br />
<small>
Timestamp: {
metadata?.timestamp ? (<span>{metadata.timestamp}</span>) :
(<span>Missing</span>)
}
<br />
Geolocation: {
metadata?.geolocation?.latitude && metadata?.geolocation?.latitude?.deg.toString() !== 'NaN' &&
metadata?.geolocation?.longitude && metadata?.geolocation?.longitude?.deg.toString() !== 'NaN' ?
<span><GpsCoordStr {...metadata.geolocation.latitude} /> <GpsCoordStr {...metadata.geolocation.longitude} /></span> :
<span>Missing</span>
}
</small>
{photos.map((photo, index) => (
<div key={index}>
<Photo id={photo.id} photo={photo.data.blob} metadata={photo.data.metadata} label='' description='' required={false} deletePhoto={handleFileDelete}/>
</div>
))}
</>
)}
</Card.Body>
</Card>
</>
);
};
)
}

export default PhotoInput
19 changes: 12 additions & 7 deletions src/components/photo_input_wrapper.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import ImageBlobReduce from 'image-blob-reduce'
import React, {FC} from 'react'
import React, {FC, useState} from 'react'

import {StoreContext} from './store'
import PhotoInput from './photo_input'
Expand All @@ -14,6 +14,12 @@ interface PhotoInputWrapperProps {
label: string
}

export const filterAttachmentsByIdPrefix = (attachments: { [s: string]: unknown } | ArrayLike<unknown>, idPrefix: string)=> {
return Object.entries(attachments).filter((attachment: any) => attachment[0].startsWith(idPrefix)).map((attachment: any) => {
return {id: attachment[0], data: attachment[1] }
})
}

/**
* A component that wraps a PhotoInput component in order to tie it to the data store
*
Expand All @@ -27,22 +33,21 @@ const PhotoInputWrapper: FC<PhotoInputWrapperProps> = ({children, id, label}) =>

return (
<StoreContext.Consumer>
{({attachments, upsertAttachment}) => {

const upsertPhoto = (img_file: Blob) => {
{({attachments, upsertAttachment, removeAttachment}) => {

const upsertPhoto = (img_file: Blob, photoId: string) => {
// Reduce the image size as needed
ImageBlobReduce()
.toBlob(img_file, {max: MAX_IMAGE_DIM})
.then(blob => {
upsertAttachment(blob, id)
upsertAttachment(blob, photoId)
})
}
const photos = filterAttachmentsByIdPrefix(attachments, id)

return (
<PhotoInput children={children} label={label}
metadata={(attachments[id]?.metadata as unknown) as PhotoMetadata}
photo={attachments[id]?.blob} upsertPhoto={upsertPhoto}
photos={photos} upsertPhoto={upsertPhoto} id={id} removeAttachment={removeAttachment}
/>
)
}}
Expand Down
20 changes: 16 additions & 4 deletions src/components/photo_wrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import React, {FC} from 'react'
import {StoreContext} from './store'
import Photo from './photo'
import PhotoMetadata from '../types/photo_metadata.type'
import { filterAttachmentsByIdPrefix } from './photo_input_wrapper'


interface PhotoWrapperProps {
Expand All @@ -29,11 +30,22 @@ const PhotoWrapper: FC<PhotoWrapperProps> = ({children, id, label, required}) =>
return (
<StoreContext.Consumer>
{({attachments, data}) => {
const photos = filterAttachmentsByIdPrefix(attachments, id)

return (
<Photo description={children} id={id} label={label}
metadata={(attachments[id]?.metadata as unknown) as PhotoMetadata}
photo={attachments[id]?.blob} required={required}
/>
<div className='photo-display-container' style={{ display: 'flex', flexWrap: 'wrap' }}>
{ photos.map((photo, index) => {
return(
<div key={index} style={{ flexBasis: photos.length % 2 === 1 && photos.length > 1 ? '50%' : '100%' }}>
<Photo description={children} id={photo.id} label={label}
metadata={photo.data.metadata}
photo={photo.data.blob} required={required}
/>
</div>
)
})
}
</div>
)
}}
</StoreContext.Consumer>
Expand Down
43 changes: 43 additions & 0 deletions src/components/store.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ interface UpsertAttachment {
(blob: Blob, id: string): void;
}

interface RemoveAttachment {
(id: string): void;
}

interface UpsertData {
(pathStr: string, data: any): void;
}
Expand All @@ -31,7 +35,11 @@ export const StoreContext = React.createContext({
metadata: {} as any,
upsertAttachment: ((blob: Blob, id: any) => {}) as UpsertAttachment,
upsertData: ((pathStr: string, data: any) => {}) as UpsertData,
<<<<<<< HEAD
removeAttachment: ((id: string) => {}) as RemoveAttachment,
=======
upsertDoc: ((pathStr: string, data: any) => {}) as UpsertDoc,
>>>>>>> origin
});


Expand Down Expand Up @@ -307,8 +315,43 @@ export const StoreProvider: FC<StoreProviderProps> = ({ children, dbName, docId
}
};

const removeAttachment: RemoveAttachment = async (id: string) => {
// Remove the attachment from memory
const newAttachments = { ...attachments }
delete newAttachments[id]
setAttachments(newAttachments)

// Remove the attachment from the database
const removeBlobDB = async (rev: string): Promise<PouchDB.Core.Response | null> => {
let result = null
if (db) {
try {
result = await db.removeAttachment(docId, id, rev)
} catch (err) {
// Try again with the latest rev value
const doc = await db.get(docId)
result = await removeBlobDB(doc._rev)
} finally {
if (result) {
revisionRef.current = result.rev
}
}
}
return result
}

if (revisionRef.current) {
await removeBlobDB(revisionRef.current)
}
};


return (
<<<<<<< HEAD
<StoreContext.Provider value={{attachments, doc, upsertAttachment, upsertData, removeAttachment }}>
=======
<StoreContext.Provider value={{attachments, data, metadata, upsertAttachment, upsertData}}>
>>>>>>> origin
{children}
</StoreContext.Provider>
);
Expand Down
Loading