fix(pdf): scaling on resize, add avatars to counterpart select
All checks were successful
Open PR on Staging / audit_and_check (pull_request) Successful in 34s

This commit is contained in:
enes 2024-08-27 15:24:19 +02:00
parent 8c5be3713d
commit 4712031615
10 changed files with 185 additions and 44 deletions

23
package-lock.json generated
View File

@ -1,13 +1,14 @@
{ {
"name": "web", "name": "sigit",
"version": "0.0.0", "version": "0.0.0",
"lockfileVersion": 3, "lockfileVersion": 3,
"requires": true, "requires": true,
"packages": { "packages": {
"": { "": {
"name": "web", "name": "sigit",
"version": "0.0.0", "version": "0.0.0",
"hasInstallScript": true, "hasInstallScript": true,
"license": "AGPL-3.0-or-later ",
"dependencies": { "dependencies": {
"@emotion/react": "11.11.4", "@emotion/react": "11.11.4",
"@emotion/styled": "11.11.0", "@emotion/styled": "11.11.0",
@ -40,6 +41,7 @@
"react-dropzone": "^14.2.3", "react-dropzone": "^14.2.3",
"react-redux": "9.1.0", "react-redux": "9.1.0",
"react-router-dom": "6.22.1", "react-router-dom": "6.22.1",
"react-singleton-hook": "^4.0.1",
"react-toastify": "10.0.4", "react-toastify": "10.0.4",
"redux": "5.0.1", "redux": "5.0.1",
"tseep": "1.2.1" "tseep": "1.2.1"
@ -5832,6 +5834,23 @@
"react-dom": ">=16.8" "react-dom": ">=16.8"
} }
}, },
"node_modules/react-singleton-hook": {
"version": "4.0.1",
"resolved": "https://registry.npmjs.org/react-singleton-hook/-/react-singleton-hook-4.0.1.tgz",
"integrity": "sha512-fWuk8VxcZPChrkQasDLM8pgd/7kyi+Cr/5FfCiD99FicjEru+JmtEZNnN4lJ8Z7KbqAST5CYPlpz6lmNsZFGNw==",
"license": "MIT",
"peerDependencies": {
"react": "18"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
},
"react-native": {
"optional": true
}
}
},
"node_modules/react-toastify": { "node_modules/react-toastify": {
"version": "10.0.4", "version": "10.0.4",
"resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-10.0.4.tgz", "resolved": "https://registry.npmjs.org/react-toastify/-/react-toastify-10.0.4.tgz",

View File

@ -51,6 +51,7 @@
"react-dropzone": "^14.2.3", "react-dropzone": "^14.2.3",
"react-redux": "9.1.0", "react-redux": "9.1.0",
"react-router-dom": "6.22.1", "react-router-dom": "6.22.1",
"react-singleton-hook": "^4.0.1",
"react-toastify": "10.0.4", "react-toastify": "10.0.4",
"redux": "5.0.1", "redux": "5.0.1",
"tseep": "1.2.1" "tseep": "1.2.1"
@ -82,4 +83,4 @@
], ],
"*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}": "npm run formatter:staged" "*.{ts,tsx,js,jsx,html,css,sass,less,yml,md,graphql}": "npm run formatter:staged"
} }
} }

View File

