From afd5b67c8a0ba2487c19ea1880f47bbff1dd09a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Th=C3=A9o=20Poizat?= Date: Wed, 30 Oct 2024 15:03:26 +0100 Subject: [PATCH] feat: Download file on mobile viewer on press 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 https://github.com/facebook/react/issues/19240). --- .../src/ViewersByFile/PdfMobileViewer.jsx | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/packages/cozy-viewer/src/ViewersByFile/PdfMobileViewer.jsx b/packages/cozy-viewer/src/ViewersByFile/PdfMobileViewer.jsx index cee9900ca0..4aa79769c5 100644 --- a/packages/cozy-viewer/src/ViewersByFile/PdfMobileViewer.jsx +++ b/packages/cozy-viewer/src/ViewersByFile/PdfMobileViewer.jsx @@ -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' @@ -32,28 +33,34 @@ 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) @@ -61,7 +68,7 @@ export const PdfMobileViewer = ({ file, url, t, gestures }) => { }) return () => { - gestures.off('pinchend tap') + gestures.off('pinchend press') } } }, [client, gestures, file, handleOnClick])