Skip to content

Commit

Permalink
feat: Download file on mobile viewer on press
Browse files Browse the repository at this point in the history
We want to download file on mobile viewer on press (so when we put
the finger on the screen) and not on tap (so when we put the finger
on the screen and we release it).

I added a throttle to avoid download multiple time the same file
because we can no use anymore 'tapCount' with press which was used to
avoid download 3 times the file if we tapped 3 times.

I also moved to useMemo instead of useCallback to support throttle
(see facebook/react#19240).
  • Loading branch information
zatteo committed Oct 30, 2024
1 parent 30c23cd commit 3c38062
Showing 1 changed file with 24 additions and 17 deletions.
41 changes: 24 additions & 17 deletions packages/cozy-viewer/src/ViewersByFile/PdfMobileViewer.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import throttle from 'lodash/throttle'
import PropTypes from 'prop-types'
import React, { useState, useEffect, useRef, useCallback } from 'react'
import React, { useState, useEffect, useRef, useMemo } from 'react'

import { useClient } from 'cozy-client'
import { downloadFile } from 'cozy-client/dist/models/file'
Expand Down Expand Up @@ -32,36 +33,42 @@ export const PdfMobileViewer = ({ file, url, t, gestures }) => {
setLoading(false)
}

const handleOnClick = useCallback(
async file => {
try {
await downloadFile({ client, file, webviewIntent })
} catch (error) {
showAlert({
message: t('Viewer.error.generic'),
severity: 'error',
variant: 'filled',
icon: false
})
}
},
const handleOnClick = useMemo(
() =>
throttle(
async file => {
try {
await downloadFile({ client, file, webviewIntent })
} catch (error) {
showAlert({
message: t('Viewer.error.generic'),
severity: 'error',
variant: 'filled',
icon: false
})
}
},
1000,
{ trailing: false }
),
[client, showAlert, t, webviewIntent]
)

useEffect(() => {
if (gestures) {
gestures.get('pinch').set({ enable: true })
gestures.on('pinchend tap', evt => {
gestures.get('press').set({ time: 1 })
gestures.on('pinchend press', evt => {
if (
(evt.type === 'pinchend' || evt.tapCount === 1) &&
(evt.type === 'pinchend' || evt.type === 'press') &&
evt.target === imgRef.current
) {
handleOnClick(file)
}
})

return () => {
gestures.off('pinchend tap')
gestures.off('pinchend press')
}
}
}, [client, gestures, file, handleOnClick])
Expand Down

0 comments on commit 3c38062

Please sign in to comment.