@ -4,6 +4,8 @@ import {
CircularProgress, CircularProgress,
FormControl, FormControl,
InputLabel, InputLabel,
ListItemIcon,
ListItemText,
MenuItem, MenuItem,
Select Select
} from '@mui/material' } from '@mui/material'
@ -13,11 +15,13 @@ import * as PDFJS from 'pdfjs-dist'
import { ProfileMetadata, User, UserRole } from '../../types' import { ProfileMetadata, User, UserRole } from '../../types'
import { MouseState, PdfPage, DrawnField, DrawTool } from '../../types/drawing' import { MouseState, PdfPage, DrawnField, DrawTool } from '../../types/drawing'
import { truncate } from 'lodash' import { truncate } from 'lodash'
import { settleAllFullfilfedPromises, hexToNpub } from '../../utils' import { settleAllFullfilfedPromises, hexToNpub, npubToHex } from '../../utils'
import { getSigitFile, SigitFile } from '../../utils/file' import { getSigitFile, SigitFile } from '../../utils/file'
import { FileDivider } from '../FileDivider' import { FileDivider } from '../FileDivider'
import { ExtensionFileBox } from '../ExtensionFileBox' import { ExtensionFileBox } from '../ExtensionFileBox'
import { inPx } from '../../utils/pdf' import { inPx } from '../../utils/pdf'
import { useScale } from '../../hooks/useScale'
import { AvatarIconButton } from '../UserAvatarIconButton'
PDFJS.GlobalWorkerOptions.workerSrc = new URL( PDFJS.GlobalWorkerOptions.workerSrc = new URL(
'pdfjs-dist/build/pdf.worker.min.mjs', 'pdfjs-dist/build/pdf.worker.min.mjs',
@ -34,6 +38,7 @@ interface Props {
export const DrawPDFFields = (props: Props) => { export const DrawPDFFields = (props: Props) => {
const { selectedFiles, selectedTool, onDrawFieldsChange, users } = props const { selectedFiles, selectedTool, onDrawFieldsChange, users } = props
const { to, from } = useScale()
const [sigitFiles, setSigitFiles] = useState<SigitFile[]>([]) const [sigitFiles, setSigitFiles] = useState<SigitFile[]>([])
const [parsingPdf, setIsParsing] = useState<boolean>(false) const [parsingPdf, setIsParsing] = useState<boolean>(false)
@ -106,8 +111,8 @@ export const DrawPDFFields = (props: Props) => {
const { mouseX, mouseY } = getMouseCoordinates(event) const { mouseX, mouseY } = getMouseCoordinates(event)
const newField: DrawnField = { const newField: DrawnField = {
left: mouseX / page.scale, left: to(page.width, mouseX),
top: mouseY / page.scale, top: to(page.width, mouseY),
width: 0, width: 0,
height: 0, height: 0,
counterpart: '', counterpart: '',
@ -161,8 +166,8 @@ export const DrawPDFFields = (props: Props) => {
const { mouseX, mouseY } = getMouseCoordinates(event) const { mouseX, mouseY } = getMouseCoordinates(event)
const width = mouseX / page.scale - lastDrawnField.left const width = to(page.width, mouseX) - lastDrawnField.left
const height = mouseY / page.scale - lastDrawnField.top const height = to(page.width, mouseY) - lastDrawnField.top
lastDrawnField.width = width lastDrawnField.width = width
lastDrawnField.height = height lastDrawnField.height = height
@ -211,7 +216,7 @@ export const DrawPDFFields = (props: Props) => {
const onDrawnFieldMouseMove = ( const onDrawnFieldMouseMove = (
event: React.MouseEvent<HTMLDivElement>, event: React.MouseEvent<HTMLDivElement>,
drawnField: DrawnField, drawnField: DrawnField,
scale: number pageWidth: number
) => { ) => {
if (mouseState.dragging) { if (mouseState.dragging) {
const { mouseX, mouseY, rect } = getMouseCoordinates( const { mouseX, mouseY, rect } = getMouseCoordinates(
@ -221,11 +226,11 @@ export const DrawPDFFields = (props: Props) => {
const coordsOffset = mouseState.coordsInWrapper const coordsOffset = mouseState.coordsInWrapper
if (coordsOffset) { if (coordsOffset) {
let left = (mouseX - coordsOffset.mouseX) / scale let left = to(pageWidth, mouseX - coordsOffset.mouseX)
let top = (mouseY - coordsOffset.mouseY) / scale let top = to(pageWidth, mouseY - coordsOffset.mouseY)
const rightLimit = rect.width / scale - drawnField.width - 3 const rightLimit = to(pageWidth, rect.width) - drawnField.width - 3
const bottomLimit = rect.height / scale - drawnField.height - 3 const bottomLimit = to(pageWidth, rect.height) - drawnField.height - 3
if (left < 0) left = 0 if (left < 0) left = 0
if (top < 0) top = 0 if (top < 0) top = 0
@ -266,7 +271,7 @@ export const DrawPDFFields = (props: Props) => {
const onResizeHandleMouseMove = ( const onResizeHandleMouseMove = (
event: React.MouseEvent<HTMLSpanElement>, event: React.MouseEvent<HTMLSpanElement>,
drawnField: DrawnField, drawnField: DrawnField,
scale: number pageWidth: number
) => { ) => {
if (mouseState.resizing) { if (mouseState.resizing) {
const { mouseX, mouseY } = getMouseCoordinates( const { mouseX, mouseY } = getMouseCoordinates(
@ -277,8 +282,8 @@ export const DrawPDFFields = (props: Props) => {
event.currentTarget.parentElement?.parentElement event.currentTarget.parentElement?.parentElement
) )
const width = mouseX / scale - drawnField.left const width = to(pageWidth, mouseX) - drawnField.left
const height = mouseY / scale - drawnField.top const height = to(pageWidth, mouseY) - drawnField.top
drawnField.width = width drawnField.width = width
drawnField.height = height drawnField.height = height
@ -375,21 +380,21 @@ export const DrawPDFFields = (props: Props) => {
key={drawnFieldIndex} key={drawnFieldIndex}
onMouseDown={onDrawnFieldMouseDown} onMouseDown={onDrawnFieldMouseDown}
onMouseMove={(event) => { onMouseMove={(event) => {
onDrawnFieldMouseMove(event, drawnField, page.scale) onDrawnFieldMouseMove(event, drawnField, page.width)
}} }}
className={styles.drawingRectangle} className={styles.drawingRectangle}
style={{ style={{
left: inPx(drawnField.left * page.scale), left: inPx(from(page.width, drawnField.left)),
top: inPx(drawnField.top * page.scale), top: inPx(from(page.width, drawnField.top)),
width: inPx(drawnField.width * page.scale), width: inPx(from(page.width, drawnField.width)),
height: inPx(drawnField.height * page.scale), height: inPx(from(page.width, drawnField.height)),
pointerEvents: mouseState.clicked ? 'none' : 'all' pointerEvents: mouseState.clicked ? 'none' : 'all'
}} }}
> >
<span <span
onMouseDown={onResizeHandleMouseDown} onMouseDown={onResizeHandleMouseDown}
onMouseMove={(event) => { onMouseMove={(event) => {
onResizeHandleMouseMove(event, drawnField, page.scale) onResizeHandleMouseMove(event, drawnField, page.width)
}} }}
className={styles.resizeHandle} className={styles.resizeHandle}
></span> ></span>
@ -423,6 +428,9 @@ export const DrawPDFFields = (props: Props) => {
sx={{ sx={{
background: 'white' background: 'white'
}} }}
renderValue={(value) =>
renderCounterpartValue(drawnField, value)
}
> >
{users {users
.filter((u) => u.role === UserRole.signer) .filter((u) => u.role === UserRole.signer)
@ -451,7 +459,22 @@ export const DrawPDFFields = (props: Props) => {
key={index} key={index}
value={hexToNpub(user.pubkey)} value={hexToNpub(user.pubkey)}
> >
{displayValue} <ListItemIcon>
<AvatarIconButton
src={metadata?.picture}
hexKey={user.pubkey}
aria-label={`account of user ${displayValue}`}
color="inherit"
sx={{
padding: 0,
'> img': {
width: '30px',
height: '30px'
}
}}
/>
</ListItemIcon>
<ListItemText>{displayValue}</ListItemText>
</MenuItem> </MenuItem>
) )
})} })}
@ -468,6 +491,45 @@ export const DrawPDFFields = (props: Props) => {
) )
} }
const renderCounterpartValue = (drawnField: DrawnField, value: string) => {
const user = users.find((u) => u.pubkey === npubToHex(value))
if (user) {
let displayValue = truncate(value, {
length: 16
})
const metadata = props.metadata[value]
if (metadata) {
displayValue = truncate(
metadata.name || metadata.display_name || metadata.username || value,
{
length: 16
}
)
}
return (
<>
<AvatarIconButton
src={props.metadata[drawnField.counterpart]?.picture}
hexKey={npubToHex(drawnField.counterpart) || undefined}
sx={{
padding: 0,
marginRight: '6px',
'> img': {
width: '21px',
height: '21px'
}
}}
/>
{displayValue}
</>
)
}
return value
}
if (parsingPdf) { if (parsingPdf) {
return ( return (
<Box sx={{ width: '100%', textAlign: 'center' }}> <Box sx={{ width: '100%', textAlign: 'center' }}>

View File

@ -73,7 +73,7 @@
justify-content: center; justify-content: center;
align-items: center; align-items: center;
bottom: -60px; bottom: -60px;
min-width: 170px; min-width: 193px;
min-height: 30px; min-height: 30px;
padding: 5px 0; padding: 5px 0;
} }

View File

@ -1,13 +1,14 @@
import { CurrentUserMark } from '../../types/mark.ts' import { CurrentUserMark } from '../../types/mark.ts'
import styles from '../DrawPDFFields/style.module.scss' import styles from '../DrawPDFFields/style.module.scss'
import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts' import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts'
import { useScale } from '../../hooks/useScale.tsx'
interface PdfMarkItemProps { interface PdfMarkItemProps {
userMark: CurrentUserMark userMark: CurrentUserMark
handleMarkClick: (id: number) => void handleMarkClick: (id: number) => void
selectedMarkValue: string selectedMarkValue: string
selectedMark: CurrentUserMark | null selectedMark: CurrentUserMark | null
scale: number pageWidth: number
} }
/** /**
@ -18,24 +19,25 @@ const PdfMarkItem = ({
handleMarkClick, handleMarkClick,
selectedMarkValue, selectedMarkValue,
userMark, userMark,
scale pageWidth
}: PdfMarkItemProps) => { }: PdfMarkItemProps) => {
const { location } = userMark.mark const { location } = userMark.mark
const handleClick = () => handleMarkClick(userMark.mark.id) const handleClick = () => handleMarkClick(userMark.mark.id)
const isEdited = () => selectedMark?.mark.id === userMark.mark.id const isEdited = () => selectedMark?.mark.id === userMark.mark.id
const getMarkValue = () => const getMarkValue = () =>
isEdited() ? selectedMarkValue : userMark.currentValue isEdited() ? selectedMarkValue : userMark.currentValue
const { from } = useScale()
return ( return (
<div <div
onClick={handleClick} onClick={handleClick}
className={`file-mark ${styles.drawingRectangle} ${isEdited() && styles.edited}`} className={`file-mark ${styles.drawingRectangle} ${isEdited() && styles.edited}`}
style={{ style={{
left: inPx(location.left * scale), left: inPx(from(pageWidth, location.left)),
top: inPx(location.top * scale), top: inPx(from(pageWidth, location.top)),
width: inPx(location.width * scale), width: inPx(from(pageWidth, location.width)),
height: inPx(location.height * scale), height: inPx(from(pageWidth, location.height)),
fontFamily: FONT_TYPE, fontFamily: FONT_TYPE,
fontSize: inPx(FONT_SIZE * scale) fontSize: inPx(from(pageWidth, FONT_SIZE))
}} }}
> >
{getMarkValue()} {getMarkValue()}

View File

@ -5,6 +5,7 @@ import PdfMarkItem from './PdfMarkItem.tsx'
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
import pdfViewStyles from './style.module.scss' import pdfViewStyles from './style.module.scss'
import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts' import { FONT_SIZE, FONT_TYPE, inPx } from '../../utils/pdf.ts'
import { useScale } from '../../hooks/useScale.tsx'
interface PdfPageProps { interface PdfPageProps {
currentUserMarks: CurrentUserMark[] currentUserMarks: CurrentUserMark[]
handleMarkClick: (id: number) => void handleMarkClick: (id: number) => void
@ -33,6 +34,8 @@ const PdfPageItem = ({
} }
}, [selectedMark]) }, [selectedMark])
const markRefs = useRef<(HTMLDivElement | null)[]>([]) const markRefs = useRef<(HTMLDivElement | null)[]>([])
const { from } = useScale()
return ( return (
<div className={`image-wrapper ${styles.pdfImageWrapper}`}> <div className={`image-wrapper ${styles.pdfImageWrapper}`}>
<img draggable="false" src={page.image} /> <img draggable="false" src={page.image} />
@ -44,7 +47,7 @@ const PdfPageItem = ({
selectedMarkValue={selectedMarkValue} selectedMarkValue={selectedMarkValue}
userMark={m} userMark={m}
selectedMark={selectedMark} selectedMark={selectedMark}
scale={page.scale} pageWidth={page.width}
/> />
</div> </div>
))} ))}
@ -54,12 +57,12 @@ const PdfPageItem = ({
key={i} key={i}
className={pdfViewStyles.otherUserMarksDisplay} className={pdfViewStyles.otherUserMarksDisplay}
style={{ style={{
left: inPx(m.location.left * page.scale), left: inPx(from(page.width, m.location.left)),
top: inPx(m.location.top * page.scale), top: inPx(from(page.width, m.location.top)),
width: inPx(m.location.width * page.scale), width: inPx(from(page.width, m.location.width)),
height: inPx(m.location.height * page.scale), height: inPx(from(page.width, m.location.height)),
fontFamily: FONT_TYPE, fontFamily: FONT_TYPE,
fontSize: inPx(FONT_SIZE * page.scale) fontSize: inPx(from(page.width, FONT_SIZE))
}} }}
> >
{m.value} {m.value}

52
src/hooks/useScale.tsx Normal file
View File

@ -0,0 +1,52 @@
import { useEffect, useState } from 'react'
import { singletonHook } from 'react-singleton-hook'
const noScaleInit = {
to: (_: number, v: number) => v,
from: (_: number, v: number) => v
}
const useScaleImpl = () => {
const [width, setWidth] = useState(
document.querySelector('#content-preview > *')?.clientWidth || 1
)
// Get the scale based on the original width
const scale = (originalWidth: number) => {
return width / originalWidth
}
// Get the original pixel value
const to = (originalWidth: number, value: number) => {
return value / scale(originalWidth)
}
// Get the scaled pixel value
const from = (originalWidth: number, value: number) => {
return value * scale(originalWidth)
}
useEffect(() => {
const resize = () => {
// Fetch the first container element we find
const element = document.querySelector('#content-preview > *')
// Set the width state
if (element) {
setWidth(element.clientWidth)
}
}
resize()
window.addEventListener('resize', resize)
return () => {
window.removeEventListener('resize', resize)
}
}, [])
return { to, from }
}
export const useScale = singletonHook(noScaleInit, useScaleImpl, {
unmountIfNoConsumers: true
})

View File

@ -52,6 +52,7 @@ import React from 'react'
import { convertToSigitFile, SigitFile } from '../../utils/file.ts' import { convertToSigitFile, SigitFile } from '../../utils/file.ts'
import { FileDivider } from '../../components/FileDivider.tsx' import { FileDivider } from '../../components/FileDivider.tsx'
import { ExtensionFileBox } from '../../components/ExtensionFileBox.tsx' import { ExtensionFileBox } from '../../components/ExtensionFileBox.tsx'
import { useScale } from '../../hooks/useScale.tsx'
interface PdfViewProps { interface PdfViewProps {
files: CurrentUserFile[] files: CurrentUserFile[]
@ -67,6 +68,7 @@ const SlimPdfView = ({
parsedSignatureEvents parsedSignatureEvents
}: PdfViewProps) => { }: PdfViewProps) => {
const pdfRefs = useRef<(HTMLDivElement | null)[]>([]) const pdfRefs = useRef<(HTMLDivElement | null)[]>([])
const { from } = useScale()
useEffect(() => { useEffect(() => {
if (currentFile !== null && !!pdfRefs.current[currentFile.id]) { if (currentFile !== null && !!pdfRefs.current[currentFile.id]) {
pdfRefs.current[currentFile.id]?.scrollIntoView({ pdfRefs.current[currentFile.id]?.scrollIntoView({
@ -110,12 +112,12 @@ const SlimPdfView = ({
className={`file-mark ${styles.mark}`} className={`file-mark ${styles.mark}`}
key={m.id} key={m.id}
style={{ style={{
left: inPx(m.location.left * page.scale), left: inPx(from(page.width, m.location.left)),
top: inPx(m.location.top * page.scale), top: inPx(from(page.width, m.location.top)),
width: inPx(m.location.width * page.scale), width: inPx(from(page.width, m.location.width)),
height: inPx(m.location.height * page.scale), height: inPx(from(page.width, m.location.height)),
fontFamily: FONT_TYPE, fontFamily: FONT_TYPE,
fontSize: inPx(FONT_SIZE * page.scale) fontSize: inPx(from(page.width, FONT_SIZE))
}} }}
> >
{m.value} {m.value}

View File

@ -12,7 +12,7 @@ export interface MouseState {
export interface PdfPage { export interface PdfPage {
image: string image: string
scale: number width: number
drawnFields: DrawnField[] drawnFields: DrawnField[]
} }

View File

@ -85,7 +85,7 @@ export const pdfToImages = async (
await page.render({ canvasContext: context!, viewport: viewport }).promise await page.render({ canvasContext: context!, viewport: viewport }).promise
pages.push({ pages.push({
image: canvas.toDataURL(), image: canvas.toDataURL(),
scale, width: originalViewport.width,
drawnFields: [] drawnFields: []
}) })
} }