From ed0158e8177b79a56124c57569f5cba81d57b40b Mon Sep 17 00:00:00 2001 From: Eugene Date: Sun, 11 Aug 2024 22:19:26 +0300 Subject: [PATCH 01/27] feat(pdf-marking): updates design and functionality of the pdf marking form --- .../DrawPDFFields/style.module.scss | 4 + src/components/MarkFormField/index.tsx | 102 ++++++++++ .../MarkFormField/style.module.scss | 187 ++++++++++++++++++ src/components/PDFView/PdfMarkItem.tsx | 27 +-- src/components/PDFView/PdfMarking.tsx | 118 ++++++----- src/pages/sign/MarkFormField.tsx | 37 ---- src/types/mark.ts | 26 +-- src/utils/const.ts | 4 +- src/utils/mark.ts | 68 +++++-- 9 files changed, 450 insertions(+), 123 deletions(-) create mode 100644 src/components/MarkFormField/index.tsx create mode 100644 src/components/MarkFormField/style.module.scss delete mode 100644 src/pages/sign/MarkFormField.tsx diff --git a/src/components/DrawPDFFields/style.module.scss b/src/components/DrawPDFFields/style.module.scss index e3e7856..f1993eb 100644 --- a/src/components/DrawPDFFields/style.module.scss +++ b/src/components/DrawPDFFields/style.module.scss @@ -71,6 +71,10 @@ visibility: hidden; } + &.edited { + border: 1px dotted #01aaad + } + .resizeHandle { position: absolute; right: -5px; diff --git a/src/components/MarkFormField/index.tsx b/src/components/MarkFormField/index.tsx new file mode 100644 index 0000000..71f6668 --- /dev/null +++ b/src/components/MarkFormField/index.tsx @@ -0,0 +1,102 @@ +import { CurrentUserMark } from '../../types/mark.ts' +import styles from './style.module.scss' + +import { MARK_TYPE_TRANSLATION, NEXT, SIGN } from '../../utils/const.ts' +import { + findNextIncompleteCurrentUserMark, + isCurrentUserMarksComplete, + isCurrentValueLast +} from '../../utils' + +interface MarkFormFieldProps { + handleSubmit: (event: any) => void + handleSelectedMarkValueChange: (event: any) => void + selectedMark: CurrentUserMark + selectedMarkValue: string + currentUserMarks: CurrentUserMark[] + handleCurrentUserMarkChange: (mark: CurrentUserMark) => void +} + +/** + * Responsible for rendering a form field connected to a mark and keeping track of its value. + */ +const MarkFormField = ({ + handleSubmit, + handleSelectedMarkValueChange, + selectedMark, + selectedMarkValue, + currentUserMarks, + handleCurrentUserMarkChange +}: MarkFormFieldProps) => { + const getSubmitButtonText = () => (isReadyToSign() ? SIGN : NEXT) + const isReadyToSign = () => + isCurrentUserMarksComplete(currentUserMarks) || + isCurrentValueLast(currentUserMarks, selectedMark, selectedMarkValue) + const isCurrent = (currentMark: CurrentUserMark) => + currentMark.id === selectedMark.id + const isDone = (currentMark: CurrentUserMark) => currentMark.isCompleted + const findNext = () => { + return ( + currentUserMarks[selectedMark.id] || + findNextIncompleteCurrentUserMark(currentUserMarks) + ) + } + const handleFormSubmit = (event: React.FormEvent) => { + event.preventDefault() + console.log('handle form submit runs...') + return isReadyToSign() + ? handleSubmit(event) + : handleCurrentUserMarkChange(findNext()!) + } + return ( +
+
+
+
+
+

Add your signature

+
+
+
+
handleFormSubmit(e)}> + +
+ +
+
+
+
+ {currentUserMarks.map((mark, index) => { + return ( +
+ + {isCurrent(mark) && ( +
+ )} +
+ ) + })} +
+
+
+
+
+
+ ) +} + +export default MarkFormField diff --git a/src/components/MarkFormField/style.module.scss b/src/components/MarkFormField/style.module.scss new file mode 100644 index 0000000..bff4644 --- /dev/null +++ b/src/components/MarkFormField/style.module.scss @@ -0,0 +1,187 @@ +.container { + width: 100%; + display: flex; + flex-direction: column; + position: fixed; + bottom: 0; + right: 0; + left: 0; + align-items: center; +} + +.actions { + background: white; + width: 100%; + border-radius: 4px; + padding: 10px 20px; + display: flex; + flex-direction: column; + align-items: center; + grid-gap: 15px; + box-shadow: 0 -2px 4px 0 rgb(0,0,0,0.1); + max-width: 750px; +} + +.actionsWrapper { + display: flex; + flex-direction: column; + grid-gap: 20px; + flex-grow: 1; + width: 100%; +} + +.actionsTop { + display: flex; + flex-direction: row; + grid-gap: 10px; + align-items: center; +} + +.actionsTopInfo { + flex-grow: 1; +} + +.actionsTopInfoText { + font-size: 16px; + color: #434343; +} + +.actionsTrigger { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + position: relative; +} + +.actionButtons { + display: flex; + flex-direction: row; + grid-gap: 5px; +} + +.inputWrapper { + display: flex; + flex-direction: column; + grid-gap: 10px; +} + +.textInput { + height: 100px; + background: rgba(0,0,0,0.1); + border-radius: 4px; + border: solid 2px #4c82a3; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} + +.input { + border-radius: 4px; + border: solid 1px rgba(0,0,0,0.15); + padding: 5px 10px; + font-size: 16px; + width: 100%; + background: linear-gradient(rgba(0,0,0,0.00), rgba(0,0,0,0.00) 100%), linear-gradient(white, white); +} + +.input:focus { + border: solid 1px rgba(0,0,0,0.15); + outline: none; + background: linear-gradient(rgba(0,0,0,0.05), rgba(0,0,0,0.05) 100%), linear-gradient(white, white); +} + +.actionsBottom { + display: flex; + flex-direction: row; + grid-gap: 5px; + justify-content: center; + align-items: center; +} + +button { + transition: ease 0.2s; + width: auto; + border-radius: 4px; + outline: unset; + border: unset; + background: unset; + color: #ffffff; + background: #4c82a3; + font-weight: 500; + font-size: 14px; + padding: 8px 15px; + white-space: nowrap; + display: flex; + flex-direction: row; + grid-gap: 12px; + justify-content: center; + align-items: center; + text-decoration: unset; + position: relative; + cursor: pointer; +} + +button:hover { + transition: ease 0.2s; + background: #5e8eab; + color: white; +} + +button:active { + transition: ease 0.2s; + background: #447592; + color: white; +} + +.submitButton { + width: 100%; + max-width: 300px; +} + +.footerContainer { + display: flex; + flex-direction: row; + justify-content: center; + align-items: center; +} + +.footer { + display: flex; + flex-direction: row; + grid-gap: 5px; + align-items: start; + justify-content: center; + width: 100%; +} + +.pagination { + display: flex; + flex-direction: column; + grid-gap: 5px; +} + +.paginationButton { + font-size: 12px; + padding: 5px 10px; + border-radius: 3px; + background: rgba(0,0,0,0.1); + color: rgba(0,0,0,0.5); +} + +.paginationButton:hover { + background: #447592; + color: rgba(255,255,255,0.5); +} + +.paginationButtonDone { + background: #5e8eab; + color: rgb(255,255,255); +} + +.paginationButtonCurrent { + height: 2px; + width: 100%; + background: #4c82a3; +} diff --git a/src/components/PDFView/PdfMarkItem.tsx b/src/components/PDFView/PdfMarkItem.tsx index 7a2b24b..d93c2b2 100644 --- a/src/components/PDFView/PdfMarkItem.tsx +++ b/src/components/PDFView/PdfMarkItem.tsx @@ -12,26 +12,31 @@ interface PdfMarkItemProps { /** * Responsible for display an individual Pdf Mark. */ -const PdfMarkItem = ({ selectedMark, handleMarkClick, selectedMarkValue, userMark }: PdfMarkItemProps) => { - const { location } = userMark.mark; - const handleClick = () => handleMarkClick(userMark.mark.id); - const getMarkValue = () => ( - selectedMark?.mark.id === userMark.mark.id - ? selectedMarkValue - : userMark.mark.value - ) +const PdfMarkItem = ({ + selectedMark, + handleMarkClick, + selectedMarkValue, + userMark +}: PdfMarkItemProps) => { + const { location } = userMark.mark + const handleClick = () => handleMarkClick(userMark.mark.id) + const isEdited = () => selectedMark?.mark.id === userMark.mark.id + const getMarkValue = () => + isEdited() ? selectedMarkValue : userMark.currentValue return (
{getMarkValue()}
+ > + {getMarkValue()} + ) } -export default PdfMarkItem \ No newline at end of file +export default PdfMarkItem diff --git a/src/components/PDFView/PdfMarking.tsx b/src/components/PDFView/PdfMarking.tsx index a6dc1a4..e162062 100644 --- a/src/components/PDFView/PdfMarking.tsx +++ b/src/components/PDFView/PdfMarking.tsx @@ -1,22 +1,23 @@ import PdfView from './index.tsx' -import MarkFormField from '../../pages/sign/MarkFormField.tsx' +import MarkFormField from '../MarkFormField' import { PdfFile } from '../../types/drawing.ts' import { CurrentUserMark, Mark } from '../../types/mark.ts' import React, { useState, useEffect } from 'react' import { - findNextCurrentUserMark, + findNextIncompleteCurrentUserMark, + getUpdatedMark, isCurrentUserMarksComplete, - updateCurrentUserMarks, + updateCurrentUserMarks } from '../../utils' import { EMPTY } from '../../utils/const.ts' import { Container } from '../Container' import styles from '../../pages/sign/style.module.scss' interface PdfMarkingProps { - files: { pdfFile: PdfFile, filename: string, hash: string | null }[], - currentUserMarks: CurrentUserMark[], - setIsReadyToSign: (isReadyToSign: boolean) => void, - setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void, + files: { pdfFile: PdfFile; filename: string; hash: string | null }[] + currentUserMarks: CurrentUserMark[] + setIsReadyToSign: (isReadyToSign: boolean) => void + setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void setUpdatedMarks: (markToUpdate: Mark) => void } @@ -35,66 +36,89 @@ const PdfMarking = (props: PdfMarkingProps) => { setUpdatedMarks } = props const [selectedMark, setSelectedMark] = useState(null) - const [selectedMarkValue, setSelectedMarkValue] = useState("") + const [selectedMarkValue, setSelectedMarkValue] = useState('') useEffect(() => { - setSelectedMark(findNextCurrentUserMark(currentUserMarks) || null) - }, [currentUserMarks]) + setSelectedMark(findNextIncompleteCurrentUserMark(currentUserMarks) || null) + }, []) const handleMarkClick = (id: number) => { - const nextMark = currentUserMarks.find((mark) => mark.mark.id === id); - setSelectedMark(nextMark!); - setSelectedMarkValue(nextMark?.mark.value ?? EMPTY); + const nextMark = currentUserMarks.find((mark) => mark.mark.id === id) + setSelectedMark(nextMark!) + setSelectedMarkValue(nextMark?.mark.value ?? EMPTY) + } + + const handleCurrentUserMarkChange = (mark: CurrentUserMark) => { + if (!selectedMark) return + const updatedSelectedMark: CurrentUserMark = getUpdatedMark( + selectedMark, + selectedMarkValue + ) + + const updatedCurrentUserMarks = updateCurrentUserMarks( + currentUserMarks, + updatedSelectedMark + ) + setCurrentUserMarks(updatedCurrentUserMarks) + setSelectedMark(mark) + setSelectedMarkValue(mark.currentValue ?? EMPTY) } const handleSubmit = (event: React.FormEvent) => { - event.preventDefault(); - if (!selectedMarkValue || !selectedMark) return; + event.preventDefault() + if (!selectedMarkValue || !selectedMark) return - const updatedMark: CurrentUserMark = { - ...selectedMark, - mark: { - ...selectedMark.mark, - value: selectedMarkValue - }, - isCompleted: true - } + const updatedMark: CurrentUserMark = getUpdatedMark( + selectedMark, + selectedMarkValue + ) setSelectedMarkValue(EMPTY) - const updatedCurrentUserMarks = updateCurrentUserMarks(currentUserMarks, updatedMark); + const updatedCurrentUserMarks = updateCurrentUserMarks( + currentUserMarks, + updatedMark + ) setCurrentUserMarks(updatedCurrentUserMarks) - setSelectedMark(findNextCurrentUserMark(updatedCurrentUserMarks) || null) - console.log(isCurrentUserMarksComplete(updatedCurrentUserMarks)) - setIsReadyToSign(isCurrentUserMarksComplete(updatedCurrentUserMarks)) + setSelectedMark(null) + setIsReadyToSign(true) setUpdatedMarks(updatedMark.mark) } - const handleChange = (event: React.ChangeEvent) => setSelectedMarkValue(event.target.value) + // const updateCurrentUserMarkValues = () => { + // const updatedMark: CurrentUserMark = getUpdatedMark(selectedMark!, selectedMarkValue) + // const updatedCurrentUserMarks = updateCurrentUserMarks(currentUserMarks, updatedMark) + // setSelectedMarkValue(EMPTY) + // setCurrentUserMarks(updatedCurrentUserMarks) + // } + + const handleChange = (event: React.ChangeEvent) => + setSelectedMarkValue(event.target.value) return ( <> - { - currentUserMarks?.length > 0 && ( - )} - { - selectedMark !== null && ( - - )} + {currentUserMarks?.length > 0 && ( + + )} + {selectedMark !== null && ( + + )} ) } -export default PdfMarking \ No newline at end of file +export default PdfMarking diff --git a/src/pages/sign/MarkFormField.tsx b/src/pages/sign/MarkFormField.tsx deleted file mode 100644 index 4de82a4..0000000 --- a/src/pages/sign/MarkFormField.tsx +++ /dev/null @@ -1,37 +0,0 @@ -import { CurrentUserMark } from '../../types/mark.ts' -import styles from './style.module.scss' -import { Box, Button, TextField } from '@mui/material' - -import { MARK_TYPE_TRANSLATION } from '../../utils/const.ts' - -interface MarkFormFieldProps { - handleSubmit: (event: any) => void - handleChange: (event: any) => void - selectedMark: CurrentUserMark - selectedMarkValue: string -} - -/** - * Responsible for rendering a form field connected to a mark and keeping track of its value. - */ -const MarkFormField = (props: MarkFormFieldProps) => { - const { handleSubmit, handleChange, selectedMark, selectedMarkValue } = props; - const getSubmitButton = () => selectedMark.isLast ? 'Complete' : 'Next'; - return ( -
- - - - -
- ) -} - -export default MarkFormField; \ No newline at end of file diff --git a/src/types/mark.ts b/src/types/mark.ts index 3184f95..c0f9b88 100644 --- a/src/types/mark.ts +++ b/src/types/mark.ts @@ -1,24 +1,26 @@ -import { MarkType } from "./drawing"; +import { MarkType } from './drawing' export interface CurrentUserMark { + id: number mark: Mark isLast: boolean isCompleted: boolean + currentValue?: string } export interface Mark { - id: number; - npub: string; - pdfFileHash: string; - type: MarkType; - location: MarkLocation; - value?: string; + id: number + npub: string + pdfFileHash: string + type: MarkType + location: MarkLocation + value?: string } export interface MarkLocation { - top: number; - left: number; - height: number; - width: number; - page: number; + top: number + left: number + height: number + width: number + page: number } diff --git a/src/utils/const.ts b/src/utils/const.ts index 4f8c233..2a97dfe 100644 --- a/src/utils/const.ts +++ b/src/utils/const.ts @@ -3,4 +3,6 @@ import { MarkType } from '../types/drawing.ts' export const EMPTY: string = '' export const MARK_TYPE_TRANSLATION: { [key: string]: string } = { [MarkType.FULLNAME.valueOf()]: 'Full Name' -} \ No newline at end of file +} +export const SIGN: string = 'Sign' +export const NEXT: string = 'Next' diff --git a/src/utils/mark.ts b/src/utils/mark.ts index 13cff84..18cc3e8 100644 --- a/src/utils/mark.ts +++ b/src/utils/mark.ts @@ -2,6 +2,7 @@ import { CurrentUserMark, Mark } from '../types/mark.ts' import { hexToNpub } from './nostr.ts' import { Meta, SignedEventContent } from '../types' import { Event } from 'nostr-tools' +import { EMPTY } from './const.ts' /** * Takes in an array of Marks already filtered by User. @@ -9,16 +10,18 @@ import { Event } from 'nostr-tools' * @param marks - default Marks extracted from Meta * @param signedMetaMarks - signed user Marks extracted from DocSignatures */ -const getCurrentUserMarks = (marks: Mark[], signedMetaMarks: Mark[]): CurrentUserMark[] => { +const getCurrentUserMarks = ( + marks: Mark[], + signedMetaMarks: Mark[] +): CurrentUserMark[] => { return marks.map((mark, index, arr) => { - const signedMark = signedMetaMarks.find((m) => m.id === mark.id); - if (signedMark && !!signedMark.value) { - mark.value = signedMark.value - } + const signedMark = signedMetaMarks.find((m) => m.id === mark.id) return { mark, + currentValue: signedMark?.value ?? EMPTY, + id: index + 1, isLast: isLast(index, arr), - isCompleted: !!mark.value + isCompleted: !!signedMark?.value } }) } @@ -27,8 +30,10 @@ const getCurrentUserMarks = (marks: Mark[], signedMetaMarks: Mark[]): CurrentUse * Returns next incomplete CurrentUserMark if there is one * @param usersMarks */ -const findNextCurrentUserMark = (usersMarks: CurrentUserMark[]): CurrentUserMark | undefined => { - return usersMarks.find((mark) => !mark.isCompleted); +const findNextIncompleteCurrentUserMark = ( + usersMarks: CurrentUserMark[] +): CurrentUserMark | undefined => { + return usersMarks.find((mark) => !mark.isCompleted) } /** @@ -37,7 +42,7 @@ const findNextCurrentUserMark = (usersMarks: CurrentUserMark[]): CurrentUserMark * @param pubkey */ const filterMarksByPubkey = (marks: Mark[], pubkey: string): Mark[] => { - return marks.filter(mark => mark.npub === hexToNpub(pubkey)) + return marks.filter((mark) => mark.npub === hexToNpub(pubkey)) } /** @@ -57,7 +62,9 @@ const extractMarksFromSignedMeta = (meta: Meta): Mark[] => { * marked as complete. * @param currentUserMarks */ -const isCurrentUserMarksComplete = (currentUserMarks: CurrentUserMark[]): boolean => { +const isCurrentUserMarksComplete = ( + currentUserMarks: CurrentUserMark[] +): boolean => { return currentUserMarks.every((mark) => mark.isCompleted) } @@ -68,7 +75,7 @@ const isCurrentUserMarksComplete = (currentUserMarks: CurrentUserMark[]): boolea * @param markToUpdate */ const updateMarks = (marks: Mark[], markToUpdate: Mark): Mark[] => { - const indexToUpdate = marks.findIndex(mark => mark.id === markToUpdate.id); + const indexToUpdate = marks.findIndex((mark) => mark.id === markToUpdate.id) return [ ...marks.slice(0, indexToUpdate), markToUpdate, @@ -76,8 +83,13 @@ const updateMarks = (marks: Mark[], markToUpdate: Mark): Mark[] => { ] } -const updateCurrentUserMarks = (currentUserMarks: CurrentUserMark[], markToUpdate: CurrentUserMark): CurrentUserMark[] => { - const indexToUpdate = currentUserMarks.findIndex((m) => m.mark.id === markToUpdate.mark.id) +const updateCurrentUserMarks = ( + currentUserMarks: CurrentUserMark[], + markToUpdate: CurrentUserMark +): CurrentUserMark[] => { + const indexToUpdate = currentUserMarks.findIndex( + (m) => m.mark.id === markToUpdate.mark.id + ) return [ ...currentUserMarks.slice(0, indexToUpdate), markToUpdate, @@ -85,14 +97,40 @@ const updateCurrentUserMarks = (currentUserMarks: CurrentUserMark[], markToUpdat ] } -const isLast = (index: number, arr: T[]) => (index === (arr.length -1)) +const isLast = (index: number, arr: T[]) => index === arr.length - 1 + +const isCurrentValueLast = ( + currentUserMarks: CurrentUserMark[], + selectedMark: CurrentUserMark, + selectedMarkValue: string +) => { + const filteredMarks = currentUserMarks.filter( + (mark) => mark.id !== selectedMark.id + ) + return ( + isCurrentUserMarksComplete(filteredMarks) && selectedMarkValue.length > 0 + ) +} + +const getUpdatedMark = ( + selectedMark: CurrentUserMark, + selectedMarkValue: string +): CurrentUserMark => { + return { + ...selectedMark, + currentValue: selectedMarkValue, + isCompleted: !!selectedMarkValue + } +} export { getCurrentUserMarks, filterMarksByPubkey, extractMarksFromSignedMeta, isCurrentUserMarksComplete, - findNextCurrentUserMark, + findNextIncompleteCurrentUserMark, updateMarks, updateCurrentUserMarks, + isCurrentValueLast, + getUpdatedMark } From 0d52cd71134c9b3eee41e1ea853dba65afc7c79b Mon Sep 17 00:00:00 2001 From: Eugene Date: Mon, 12 Aug 2024 10:16:30 +0300 Subject: [PATCH 02/27] fix: selected mark selection --- src/components/MarkFormField/style.module.scss | 1 + src/components/PDFView/PdfMarking.tsx | 11 ++++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/components/MarkFormField/style.module.scss b/src/components/MarkFormField/style.module.scss index bff4644..e4e76ea 100644 --- a/src/components/MarkFormField/style.module.scss +++ b/src/components/MarkFormField/style.module.scss @@ -138,6 +138,7 @@ button:active { .submitButton { width: 100%; max-width: 300px; + margin-top: 10px; } .footerContainer { diff --git a/src/components/PDFView/PdfMarking.tsx b/src/components/PDFView/PdfMarking.tsx index e162062..b0e0748 100644 --- a/src/components/PDFView/PdfMarking.tsx +++ b/src/components/PDFView/PdfMarking.tsx @@ -39,8 +39,13 @@ const PdfMarking = (props: PdfMarkingProps) => { const [selectedMarkValue, setSelectedMarkValue] = useState('') useEffect(() => { - setSelectedMark(findNextIncompleteCurrentUserMark(currentUserMarks) || null) - }, []) + if (selectedMark === null && currentUserMarks.length > 0) { + setSelectedMark( + findNextIncompleteCurrentUserMark(currentUserMarks) || + currentUserMarks[0] + ) + } + }, [currentUserMarks, selectedMark]) const handleMarkClick = (id: number) => { const nextMark = currentUserMarks.find((mark) => mark.mark.id === id) @@ -60,8 +65,8 @@ const PdfMarking = (props: PdfMarkingProps) => { updatedSelectedMark ) setCurrentUserMarks(updatedCurrentUserMarks) - setSelectedMark(mark) setSelectedMarkValue(mark.currentValue ?? EMPTY) + setSelectedMark(mark) } const handleSubmit = (event: React.FormEvent) => { From 4c04c1240344c0f07a503bb0a5f56e7bfc791c8f Mon Sep 17 00:00:00 2001 From: Eugene Date: Mon, 12 Aug 2024 12:08:53 +0300 Subject: [PATCH 03/27] fix: button colour --- src/components/MarkFormField/index.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/components/MarkFormField/index.tsx b/src/components/MarkFormField/index.tsx index 71f6668..15ecc2a 100644 --- a/src/components/MarkFormField/index.tsx +++ b/src/components/MarkFormField/index.tsx @@ -34,7 +34,8 @@ const MarkFormField = ({ isCurrentValueLast(currentUserMarks, selectedMark, selectedMarkValue) const isCurrent = (currentMark: CurrentUserMark) => currentMark.id === selectedMark.id - const isDone = (currentMark: CurrentUserMark) => currentMark.isCompleted + const isDone = (currentMark: CurrentUserMark) => + isCurrent(currentMark) ? !!selectedMarkValue : currentMark.isCompleted const findNext = () => { return ( currentUserMarks[selectedMark.id] || @@ -50,6 +51,9 @@ const MarkFormField = ({ } return (
+
+ +
From 3549b6e54292b3d6fe456025cefc397ba0aa070d Mon Sep 17 00:00:00 2001 From: Eugene Date: Mon, 12 Aug 2024 12:32:36 +0300 Subject: [PATCH 04/27] fix: toggle --- src/components/MarkFormField/index.tsx | 22 ++++++++++++++++-- .../MarkFormField/style.module.scss | 23 ++++++++++++++++++- 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/components/MarkFormField/index.tsx b/src/components/MarkFormField/index.tsx index 15ecc2a..2fa2780 100644 --- a/src/components/MarkFormField/index.tsx +++ b/src/components/MarkFormField/index.tsx @@ -7,6 +7,7 @@ import { isCurrentUserMarksComplete, isCurrentValueLast } from '../../utils' +import { useState } from 'react' interface MarkFormFieldProps { handleSubmit: (event: any) => void @@ -28,6 +29,7 @@ const MarkFormField = ({ currentUserMarks, handleCurrentUserMarkChange }: MarkFormFieldProps) => { + const [displayActions, setDisplayActions] = useState(true) const getSubmitButtonText = () => (isReadyToSign() ? SIGN : NEXT) const isReadyToSign = () => isCurrentUserMarksComplete(currentUserMarks) || @@ -49,12 +51,28 @@ const MarkFormField = ({ ? handleSubmit(event) : handleCurrentUserMarkChange(findNext()!) } + const toggleActions = () => setDisplayActions(!displayActions) return (
- +
-
+
diff --git a/src/components/MarkFormField/style.module.scss b/src/components/MarkFormField/style.module.scss index e4e76ea..f3fa5d5 100644 --- a/src/components/MarkFormField/style.module.scss +++ b/src/components/MarkFormField/style.module.scss @@ -14,12 +14,16 @@ width: 100%; border-radius: 4px; padding: 10px 20px; - display: flex; + display: none; flex-direction: column; align-items: center; grid-gap: 15px; box-shadow: 0 -2px 4px 0 rgb(0,0,0,0.1); max-width: 750px; + + &.expanded { + display: flex; + } } .actionsWrapper { @@ -186,3 +190,20 @@ button:active { width: 100%; background: #4c82a3; } + +.trigger { + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; + position: relative; +} + +.triggerBtn { + background: white; + color: #434343; + padding: 5px 30px; + box-shadow: 0px -3px 4px 0 rgb(0,0,0,0.1); + position: absolute; + top: -25px; +} From 6d881ccb45e440c343b768c6d26d6933b2a4b813 Mon Sep 17 00:00:00 2001 From: Eugene Date: Tue, 13 Aug 2024 12:48:52 +0300 Subject: [PATCH 05/27] feat(pdf-marking): adds file downloading functionality --- src/components/FileList/index.tsx | 41 +++++++ src/components/FileList/style.module.scss | 78 ++++++++++++ src/components/PDFView/PdfMarking.tsx | 54 +++++--- src/components/PDFView/index.tsx | 49 +++++--- src/components/PDFView/style.module.scss | 15 ++- src/pages/sign/index.tsx | 98 ++++++++++----- src/pages/verify/index.tsx | 31 ++--- src/types/file.ts | 8 ++ src/utils/const.ts | 2 + src/utils/file.ts | 24 ++++ src/utils/pdf.ts | 143 +++++++++++----------- src/utils/utils.ts | 16 ++- 12 files changed, 402 insertions(+), 157 deletions(-) create mode 100644 src/components/FileList/index.tsx create mode 100644 src/components/FileList/style.module.scss create mode 100644 src/types/file.ts create mode 100644 src/utils/file.ts diff --git a/src/components/FileList/index.tsx b/src/components/FileList/index.tsx new file mode 100644 index 0000000..ba69332 --- /dev/null +++ b/src/components/FileList/index.tsx @@ -0,0 +1,41 @@ +import { CurrentUserFile } from '../../types/file.ts' +import styles from './style.module.scss' +import { Button } from '@mui/material' + +interface FileListProps { + files: CurrentUserFile[] + currentFile: CurrentUserFile + setCurrentFile: (file: CurrentUserFile) => void + handleDownload: () => void +} + +const FileList = ({ + files, + currentFile, + setCurrentFile, + handleDownload +}: FileListProps) => { + const isActive = (file: CurrentUserFile) => file.id === currentFile.id + return ( +
+
+
    + {files.map((file: CurrentUserFile) => ( +
  • setCurrentFile(file)} + > + {file.id} + {file.filename} +
  • + ))} +
+ +
+ ) +} + +export default FileList diff --git a/src/components/FileList/style.module.scss b/src/components/FileList/style.module.scss new file mode 100644 index 0000000..bbf9311 --- /dev/null +++ b/src/components/FileList/style.module.scss @@ -0,0 +1,78 @@ +.container { + border-radius: 4px; + background: white; + padding: 15px; + display: flex; + flex-direction: column; + grid-gap: 0px; +} + +.files { + display: flex; + flex-direction: column; + width: 100%; + grid-gap: 15px; + max-height: 350px; + overflow: auto; + padding: 0 5px 0 0; + margin: 0 -5px 0 0; +} + +.files::-webkit-scrollbar { + width: 10px; +} + +.files::-webkit-scrollbar-track { + background-color: rgba(0,0,0,0.15); +} + +.files::-webkit-scrollbar-thumb { + max-width: 10px; + border-radius: 2px; + background-color: #4c82a3; + cursor: grab; +} + +.fileItem { + transition: ease 0.2s; + display: flex; + flex-direction: row; + grid-gap: 10px; + border-radius: 4px; + overflow: hidden; + background: #ffffff; + padding: 5px 10px; + align-items: center; + color: rgba(0,0,0,0.5); + cursor: pointer; + flex-grow: 1; + font-size: 16px; + font-weight: 500; +} + +.fileItem:hover { + transition: ease 0.2s; + background: #4c82a3; + color: white; + + &.active { + background: #4c82a3; + color: white; + } +} + +.fileName { + display: -webkit-box; + -webkit-box-orient: vertical; + overflow: hidden; + -webkit-line-clamp: 1; +} + +.fileNumber { + font-size: 14px; + font-weight: 500; + display: flex; + flex-direction: column; + justify-content: center; + align-items: center; +} \ No newline at end of file diff --git a/src/components/PDFView/PdfMarking.tsx b/src/components/PDFView/PdfMarking.tsx index b0e0748..fc49f79 100644 --- a/src/components/PDFView/PdfMarking.tsx +++ b/src/components/PDFView/PdfMarking.tsx @@ -1,24 +1,26 @@ import PdfView from './index.tsx' import MarkFormField from '../MarkFormField' -import { PdfFile } from '../../types/drawing.ts' import { CurrentUserMark, Mark } from '../../types/mark.ts' import React, { useState, useEffect } from 'react' import { findNextIncompleteCurrentUserMark, getUpdatedMark, - isCurrentUserMarksComplete, updateCurrentUserMarks } from '../../utils' import { EMPTY } from '../../utils/const.ts' import { Container } from '../Container' -import styles from '../../pages/sign/style.module.scss' +import signPageStyles from '../../pages/sign/style.module.scss' +import styles from './style.module.scss' +import { CurrentUserFile } from '../../types/file.ts' +import FileList from '../FileList' interface PdfMarkingProps { - files: { pdfFile: PdfFile; filename: string; hash: string | null }[] + files: CurrentUserFile[] currentUserMarks: CurrentUserMark[] setIsReadyToSign: (isReadyToSign: boolean) => void setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void setUpdatedMarks: (markToUpdate: Mark) => void + handleDownload: () => void } /** @@ -33,10 +35,12 @@ const PdfMarking = (props: PdfMarkingProps) => { currentUserMarks, setIsReadyToSign, setCurrentUserMarks, - setUpdatedMarks + setUpdatedMarks, + handleDownload } = props const [selectedMark, setSelectedMark] = useState(null) const [selectedMarkValue, setSelectedMarkValue] = useState('') + const [currentFile, setCurrentFile] = useState(null) useEffect(() => { if (selectedMark === null && currentUserMarks.length > 0) { @@ -47,6 +51,12 @@ const PdfMarking = (props: PdfMarkingProps) => { } }, [currentUserMarks, selectedMark]) + useEffect(() => { + if (currentFile === null && files.length > 0) { + setCurrentFile(files[0]) + } + }, [files, currentFile]) + const handleMarkClick = (id: number) => { const nextMark = currentUserMarks.find((mark) => mark.mark.id === id) setSelectedMark(nextMark!) @@ -101,16 +111,30 @@ const PdfMarking = (props: PdfMarkingProps) => { return ( <> - - {currentUserMarks?.length > 0 && ( - - )} + +
+
+ {currentFile !== null && ( + + )} +
+ {currentUserMarks?.length > 0 && ( +
+ +
+ )} +
{selectedMark !== null && ( void selectedMarkValue: string @@ -14,29 +14,38 @@ interface PdfViewProps { /** * Responsible for rendering Pdf files. */ -const PdfView = ({ files, currentUserMarks, handleMarkClick, selectedMarkValue, selectedMark }: PdfViewProps) => { - const filterByFile = (currentUserMarks: CurrentUserMark[], hash: string): CurrentUserMark[] => { - return currentUserMarks.filter((currentUserMark) => currentUserMark.mark.pdfFileHash === hash) +const PdfView = ({ + files, + currentUserMarks, + handleMarkClick, + selectedMarkValue, + selectedMark +}: PdfViewProps) => { + const filterByFile = ( + currentUserMarks: CurrentUserMark[], + hash: string + ): CurrentUserMark[] => { + return currentUserMarks.filter( + (currentUserMark) => currentUserMark.mark.pdfFileHash === hash + ) } return ( - { - files.map(({ pdfFile, hash }, i) => { - if (!hash) return - return ( - { + if (!hash) return + return ( + - ) - }) - } + ) + })} ) } -export default PdfView; \ No newline at end of file +export default PdfView diff --git a/src/components/PDFView/style.module.scss b/src/components/PDFView/style.module.scss index 2e6e519..3ebbc85 100644 --- a/src/components/PDFView/style.module.scss +++ b/src/components/PDFView/style.module.scss @@ -13,4 +13,17 @@ max-width: 100%; max-height: 100%; object-fit: contain; /* Ensure the image fits within the container */ -} \ No newline at end of file +} + +.container { + display: flex; + width: 100%; + flex-direction: column; +} + +.pdfView { + display: flex; + flex-direction: column; + width: 100%; + height: 100%; +} diff --git a/src/pages/sign/index.tsx b/src/pages/sign/index.tsx index 07c385e..02ac415 100644 --- a/src/pages/sign/index.tsx +++ b/src/pages/sign/index.tsx @@ -16,13 +16,16 @@ import { State } from '../../store/rootReducer' import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types' import { decryptArrayBuffer, - encryptArrayBuffer, extractMarksFromSignedMeta, + encryptArrayBuffer, + extractMarksFromSignedMeta, extractZipUrlAndEncryptionKey, generateEncryptionKey, - generateKeysFile, getFilesWithHashes, + generateKeysFile, + getCurrentUserFiles, getHash, hexToNpub, - isOnline, loadZip, + isOnline, + loadZip, now, npubToHex, parseJson, @@ -41,9 +44,12 @@ import { getLastSignersSig } from '../../utils/sign.ts' import { filterMarksByPubkey, getCurrentUserMarks, - isCurrentUserMarksComplete, updateMarks + isCurrentUserMarksComplete, + updateMarks } from '../../utils' import PdfMarking from '../../components/PDFView/PdfMarking.tsx' +import { getZipWithFiles } from '../../utils/file.ts' +import { ARRAY_BUFFER, DEFLATE } from '../../utils/const.ts' enum SignedStatus { Fully_Signed, User_Is_Next_Signer, @@ -81,7 +87,7 @@ export const SignPage = () => { const [signers, setSigners] = useState<`npub1${string}`[]>([]) const [viewers, setViewers] = useState<`npub1${string}`[]>([]) - const [marks, setMarks] = useState([]) + const [marks, setMarks] = useState([]) const [creatorFileHashes, setCreatorFileHashes] = useState<{ [key: string]: string }>({}) @@ -100,8 +106,10 @@ export const SignPage = () => { const [authUrl, setAuthUrl] = useState() const nostrController = NostrController.getInstance() - const [currentUserMarks, setCurrentUserMarks] = useState([]); - const [isReadyToSign, setIsReadyToSign] = useState(false); + const [currentUserMarks, setCurrentUserMarks] = useState( + [] + ) + const [isReadyToSign, setIsReadyToSign] = useState(false) useEffect(() => { if (signers.length > 0) { @@ -192,13 +200,16 @@ export const SignPage = () => { setViewers(createSignatureContent.viewers) setCreatorFileHashes(createSignatureContent.fileHashes) setSubmittedBy(createSignatureEvent.pubkey) - setMarks(createSignatureContent.markConfig); + setMarks(createSignatureContent.markConfig) if (usersPubkey) { - const metaMarks = filterMarksByPubkey(createSignatureContent.markConfig, usersPubkey!) + const metaMarks = filterMarksByPubkey( + createSignatureContent.markConfig, + usersPubkey! + ) const signedMarks = extractMarksFromSignedMeta(meta) - const currentUserMarks = getCurrentUserMarks(metaMarks, signedMarks); - setCurrentUserMarks(currentUserMarks); + const currentUserMarks = getCurrentUserMarks(metaMarks, signedMarks) + setCurrentUserMarks(currentUserMarks) // setCurrentUserMark(findNextCurrentUserMark(currentUserMarks) || null) setIsReadyToSign(isCurrentUserMarksComplete(currentUserMarks)) } @@ -307,7 +318,7 @@ export const SignPage = () => { ) if (arrayBuffer) { - files[fileName] = await convertToPdfFile(arrayBuffer, fileName); + files[fileName] = await convertToPdfFile(arrayBuffer, fileName) const hash = await getHash(arrayBuffer) if (hash) { @@ -348,7 +359,7 @@ export const SignPage = () => { const decrypt = async (file: File) => { setLoadingSpinnerDesc('Decrypting file') - const zip = await loadZip(file); + const zip = await loadZip(file) if (!zip) return const parsedKeysJson = await parseKeysJson(zip) @@ -414,6 +425,27 @@ export const SignPage = () => { return null } + const handleDownload = async () => { + if (Object.entries(files).length === 0 || !meta || !usersPubkey) return + setLoadingSpinnerDesc('Generating file') + try { + const zip = await getZipWithFiles(meta, files) + const arrayBuffer = await zip.generateAsync({ + type: ARRAY_BUFFER, + compression: DEFLATE, + compressionOptions: { + level: 6 + } + }) + if (!arrayBuffer) return + const blob = new Blob([arrayBuffer]) + saveAs(blob, `exported-${now()}.sigit.zip`) + } catch (error: any) { + console.log('error in zip:>> ', error) + toast.error(error.message || 'Error occurred in generating zip file') + } + } + const handleDecryptedArrayBuffer = async (arrayBuffer: ArrayBuffer) => { const decryptedZipFile = new File([arrayBuffer], 'decrypted.zip') @@ -439,7 +471,7 @@ export const SignPage = () => { ) if (arrayBuffer) { - files[fileName] = await convertToPdfFile(arrayBuffer, fileName); + files[fileName] = await convertToPdfFile(arrayBuffer, fileName) const hash = await getHash(arrayBuffer) if (hash) { @@ -520,7 +552,10 @@ export const SignPage = () => { } // Sign the event for the meta file - const signEventForMeta = async (signerContent: { prevSig: string, marks: Mark[] }) => { + const signEventForMeta = async (signerContent: { + prevSig: string + marks: Mark[] + }) => { return await signEventForMetaFile( JSON.stringify(signerContent), nostrController, @@ -529,8 +564,8 @@ export const SignPage = () => { } const getSignerMarksForMeta = (): Mark[] | undefined => { - if (currentUserMarks.length === 0) return; - return currentUserMarks.map(( { mark }: CurrentUserMark) => mark); + if (currentUserMarks.length === 0) return + return currentUserMarks.map(({ mark }: CurrentUserMark) => mark) } // Update the meta signatures @@ -600,13 +635,9 @@ export const SignPage = () => { if (!arraybuffer) return null - return new File( - [new Blob([arraybuffer])], - `${unixNow}.sigit.zip`, - { - type: 'application/zip' - } - ) + return new File([new Blob([arraybuffer])], `${unixNow}.sigit.zip`, { + type: 'application/zip' + }) } // Handle errors during zip file generation @@ -694,7 +725,7 @@ export const SignPage = () => { setIsLoading(true) setLoadingSpinnerDesc('Signing nostr event') - if (!meta) return; + if (!meta) return const prevSig = getLastSignersSig(meta, signers) if (!prevSig) return @@ -918,11 +949,14 @@ export const SignPage = () => { ) } - return + return ( + + ) } diff --git a/src/pages/verify/index.tsx b/src/pages/verify/index.tsx index 6290c02..b39fe74 100644 --- a/src/pages/verify/index.tsx +++ b/src/pages/verify/index.tsx @@ -23,14 +23,17 @@ import { SignedEventContent } from '../../types' import { - decryptArrayBuffer, extractMarksFromSignedMeta, + decryptArrayBuffer, + extractMarksFromSignedMeta, extractZipUrlAndEncryptionKey, getHash, - hexToNpub, now, + hexToNpub, + now, npubToHex, parseJson, readContentOfZipEntry, - shorten, signEventForMetaFile + shorten, + signEventForMetaFile } from '../../utils' import styles from './style.module.scss' import { Cancel, CheckCircle } from '@mui/icons-material' @@ -41,7 +44,7 @@ import { addMarks, convertToPdfBlob, convertToPdfFile, - groupMarksByPage, + groupMarksByPage } from '../../utils/pdf.ts' import { State } from '../../store/rootReducer.ts' import { useSelector } from 'react-redux' @@ -78,7 +81,7 @@ export const VerifyPage = () => { const [currentFileHashes, setCurrentFileHashes] = useState<{ [key: string]: string | null }>({}) - const [files, setFiles] = useState<{ [filename: string]: PdfFile}>({}) + const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({}) const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>( {} @@ -155,7 +158,10 @@ export const VerifyPage = () => { ) if (arrayBuffer) { - files[fileName] = await convertToPdfFile(arrayBuffer, fileName!) + files[fileName] = await convertToPdfFile( + arrayBuffer, + fileName! + ) const hash = await getHash(arrayBuffer) if (hash) { @@ -169,7 +175,6 @@ export const VerifyPage = () => { setCurrentFileHashes(fileHashes) setFiles(files) - setSigners(createSignatureContent.signers) setViewers(createSignatureContent.viewers) setCreatorFileHashes(createSignatureContent.fileHashes) @@ -177,8 +182,6 @@ export const VerifyPage = () => { setMeta(metaInNavState) setIsLoading(false) - - } }) .catch((err) => { @@ -381,7 +384,7 @@ export const VerifyPage = () => { } const handleExport = async () => { - if (Object.entries(files).length === 0 ||!meta ||!usersPubkey) return; + if (Object.entries(files).length === 0 || !meta || !usersPubkey) return const usersNpub = hexToNpub(usersPubkey) if ( @@ -395,10 +398,8 @@ export const VerifyPage = () => { setIsLoading(true) setLoadingSpinnerDesc('Signing nostr event') - if (!meta) return; - const prevSig = getLastSignersSig(meta, signers) - if (!prevSig) return; + if (!prevSig) return const signedEvent = await signEventForMetaFile( JSON.stringify({ prevSig }), @@ -406,10 +407,10 @@ export const VerifyPage = () => { setIsLoading ) - if (!signedEvent) return; + if (!signedEvent) return const exportSignature = JSON.stringify(signedEvent, null, 2) - const updatedMeta = {...meta, exportSignature } + const updatedMeta = { ...meta, exportSignature } const stringifiedMeta = JSON.stringify(updatedMeta, null, 2) const zip = new JSZip() diff --git a/src/types/file.ts b/src/types/file.ts new file mode 100644 index 0000000..0f2c127 --- /dev/null +++ b/src/types/file.ts @@ -0,0 +1,8 @@ +import { PdfFile } from './drawing.ts' + +export interface CurrentUserFile { + id: number + pdfFile: PdfFile + filename: string + hash?: string +} diff --git a/src/utils/const.ts b/src/utils/const.ts index 2a97dfe..511f418 100644 --- a/src/utils/const.ts +++ b/src/utils/const.ts @@ -6,3 +6,5 @@ export const MARK_TYPE_TRANSLATION: { [key: string]: string } = { } export const SIGN: string = 'Sign' export const NEXT: string = 'Next' +export const ARRAY_BUFFER = 'arraybuffer' +export const DEFLATE = 'DEFLATE' diff --git a/src/utils/file.ts b/src/utils/file.ts new file mode 100644 index 0000000..94308d5 --- /dev/null +++ b/src/utils/file.ts @@ -0,0 +1,24 @@ +import { Meta } from '../types' +import { extractMarksFromSignedMeta } from './mark.ts' +import { addMarks, convertToPdfBlob, groupMarksByPage } from './pdf.ts' +import JSZip from 'jszip' +import { PdfFile } from '../types/drawing.ts' + +const getZipWithFiles = async ( + meta: Meta, + files: { [filename: string]: PdfFile } +): Promise => { + const zip = new JSZip() + const marks = extractMarksFromSignedMeta(meta) + const marksByPage = groupMarksByPage(marks) + + for (const [fileName, pdf] of Object.entries(files)) { + const pages = await addMarks(pdf.file, marksByPage) + const blob = await convertToPdfBlob(pages) + zip.file(`/files/${fileName}`, blob) + } + + return zip +} + +export { getZipWithFiles } diff --git a/src/utils/pdf.ts b/src/utils/pdf.ts index 70b6539..a684d78 100644 --- a/src/utils/pdf.ts +++ b/src/utils/pdf.ts @@ -3,13 +3,14 @@ import * as PDFJS from 'pdfjs-dist' import { PDFDocument } from 'pdf-lib' import { Mark } from '../types/mark.ts' -PDFJS.GlobalWorkerOptions.workerSrc = 'node_modules/pdfjs-dist/build/pdf.worker.mjs'; +PDFJS.GlobalWorkerOptions.workerSrc = + 'node_modules/pdfjs-dist/build/pdf.worker.mjs' /** * Scale between the PDF page's natural size and rendered size * @constant {number} */ -const SCALE: number = 3; +const SCALE: number = 3 /** * Defined font size used when generating a PDF. Currently it is difficult to fully * correlate font size used at the time of filling in / drawing on the PDF @@ -17,20 +18,20 @@ const SCALE: number = 3; * This should be fixed going forward. * Switching to PDF-Lib will most likely make this problem redundant. */ -const FONT_SIZE: number = 40; +const FONT_SIZE: number = 40 /** * Current font type used when generating a PDF. */ -const FONT_TYPE: string = 'Arial'; +const FONT_TYPE: string = 'Arial' /** * Converts a PDF ArrayBuffer to a generic PDF File * @param arrayBuffer of a PDF * @param fileName identifier of the pdf file */ -const toFile = (arrayBuffer: ArrayBuffer, fileName: string) : File => { - const blob = new Blob([arrayBuffer], { type: "application/pdf" }); - return new File([blob], fileName, { type: "application/pdf" }); +const toFile = (arrayBuffer: ArrayBuffer, fileName: string): File => { + const blob = new Blob([arrayBuffer], { type: 'application/pdf' }) + return new File([blob], fileName, { type: 'application/pdf' }) } /** @@ -50,42 +51,40 @@ const toPdfFile = async (file: File): Promise => { * @return PdfFile[] - an array of Sigit's internal Pdf File type */ const toPdfFiles = async (selectedFiles: File[]): Promise => { - return Promise.all(selectedFiles - .filter(isPdf) - .map(toPdfFile)); + return Promise.all(selectedFiles.filter(isPdf).map(toPdfFile)) } /** * A utility that transforms a drawing coordinate number into a CSS-compatible string * @param coordinate */ -const inPx = (coordinate: number): string => `${coordinate}px`; +const inPx = (coordinate: number): string => `${coordinate}px` /** * A utility that checks if a given file is of the pdf type * @param file */ -const isPdf = (file: File) => file.type.toLowerCase().includes('pdf'); +const isPdf = (file: File) => file.type.toLowerCase().includes('pdf') /** * Reads the pdf file binaries */ const readPdf = (file: File): Promise => { return new Promise((resolve, reject) => { - const reader = new FileReader(); + const reader = new FileReader() reader.onload = (e: any) => { const data = e.target.result resolve(data) - }; + } reader.onerror = (err) => { console.error('err', err) reject(err) - }; + } - reader.readAsDataURL(file); + reader.readAsDataURL(file) }) } @@ -94,26 +93,28 @@ const readPdf = (file: File): Promise => { * @param data pdf file bytes */ const pdfToImages = async (data: any): Promise => { - const images: string[] = []; - const pdf = await PDFJS.getDocument(data).promise; - const canvas = document.createElement("canvas"); + const images: string[] = [] + const pdf = await PDFJS.getDocument(data).promise + const canvas = document.createElement('canvas') for (let i = 0; i < pdf.numPages; i++) { - const page = await pdf.getPage(i + 1); - const viewport = page.getViewport({ scale: SCALE }); - const context = canvas.getContext("2d"); - canvas.height = viewport.height; - canvas.width = viewport.width; - await page.render({ canvasContext: context!, viewport: viewport }).promise; - images.push(canvas.toDataURL()); + const page = await pdf.getPage(i + 1) + const viewport = page.getViewport({ scale: SCALE }) + const context = canvas.getContext('2d') + canvas.height = viewport.height + canvas.width = viewport.width + await page.render({ canvasContext: context!, viewport: viewport }).promise + images.push(canvas.toDataURL()) } - return Promise.resolve(images.map((image) => { - return { - image, - drawnFields: [] - } - })) + return Promise.resolve( + images.map((image) => { + return { + image, + drawnFields: [] + } + }) + ) } /** @@ -121,34 +122,37 @@ const pdfToImages = async (data: any): Promise => { * Returns an array of encoded images where each image is a representation * of a PDF page with completed and signed marks from all users */ -const addMarks = async (file: File, marksPerPage: {[key: string]: Mark[]}) => { - const p = await readPdf(file); - const pdf = await PDFJS.getDocument(p).promise; - const canvas = document.createElement("canvas"); +const addMarks = async ( + file: File, + marksPerPage: { [key: string]: Mark[] } +) => { + const p = await readPdf(file) + const pdf = await PDFJS.getDocument(p).promise + const canvas = document.createElement('canvas') - const images: string[] = []; + const images: string[] = [] - for (let i = 0; i< pdf.numPages; i++) { - const page = await pdf.getPage(i+1) - const viewport = page.getViewport({ scale: SCALE }); - const context = canvas.getContext("2d"); - canvas.height = viewport.height; - canvas.width = viewport.width; - await page.render({ canvasContext: context!, viewport: viewport }).promise; + for (let i = 0; i < pdf.numPages; i++) { + const page = await pdf.getPage(i + 1) + const viewport = page.getViewport({ scale: SCALE }) + const context = canvas.getContext('2d') + canvas.height = viewport.height + canvas.width = viewport.width + await page.render({ canvasContext: context!, viewport: viewport }).promise - marksPerPage[i].forEach(mark => draw(mark, context!)) + marksPerPage[i]?.forEach((mark) => draw(mark, context!)) - images.push(canvas.toDataURL()); + images.push(canvas.toDataURL()) } - return Promise.resolve(images); + return Promise.resolve(images) } /** * Utility to scale mark in line with the PDF-to-PNG scale */ const scaleMark = (mark: Mark): Mark => { - const { location } = mark; + const { location } = mark return { ...mark, location: { @@ -165,7 +169,7 @@ const scaleMark = (mark: Mark): Mark => { * Utility to check if a Mark has value * @param mark */ -const hasValue = (mark: Mark): boolean => !!mark.value; +const hasValue = (mark: Mark): boolean => !!mark.value /** * Draws a Mark on a Canvas representation of a PDF Page @@ -173,14 +177,14 @@ const hasValue = (mark: Mark): boolean => !!mark.value; * @param ctx a Canvas representation of a specific PDF Page */ const draw = (mark: Mark, ctx: CanvasRenderingContext2D) => { - const { location } = mark; + const { location } = mark - ctx!.font = FONT_SIZE + 'px ' + FONT_TYPE; - ctx!.fillStyle = 'black'; - const textMetrics = ctx!.measureText(mark.value!); - const textX = location.left + (location.width - textMetrics.width) / 2; - const textY = location.top + (location.height + parseInt(ctx!.font)) / 2; - ctx!.fillText(mark.value!, textX, textY); + ctx!.font = FONT_SIZE + 'px ' + FONT_TYPE + ctx!.fillStyle = 'black' + const textMetrics = ctx!.measureText(mark.value!) + const textX = location.left + (location.width - textMetrics.width) / 2 + const textY = location.top + (location.height + parseInt(ctx!.font)) / 2 + ctx!.fillText(mark.value!, textX, textY) } /** @@ -188,7 +192,7 @@ const draw = (mark: Mark, ctx: CanvasRenderingContext2D) => { * @param markedPdfPages */ const convertToPdfBlob = async (markedPdfPages: string[]): Promise => { - const pdfDoc = await PDFDocument.create(); + const pdfDoc = await PDFDocument.create() for (const page of markedPdfPages) { const pngImage = await pdfDoc.embedPng(page) @@ -203,7 +207,6 @@ const convertToPdfBlob = async (markedPdfPages: string[]): Promise => { const pdfBytes = await pdfDoc.save() return new Blob([pdfBytes], { type: 'application/pdf' }) - } /** @@ -211,9 +214,12 @@ const convertToPdfBlob = async (markedPdfPages: string[]): Promise => { * @param arrayBuffer * @param fileName */ -const convertToPdfFile = async (arrayBuffer: ArrayBuffer, fileName: string): Promise => { - const file = toFile(arrayBuffer, fileName); - return toPdfFile(file); +const convertToPdfFile = async ( + arrayBuffer: ArrayBuffer, + fileName: string +): Promise => { + const file = toFile(arrayBuffer, fileName) + return toPdfFile(file) } /** @@ -226,7 +232,7 @@ const groupMarksByPage = (marks: Mark[]) => { return marks .filter(hasValue) .map(scaleMark) - .reduce<{[key: number]: Mark[]}>(byPage, {}) + .reduce<{ [key: number]: Mark[] }>(byPage, {}) } /** @@ -237,11 +243,10 @@ const groupMarksByPage = (marks: Mark[]) => { * @param obj - accumulator in the reducer callback * @param mark - current value, i.e. Mark being examined */ -const byPage = (obj: { [key: number]: Mark[]}, mark: Mark) => { - const key = mark.location.page; - const curGroup = obj[key] ?? []; - return { ...obj, [key]: [...curGroup, mark] - } +const byPage = (obj: { [key: number]: Mark[] }, mark: Mark) => { + const key = mark.location.page + const curGroup = obj[key] ?? [] + return { ...obj, [key]: [...curGroup, mark] } } export { @@ -252,5 +257,5 @@ export { convertToPdfFile, addMarks, convertToPdfBlob, - groupMarksByPage, -} \ No newline at end of file + groupMarksByPage +} diff --git a/src/utils/utils.ts b/src/utils/utils.ts index ed830a2..e201c41 100644 --- a/src/utils/utils.ts +++ b/src/utils/utils.ts @@ -1,4 +1,5 @@ import { PdfFile } from '../types/drawing.ts' +import { CurrentUserFile } from '../types/file.ts' export const compareObjects = ( obj1: object | null | undefined, @@ -72,11 +73,16 @@ export const timeout = (ms: number = 60000) => { * @param files * @param fileHashes */ -export const getFilesWithHashes = ( - files: { [filename: string ]: PdfFile }, +export const getCurrentUserFiles = ( + files: { [filename: string]: PdfFile }, fileHashes: { [key: string]: string | null } - ) => { - return Object.entries(files).map(([filename, pdfFile]) => { - return { pdfFile, filename, hash: fileHashes[filename] } +): CurrentUserFile[] => { + return Object.entries(files).map(([filename, pdfFile], index) => { + return { + pdfFile, + filename, + id: index + 1, + ...(!!fileHashes[filename] && { hash: fileHashes[filename]! }) + } }) } From d9779c10bde5a510f2ac8daf660857299dc585e9 Mon Sep 17 00:00:00 2001 From: enes Date: Tue, 13 Aug 2024 13:32:32 +0200 Subject: [PATCH 06/27] refactor: flat meta and add useSigitProfile --- src/components/DisplaySigit/index.tsx | 65 ++-------------- src/hooks/useSigitMeta.tsx | 70 ++++++++++++++--- src/hooks/useSigitProfiles.tsx | 70 +++++++++++++++++ src/pages/verify/index.tsx | 107 +++++--------------------- src/utils/meta.ts | 4 +- 5 files changed, 155 insertions(+), 161 deletions(-) create mode 100644 src/hooks/useSigitProfiles.tsx diff --git a/src/components/DisplaySigit/index.tsx b/src/components/DisplaySigit/index.tsx index 0fe5c2f..ce82f47 100644 --- a/src/components/DisplaySigit/index.tsx +++ b/src/components/DisplaySigit/index.tsx @@ -1,9 +1,6 @@ -import { useEffect, useState } from 'react' -import { Meta, ProfileMetadata } from '../../types' +import { Meta } from '../../types' import { SigitCardDisplayInfo, SigitStatus } from '../../utils' -import { Event, kinds } from 'nostr-tools' import { Link } from 'react-router-dom' -import { MetadataController } from '../../controllers' import { formatTimestamp, hexToNpub, npubToHex, shorten } from '../../utils' import { appPublicRoutes, appPrivateRoutes } from '../../routes' import { Button, Divider, Tooltip } from '@mui/material' @@ -22,6 +19,7 @@ import { UserAvatarGroup } from '../UserAvatarGroup' import styles from './style.module.scss' import { TooltipChild } from '../TooltipChild' import { getExtensionIconLabel } from '../getExtensionIconLabel' +import { useSigitProfiles } from '../../hooks/useSigitProfiles' type SigitProps = { meta: Meta @@ -38,61 +36,10 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => { fileExtensions } = parsedMeta - const [profiles, setProfiles] = useState<{ [key: string]: ProfileMetadata }>( - {} - ) - - useEffect(() => { - const hexKeys = new Set([ - ...signers.map((signer) => npubToHex(signer)!) - ]) - - if (submittedBy) { - hexKeys.add(npubToHex(submittedBy)!) - } - - const metadataController = new MetadataController() - - const handleMetadataEvent = (key: string) => (event: Event) => { - const metadataContent = - metadataController.extractProfileMetadataContent(event) - - if (metadataContent) { - setProfiles((prev) => ({ - ...prev, - [key]: metadataContent - })) - } - } - - const handleEventListener = - (key: string) => (kind: number, event: Event) => { - if (kind === kinds.Metadata) { - handleMetadataEvent(key)(event) - } - } - - hexKeys.forEach((key) => { - if (!(key in profiles)) { - metadataController.on(key, handleEventListener(key)) - - metadataController - .findMetadata(key) - .then((metadataEvent) => { - if (metadataEvent) handleMetadataEvent(key)(metadataEvent) - }) - .catch((err) => { - console.error(`error occurred in finding metadata for: ${key}`, err) - }) - } - }) - - return () => { - hexKeys.forEach((key) => { - metadataController.off(key, handleEventListener(key)) - }) - } - }, [submittedBy, signers, profiles]) + const profiles = useSigitProfiles([ + ...(submittedBy ? [submittedBy] : []), + ...signers + ]) return (
diff --git a/src/hooks/useSigitMeta.tsx b/src/hooks/useSigitMeta.tsx index aebd791..5460983 100644 --- a/src/hooks/useSigitMeta.tsx +++ b/src/hooks/useSigitMeta.tsx @@ -3,6 +3,7 @@ import { CreateSignatureEventContent, Meta } from '../types' import { Mark } from '../types/mark' import { fromUnixTimestamp, + hexToNpub, parseCreateSignatureEvent, parseCreateSignatureEventContent, SigitMetaParseError, @@ -12,11 +13,30 @@ import { import { toast } from 'react-toastify' import { verifyEvent } from 'nostr-tools' import { Event } from 'nostr-tools' +import store from '../store/store' +import { AuthState } from '../store/auth/types' +import { NostrController } from '../controllers' + +/** + * Flattened interface that combines properties `Meta`, `CreateSignatureEventContent`, + * and `Event` (event's fields are made optional and pubkey and created_at replaced with our versions) + */ +interface FlatMeta + extends Meta, + CreateSignatureEventContent, + Partial> { + // Remove pubkey and use submittedBy as `npub1${string}` + submittedBy?: `npub1${string}` + + // Remove created_at and replace with createdAt + createdAt?: number -interface FlatMeta extends Meta, CreateSignatureEventContent, Partial { // Validated create signature event isValid: boolean + // Decryption + encryptionKey: string | null + // Calculated status fields signedStatus: SigitStatus signersStatus: { @@ -33,8 +53,8 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { const [isValid, setIsValid] = useState(false) const [kind, setKind] = useState() const [tags, setTags] = useState() - const [created_at, setCreatedAt] = useState() - const [pubkey, setPubkey] = useState() // submittedBy, pubkey from nostr event + const [createdAt, setCreatedAt] = useState() + const [submittedBy, setSubmittedBy] = useState<`npub1${string}`>() // submittedBy, pubkey from nostr event const [id, setId] = useState() const [sig, setSig] = useState() @@ -54,6 +74,8 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { [signer: `npub1${string}`]: SignStatus }>({}) + const [encryptionKey, setEncryptionKey] = useState(null) + useEffect(() => { if (!meta) return ;(async function () { @@ -70,7 +92,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { setTags(tags) // created_at in nostr events are stored in seconds setCreatedAt(fromUnixTimestamp(created_at)) - setPubkey(pubkey) + setSubmittedBy(pubkey as `npub1${string}`) setId(id) setSig(sig) @@ -84,6 +106,31 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { setMarkConfig(markConfig) setZipUrl(zipUrl) + if (meta.keys) { + const { sender, keys } = meta.keys + + // Retrieve the user's public key from the state + const usersPubkey = (store.getState().auth as AuthState).usersPubkey! + const usersNpub = hexToNpub(usersPubkey) + + // Check if the user's public key is in the keys object + if (usersNpub in keys) { + // Instantiate the NostrController to decrypt the encryption key + const nostrController = NostrController.getInstance() + const decrypted = await nostrController + .nip04Decrypt(sender, keys[usersNpub]) + .catch((err) => { + console.log( + 'An error occurred in decrypting encryption key', + err + ) + return null + }) + + setEncryptionKey(decrypted) + } + } + // Parse each signature event and set signer status for (const npub in meta.docSignatures) { try { @@ -125,15 +172,15 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { }, [meta]) return { - modifiedAt: meta.modifiedAt, - createSignature: meta.createSignature, - docSignatures: meta.docSignatures, - keys: meta.keys, + modifiedAt: meta?.modifiedAt, + createSignature: meta?.createSignature, + docSignatures: meta?.docSignatures, + keys: meta?.keys, isValid, kind, tags, - created_at, - pubkey, + createdAt, + submittedBy, id, sig, signers, @@ -143,6 +190,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { title, zipUrl, signedStatus, - signersStatus + signersStatus, + encryptionKey } } diff --git a/src/hooks/useSigitProfiles.tsx b/src/hooks/useSigitProfiles.tsx new file mode 100644 index 0000000..8178dd7 --- /dev/null +++ b/src/hooks/useSigitProfiles.tsx @@ -0,0 +1,70 @@ +import { useEffect, useState } from 'react' +import { ProfileMetadata } from '../types' +import { MetadataController } from '../controllers' +import { npubToHex } from '../utils' +import { Event, kinds } from 'nostr-tools' + +/** + * Extracts profiles from metadata events + * @param pubkeys Array of npubs to check + * @returns ProfileMetadata + */ +export const useSigitProfiles = ( + pubkeys: `npub1${string}`[] +): { [key: string]: ProfileMetadata } => { + const [profileMetadata, setProfileMetadata] = useState<{ + [key: string]: ProfileMetadata + }>({}) + + useEffect(() => { + if (pubkeys.length) { + const metadataController = new MetadataController() + + // Remove duplicate keys + const users = new Set([...pubkeys]) + + const handleMetadataEvent = (key: string) => (event: Event) => { + const metadataContent = + metadataController.extractProfileMetadataContent(event) + + if (metadataContent) { + setProfileMetadata((prev) => ({ + ...prev, + [key]: metadataContent + })) + } + } + + users.forEach((user) => { + const hexKey = npubToHex(user) + if (hexKey && !(hexKey in profileMetadata)) { + metadataController.on(hexKey, (kind: number, event: Event) => { + if (kind === kinds.Metadata) { + handleMetadataEvent(hexKey)(event) + } + }) + + metadataController + .findMetadata(hexKey) + .then((metadataEvent) => { + if (metadataEvent) handleMetadataEvent(hexKey)(metadataEvent) + }) + .catch((err) => { + console.error( + `error occurred in finding metadata for: ${user}`, + err + ) + }) + } + }) + + return () => { + users.forEach((key) => { + metadataController.off(key, handleMetadataEvent(key)) + }) + } + } + }, [pubkeys, profileMetadata]) + + return profileMetadata +} diff --git a/src/pages/verify/index.tsx b/src/pages/verify/index.tsx index 1f6bee1..f77bd48 100644 --- a/src/pages/verify/index.tsx +++ b/src/pages/verify/index.tsx @@ -10,22 +10,20 @@ import { } from '@mui/material' import JSZip from 'jszip' import { MuiFileInput } from 'mui-file-input' -import { Event, kinds, verifyEvent } from 'nostr-tools' +import { Event, verifyEvent } from 'nostr-tools' import { useEffect, useState } from 'react' import { toast } from 'react-toastify' import { LoadingSpinner } from '../../components/LoadingSpinner' import { UserAvatar } from '../../components/UserAvatar' -import { MetadataController, NostrController } from '../../controllers' +import { NostrController } from '../../controllers' import { CreateSignatureEventContent, Meta, - ProfileMetadata, SignedEventContent } from '../../types' import { decryptArrayBuffer, extractMarksFromSignedMeta, - extractZipUrlAndEncryptionKey, getHash, hexToNpub, unixNow, @@ -51,6 +49,8 @@ import { useSelector } from 'react-redux' import { getLastSignersSig } from '../../utils/sign.ts' import { saveAs } from 'file-saver' import { Container } from '../../components/Container' +import { useSigitMeta } from '../../hooks/useSigitMeta.tsx' +import { useSigitProfiles } from '../../hooks/useSigitProfiles.tsx' export const VerifyPage = () => { const theme = useTheme() @@ -63,52 +63,35 @@ export const VerifyPage = () => { * uploadedZip will be received from home page when a user uploads a sigit zip wrapper that contains meta.json * meta will be received in navigation from create & home page in online mode */ - const { uploadedZip, meta: metaInNavState } = location.state || {} + const { uploadedZip, meta } = location.state || {} + + const { submittedBy, zipUrl, encryptionKey, signers, viewers, fileHashes } = + useSigitMeta(meta) + const profiles = useSigitProfiles([ + ...(submittedBy ? [submittedBy] : []), + ...signers, + ...viewers + ]) const [isLoading, setIsLoading] = useState(false) const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') const [selectedFile, setSelectedFile] = useState(null) - const [meta, setMeta] = useState(null) - const [submittedBy, setSubmittedBy] = useState() - - const [signers, setSigners] = useState<`npub1${string}`[]>([]) - const [viewers, setViewers] = useState<`npub1${string}`[]>([]) - const [creatorFileHashes, setCreatorFileHashes] = useState<{ - [key: string]: string - }>({}) const [currentFileHashes, setCurrentFileHashes] = useState<{ [key: string]: string | null - }>({}) + }>(fileHashes) const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({}) - const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>( - {} - ) const usersPubkey = useSelector((state: State) => state.auth.usersPubkey) const nostrController = NostrController.getInstance() useEffect(() => { if (uploadedZip) { setSelectedFile(uploadedZip) - } else if (metaInNavState) { + } else if (meta && encryptionKey) { const processSigit = async () => { setIsLoading(true) - setLoadingSpinnerDesc('Extracting zipUrl and encryption key from meta') - - const res = await extractZipUrlAndEncryptionKey(metaInNavState) - if (!res) { - setIsLoading(false) - return - } - - const { - zipUrl, - encryptionKey, - createSignatureEvent, - createSignatureContent - } = res setLoadingSpinnerDesc('Fetching file from file server') axios @@ -175,12 +158,6 @@ export const VerifyPage = () => { setCurrentFileHashes(fileHashes) setFiles(files) - setSigners(createSignatureContent.signers) - setViewers(createSignatureContent.viewers) - setCreatorFileHashes(createSignatureContent.fileHashes) - setSubmittedBy(createSignatureEvent.pubkey) - - setMeta(metaInNavState) setIsLoading(false) } }) @@ -197,49 +174,7 @@ export const VerifyPage = () => { processSigit() } - }, [uploadedZip, metaInNavState]) - - useEffect(() => { - if (submittedBy) { - const metadataController = new MetadataController() - - const users = [submittedBy, ...signers, ...viewers] - - users.forEach((user) => { - const pubkey = npubToHex(user)! - - if (!(pubkey in metadata)) { - const handleMetadataEvent = (event: Event) => { - const metadataContent = - metadataController.extractProfileMetadataContent(event) - if (metadataContent) - setMetadata((prev) => ({ - ...prev, - [pubkey]: metadataContent - })) - } - - metadataController.on(pubkey, (kind: number, event: Event) => { - if (kind === kinds.Metadata) { - handleMetadataEvent(event) - } - }) - - metadataController - .findMetadata(pubkey) - .then((metadataEvent) => { - if (metadataEvent) handleMetadataEvent(metadataEvent) - }) - .catch((err) => { - console.error( - `error occurred in finding metadata for: ${user}`, - err - ) - }) - } - }) - } - }, [submittedBy, signers, viewers, metadata]) + }, [encryptionKey, meta, uploadedZip, zipUrl]) const handleVerify = async () => { if (!selectedFile) return @@ -345,12 +280,6 @@ export const VerifyPage = () => { if (!createSignatureContent) return - setSigners(createSignatureContent.signers) - setViewers(createSignatureContent.viewers) - setCreatorFileHashes(createSignatureContent.fileHashes) - setSubmittedBy(createSignatureEvent.pubkey) - - setMeta(parsedMetaJson) setIsLoading(false) } @@ -451,7 +380,7 @@ export const VerifyPage = () => { } const displayUser = (pubkey: string, verifySignature = false) => { - const profile = metadata[pubkey] + const profile = profiles[pubkey] let isValidSignature = false @@ -682,7 +611,7 @@ export const VerifyPage = () => { {Object.entries(currentFileHashes).map( ([filename, hash], index) => { - const isValidHash = creatorFileHashes[filename] === hash + const isValidHash = fileHashes[filename] === hash return ( diff --git a/src/utils/meta.ts b/src/utils/meta.ts index b3c0c28..74d38b7 100644 --- a/src/utils/meta.ts +++ b/src/utils/meta.ts @@ -69,7 +69,7 @@ export enum SigitMetaParseErrorType { export interface SigitCardDisplayInfo { createdAt?: number title?: string - submittedBy?: string + submittedBy?: `npub1${string}` signers: `npub1${string}`[] fileExtensions: string[] signedStatus: SigitStatus @@ -161,7 +161,7 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => { ) sigitInfo.title = createSignatureContent.title - sigitInfo.submittedBy = createSignatureEvent.pubkey + sigitInfo.submittedBy = createSignatureEvent.pubkey as `npub1${string}` sigitInfo.signers = createSignatureContent.signers sigitInfo.fileExtensions = extensions From bc23361fb037779de5d7c6fe89cdbefd2ce0479d Mon Sep 17 00:00:00 2001 From: enes Date: Tue, 13 Aug 2024 17:26:21 +0200 Subject: [PATCH 07/27] refactor: move styles from page to Avatar Group component --- src/components/DisplaySigit/index.tsx | 2 +- src/components/DisplaySigit/style.module.scss | 20 ------------------- src/components/UserAvatarGroup/index.tsx | 2 +- .../UserAvatarGroup/style.module.scss | 20 +++++++++++++++++++ 4 files changed, 22 insertions(+), 22 deletions(-) diff --git a/src/components/DisplaySigit/index.tsx b/src/components/DisplaySigit/index.tsx index ce82f47..dfbcbba 100644 --- a/src/components/DisplaySigit/index.tsx +++ b/src/components/DisplaySigit/index.tsx @@ -77,7 +77,7 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => { {submittedBy && signers.length ? ( ) : null} - + {signers.map((signer) => { const pubkey = npubToHex(signer)! const profile = profiles[pubkey] diff --git a/src/components/DisplaySigit/style.module.scss b/src/components/DisplaySigit/style.module.scss index 7544fc4..4bb2f15 100644 --- a/src/components/DisplaySigit/style.module.scss +++ b/src/components/DisplaySigit/style.module.scss @@ -93,26 +93,6 @@ grid-gap: 10px; } -.signers { - padding: 0 0 0 10px; - - > * { - transition: margin ease 0.2s; - margin: 0 0 0 -10px; - position: relative; - z-index: 1; - &:first-child { - margin-left: -10px !important; - } - } - - > *:hover, - > *:focus-within { - margin: 0 15px 0 5px; - z-index: 2; - } -} - .details { color: rgba(0, 0, 0, 0.3); font-size: 14px; diff --git a/src/components/UserAvatarGroup/index.tsx b/src/components/UserAvatarGroup/index.tsx index 13f8b25..f8e231f 100644 --- a/src/components/UserAvatarGroup/index.tsx +++ b/src/components/UserAvatarGroup/index.tsx @@ -28,7 +28,7 @@ export const UserAvatarGroup = ({ const childrenArray = Children.toArray(children) return ( -
+
{surplus > 1 ? childrenArray.slice(0, surplus * -1).map((c) => c) : children} diff --git a/src/components/UserAvatarGroup/style.module.scss b/src/components/UserAvatarGroup/style.module.scss index 9604202..c9ee551 100644 --- a/src/components/UserAvatarGroup/style.module.scss +++ b/src/components/UserAvatarGroup/style.module.scss @@ -1,5 +1,25 @@ @import '../../styles/colors.scss'; +.container { + padding: 0 0 0 10px; + + > * { + transition: margin ease 0.2s; + margin: 0 0 0 -10px; + position: relative; + z-index: 1; + &:first-child { + margin-left: -10px !important; + } + } + + > *:hover, + > *:focus-within { + margin: 0 15px 0 5px; + z-index: 2; + } +} + .icon { width: 40px; height: 40px; From e16b8cfe3fe297983a3fd122ac25b89ca1568835 Mon Sep 17 00:00:00 2001 From: enes Date: Tue, 13 Aug 2024 17:27:08 +0200 Subject: [PATCH 08/27] feat: add sticky layout with slots --- src/layouts/Files.module.scss | 24 ++++++++++++++++++++++++ src/layouts/Files.tsx | 29 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 src/layouts/Files.module.scss create mode 100644 src/layouts/Files.tsx diff --git a/src/layouts/Files.module.scss b/src/layouts/Files.module.scss new file mode 100644 index 0000000..bda18dc --- /dev/null +++ b/src/layouts/Files.module.scss @@ -0,0 +1,24 @@ +@import '../styles/colors.scss'; +@import '../styles/sizes.scss'; + +.container { + display: grid; + grid-template-columns: 0.75fr 1.5fr 0.75fr; + grid-gap: 30px; + flex-grow: 1; +} + +.sidesWrap { + position: relative; +} + +.sides { + position: sticky; + top: $header-height + $body-vertical-padding; +} + +.files { + display: flex; + flex-direction: column; + grid-gap: 15px; +} diff --git a/src/layouts/Files.tsx b/src/layouts/Files.tsx new file mode 100644 index 0000000..a494293 --- /dev/null +++ b/src/layouts/Files.tsx @@ -0,0 +1,29 @@ +import { PropsWithChildren, ReactNode } from 'react' + +import styles from './Files.module.scss' + +interface FilesProps { + left: ReactNode + right: ReactNode + content: ReactNode +} + +export const Files = ({ + left, + right, + content, + children +}: PropsWithChildren) => { + return ( +
+
+
{left}
+
+
{content}
+
+
{right}
+
+ {children} +
+ ) +} From b3155cce0d9cc6be4fc20c9130988c76ea417784 Mon Sep 17 00:00:00 2001 From: enes Date: Tue, 13 Aug 2024 17:28:14 +0200 Subject: [PATCH 09/27] refactor: expand useSigitMeta and update verify w details section --- src/components/FilesUsers.tsx/index.tsx | 246 +++++++++++++++++ .../FilesUsers.tsx/style.module.scss | 41 +++ src/hooks/useSigitMeta.tsx | 54 +++- src/pages/verify/index.tsx | 249 ++---------------- src/utils/meta.ts | 47 ++-- 5 files changed, 376 insertions(+), 261 deletions(-) create mode 100644 src/components/FilesUsers.tsx/index.tsx create mode 100644 src/components/FilesUsers.tsx/style.module.scss diff --git a/src/components/FilesUsers.tsx/index.tsx b/src/components/FilesUsers.tsx/index.tsx new file mode 100644 index 0000000..59e3a09 --- /dev/null +++ b/src/components/FilesUsers.tsx/index.tsx @@ -0,0 +1,246 @@ +import { CheckCircle, Cancel } from '@mui/icons-material' +import { Divider, Tooltip } from '@mui/material' +import { verifyEvent } from 'nostr-tools' +import { useSigitProfiles } from '../../hooks/useSigitProfiles' +import { Meta, SignedEventContent } from '../../types' +import { + extractFileExtensions, + formatTimestamp, + fromUnixTimestamp, + hexToNpub, + npubToHex, + shorten +} from '../../utils' +import { UserAvatar } from '../UserAvatar' +import { useSigitMeta } from '../../hooks/useSigitMeta' +import { UserAvatarGroup } from '../UserAvatarGroup' + +import styles from './style.module.scss' +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' +import { + faCalendar, + faCalendarCheck, + faCalendarPlus, + faEye, + faFile, + faFileCircleExclamation +} from '@fortawesome/free-solid-svg-icons' +import { getExtensionIconLabel } from '../getExtensionIconLabel' +import { useSelector } from 'react-redux' +import { State } from '../../store/rootReducer' + +interface FileUsersProps { + meta: Meta +} + +export const FileUsers = ({ meta }: FileUsersProps) => { + const { usersPubkey } = useSelector((state: State) => state.auth) + const { + submittedBy, + signers, + viewers, + fileHashes, + sig, + docSignatures, + parsedSignatureEvents, + createdAt, + signedStatus, + completedAt + } = useSigitMeta(meta) + const profiles = useSigitProfiles([ + ...(submittedBy ? [submittedBy] : []), + ...signers, + ...viewers + ]) + const userCanSign = + typeof usersPubkey !== 'undefined' && + signers.includes(hexToNpub(usersPubkey)) + + const ext = extractFileExtensions(Object.keys(fileHashes)) + + const getPrevSignersSig = (npub: string) => { + // if user is first signer then use creator's signature + if (signers[0] === npub) { + return sig + } + + // find the index of signer + const currentSignerIndex = signers.findIndex((signer) => signer === npub) + // return null if could not found user in signer's list + if (currentSignerIndex === -1) return null + // find prev signer + const prevSigner = signers[currentSignerIndex - 1] + + // get the signature of prev signer + try { + const prevSignersEvent = parsedSignatureEvents[prevSigner] + return prevSignersEvent.sig + } catch (error) { + return null + } + } + + const displayUser = (pubkey: string, verifySignature = false) => { + const profile = profiles[pubkey] + + let isValidSignature = false + + if (verifySignature) { + const npub = hexToNpub(pubkey) + const signedEventString = docSignatures[npub] + if (signedEventString) { + try { + const signedEvent = JSON.parse(signedEventString) + const isVerifiedEvent = verifyEvent(signedEvent) + + if (isVerifiedEvent) { + // get the actual signature of prev signer + const prevSignersSig = getPrevSignersSig(npub) + + // get the signature of prev signer from the content of current signers signedEvent + + try { + const obj: SignedEventContent = JSON.parse(signedEvent.content) + if ( + obj.prevSig && + prevSignersSig && + obj.prevSig === prevSignersSig + ) { + isValidSignature = true + } + } catch (error) { + isValidSignature = false + } + } + } catch (error) { + console.error( + `An error occurred in parsing and verifying the signature event for ${pubkey}`, + error + ) + } + } + } + + return ( + <> + + + {verifySignature && ( + <> + {isValidSignature && ( + + + + )} + + {!isValidSignature && ( + + + + )} + + )} + + ) + } + + return submittedBy ? ( +
+
+

Signers

+ {displayUser(submittedBy)} + {submittedBy && signers.length ? ( + + ) : null} + + {signers.length > 0 && + signers.map((signer) => ( + {displayUser(npubToHex(signer)!, true)} + ))} + {viewers.length > 0 && + viewers.map((viewer) => ( + {displayUser(npubToHex(viewer)!)} + ))} + +
+
+

Details

+ + + + {' '} + {createdAt ? formatTimestamp(createdAt) : <>—} + + + + + + {' '} + {completedAt ? formatTimestamp(completedAt) : <>—} + + + + {/* User signed date */} + {userCanSign ? ( + + + {' '} + {hexToNpub(usersPubkey) in parsedSignatureEvents ? ( + parsedSignatureEvents[hexToNpub(usersPubkey)].created_at ? ( + formatTimestamp( + fromUnixTimestamp( + parsedSignatureEvents[hexToNpub(usersPubkey)].created_at + ) + ) + ) : ( + <>— + ) + ) : ( + <>— + )} + + + ) : null} + + {signedStatus} + + {ext.length > 0 ? ( + + {ext.length > 1 ? ( + <> + Multiple File Types + + ) : ( + getExtensionIconLabel(ext[0]) + )} + + ) : ( + <> + — + + )} +
+
+ ) : undefined +} diff --git a/src/components/FilesUsers.tsx/style.module.scss b/src/components/FilesUsers.tsx/style.module.scss new file mode 100644 index 0000000..b6e0313 --- /dev/null +++ b/src/components/FilesUsers.tsx/style.module.scss @@ -0,0 +1,41 @@ +@import '../../styles/colors.scss'; + +.container { + border-radius: 4px; + background: $overlay-background-color; + padding: 15px; + display: flex; + flex-direction: column; + grid-gap: 25px; + + font-size: 14px; +} + +.section { + display: flex; + flex-direction: column; + grid-gap: 10px; +} + +.detailsItem { + transition: ease 0.2s; + color: rgba(0, 0, 0, 0.5); + font-size: 14px; + align-items: center; + border-radius: 4px; + padding: 5px; + + display: flex; + align-items: center; + justify-content: start; + + > :first-child { + padding: 5px; + margin-right: 10px; + } + + &:hover { + background: $primary-main; + color: white; + } +} diff --git a/src/hooks/useSigitMeta.tsx b/src/hooks/useSigitMeta.tsx index 5460983..78516d5 100644 --- a/src/hooks/useSigitMeta.tsx +++ b/src/hooks/useSigitMeta.tsx @@ -4,7 +4,7 @@ import { Mark } from '../types/mark' import { fromUnixTimestamp, hexToNpub, - parseCreateSignatureEvent, + parseNostrEvent, parseCreateSignatureEventContent, SigitMetaParseError, SigitStatus, @@ -21,7 +21,7 @@ import { NostrController } from '../controllers' * Flattened interface that combines properties `Meta`, `CreateSignatureEventContent`, * and `Event` (event's fields are made optional and pubkey and created_at replaced with our versions) */ -interface FlatMeta +export interface FlatMeta extends Meta, CreateSignatureEventContent, Partial> { @@ -37,6 +37,12 @@ interface FlatMeta // Decryption encryptionKey: string | null + // Parsed Document Signatures + parsedSignatureEvents: { [signer: `npub1${string}`]: Event } + + // Calculated completion time + completedAt?: number + // Calculated status fields signedStatus: SigitStatus signersStatus: { @@ -67,6 +73,12 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { const [title, setTitle] = useState('') const [zipUrl, setZipUrl] = useState('') + const [parsedSignatureEvents, setParsedSignatureEvents] = useState<{ + [signer: `npub1${string}`]: Event + }>({}) + + const [completedAt, setCompletedAt] = useState() + const [signedStatus, setSignedStatus] = useState( SigitStatus.Partial ) @@ -80,9 +92,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { if (!meta) return ;(async function () { try { - const createSignatureEvent = await parseCreateSignatureEvent( - meta.createSignature - ) + const createSignatureEvent = await parseNostrEvent(meta.createSignature) const { kind, tags, created_at, pubkey, id, sig, content } = createSignatureEvent @@ -131,13 +141,22 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { } } - // Parse each signature event and set signer status + // Temp. map to hold events + const parsedSignatureEventsMap = new Map<`npub1${string}`, Event>() for (const npub in meta.docSignatures) { try { - const event = await parseCreateSignatureEvent( + // Parse each signature event + const event = await parseNostrEvent( meta.docSignatures[npub as `npub1${string}`] ) + const isValidSignature = verifyEvent(event) + + // Save events to a map, to save all at once outside loop + // We need the object to find completedAt + // Avoided using parsedSignatureEvents due to useEffect deps + parsedSignatureEventsMap.set(npub as `npub1${string}`, event) + setSignersStatus((prev) => { return { ...prev, @@ -155,6 +174,11 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { }) } } + + setParsedSignatureEvents( + Object.fromEntries(parsedSignatureEventsMap.entries()) + ) + const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[] const isCompletelySigned = signers.every((signer) => signedBy.includes(signer) @@ -162,6 +186,20 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { setSignedStatus( isCompletelySigned ? SigitStatus.Complete : SigitStatus.Partial ) + + // Check if all signers signed and are valid + if (isCompletelySigned) { + setCompletedAt( + fromUnixTimestamp( + signedBy.reduce((p, c) => { + return Math.max( + p, + parsedSignatureEventsMap.get(c)?.created_at || 0 + ) + }, 0) + ) + ) + } } catch (error) { if (error instanceof SigitMetaParseError) { toast.error(error.message) @@ -189,6 +227,8 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { markConfig, title, zipUrl, + parsedSignatureEvents, + completedAt, signedStatus, signersStatus, encryptionKey diff --git a/src/pages/verify/index.tsx b/src/pages/verify/index.tsx index f77bd48..d6a297d 100644 --- a/src/pages/verify/index.tsx +++ b/src/pages/verify/index.tsx @@ -1,36 +1,20 @@ -import { - Box, - Button, - List, - ListItem, - ListSubheader, - Tooltip, - Typography, - useTheme -} from '@mui/material' +import { Box, Button, Tooltip, Typography, useTheme } from '@mui/material' import JSZip from 'jszip' import { MuiFileInput } from 'mui-file-input' import { Event, verifyEvent } from 'nostr-tools' import { useEffect, useState } from 'react' import { toast } from 'react-toastify' import { LoadingSpinner } from '../../components/LoadingSpinner' -import { UserAvatar } from '../../components/UserAvatar' import { NostrController } from '../../controllers' -import { - CreateSignatureEventContent, - Meta, - SignedEventContent -} from '../../types' +import { CreateSignatureEventContent, Meta } from '../../types' import { decryptArrayBuffer, extractMarksFromSignedMeta, getHash, hexToNpub, unixNow, - npubToHex, parseJson, readContentOfZipEntry, - shorten, signEventForMetaFile } from '../../utils' import styles from './style.module.scss' @@ -50,7 +34,8 @@ import { getLastSignersSig } from '../../utils/sign.ts' import { saveAs } from 'file-saver' import { Container } from '../../components/Container' import { useSigitMeta } from '../../hooks/useSigitMeta.tsx' -import { useSigitProfiles } from '../../hooks/useSigitProfiles.tsx' +import { Files } from '../../layouts/Files.tsx' +import { FileUsers } from '../../components/FilesUsers.tsx/index.tsx' export const VerifyPage = () => { const theme = useTheme() @@ -67,11 +52,6 @@ export const VerifyPage = () => { const { submittedBy, zipUrl, encryptionKey, signers, viewers, fileHashes } = useSigitMeta(meta) - const profiles = useSigitProfiles([ - ...(submittedBy ? [submittedBy] : []), - ...signers, - ...viewers - ]) const [isLoading, setIsLoading] = useState(false) const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') @@ -283,35 +263,6 @@ export const VerifyPage = () => { setIsLoading(false) } - const getPrevSignersSig = (npub: string) => { - if (!meta) return null - - // if user is first signer then use creator's signature - if (signers[0] === npub) { - try { - const createSignatureEvent: Event = JSON.parse(meta.createSignature) - return createSignatureEvent.sig - } catch (error) { - return null - } - } - - // find the index of signer - const currentSignerIndex = signers.findIndex((signer) => signer === npub) - // return null if could not found user in signer's list - if (currentSignerIndex === -1) return null - // find prev signer - const prevSigner = signers[currentSignerIndex - 1] - - // get the signature of prev signer - try { - const prevSignersEvent: Event = JSON.parse(meta.docSignatures[prevSigner]) - return prevSignersEvent.sig - } catch (error) { - return null - } - } - const handleExport = async () => { if (Object.entries(files).length === 0 || !meta || !usersPubkey) return @@ -379,76 +330,6 @@ export const VerifyPage = () => { setIsLoading(false) } - const displayUser = (pubkey: string, verifySignature = false) => { - const profile = profiles[pubkey] - - let isValidSignature = false - - if (verifySignature) { - const npub = hexToNpub(pubkey) - const signedEventString = meta ? meta.docSignatures[npub] : null - if (signedEventString) { - try { - const signedEvent = JSON.parse(signedEventString) - const isVerifiedEvent = verifyEvent(signedEvent) - - if (isVerifiedEvent) { - // get the actual signature of prev signer - const prevSignersSig = getPrevSignersSig(npub) - - // get the signature of prev signer from the content of current signers signedEvent - - try { - const obj: SignedEventContent = JSON.parse(signedEvent.content) - if ( - obj.prevSig && - prevSignersSig && - obj.prevSig === prevSignersSig - ) { - isValidSignature = true - } - } catch (error) { - isValidSignature = false - } - } - } catch (error) { - console.error( - `An error occurred in parsing and verifying the signature event for ${pubkey}`, - error - ) - } - } - } - - return ( - <> - - - {verifySignature && ( - <> - {isValidSignature && ( - - - - )} - - {!isValidSignature && ( - - - - )} - - )} - - ) - } - const displayExportedBy = () => { if (!meta || !meta.exportSignature) return null @@ -458,7 +339,7 @@ export const VerifyPage = () => { const exportSignatureEvent = JSON.parse(exportSignatureString) as Event if (verifyEvent(exportSignatureEvent)) { - return displayUser(exportSignatureEvent.pubkey) + // return displayUser(exportSignatureEvent.pubkey) } else { toast.error(`Invalid export signature!`) return ( @@ -505,109 +386,9 @@ export const VerifyPage = () => { )} {meta && ( - <> - - Meta Info - - } - > - {submittedBy && ( - - - Submitted By - - {displayUser(submittedBy)} - - )} - - - - Exported By - - {displayExportedBy()} - - - - - - {signers.length > 0 && ( - - - Signers - -
    - {signers.map((signer) => ( -
  • - {displayUser(npubToHex(signer)!, true)} -
  • - ))} -
-
- )} - - {viewers.length > 0 && ( - - - Viewers - -
    - {viewers.map((viewer) => ( -
  • - {displayUser(npubToHex(viewer)!)} -
  • - ))} -
-
- )} - - - - Files - + {Object.entries(currentFileHashes).map( ([filename, hash], index) => { @@ -643,9 +424,17 @@ export const VerifyPage = () => { } )} - -
- + {displayExportedBy()} + + + + + } + right={} + content={
} + /> )} diff --git a/src/utils/meta.ts b/src/utils/meta.ts index 74d38b7..dd29b60 100644 --- a/src/utils/meta.ts +++ b/src/utils/meta.ts @@ -62,7 +62,7 @@ function handleError(error: unknown): Error { // Reuse common error messages for meta parsing export enum SigitMetaParseErrorType { - 'PARSE_ERROR_SIGNATURE_EVENT' = 'error occurred in parsing the create signature event', + 'PARSE_ERROR_EVENT' = 'error occurred in parsing the create signature event', 'PARSE_ERROR_SIGNATURE_EVENT_CONTENT' = "err in parsing the createSignature event's content" } @@ -76,24 +76,19 @@ export interface SigitCardDisplayInfo { } /** - * Wrapper for createSignatureEvent parse that throws custom SigitMetaParseError with cause and context + * Wrapper for event parser that throws custom SigitMetaParseError with cause and context * @param raw Raw string for parsing * @returns parsed Event */ -export const parseCreateSignatureEvent = async ( - raw: string -): Promise => { +export const parseNostrEvent = async (raw: string): Promise => { try { - const createSignatureEvent = await parseJson(raw) - return createSignatureEvent + const event = await parseJson(raw) + return event } catch (error) { - throw new SigitMetaParseError( - SigitMetaParseErrorType.PARSE_ERROR_SIGNATURE_EVENT, - { - cause: handleError(error), - context: raw - } - ) + throw new SigitMetaParseError(SigitMetaParseErrorType.PARSE_ERROR_EVENT, { + cause: handleError(error), + context: raw + }) } } @@ -135,9 +130,7 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => { } try { - const createSignatureEvent = await parseCreateSignatureEvent( - meta.createSignature - ) + const createSignatureEvent = await parseNostrEvent(meta.createSignature) // created_at in nostr events are stored in seconds sigitInfo.createdAt = fromUnixTimestamp(createSignatureEvent.created_at) @@ -147,13 +140,7 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => { ) const files = Object.keys(createSignatureContent.fileHashes) - const extensions = files.reduce((result: string[], file: string) => { - const extension = file.split('.').pop() - if (extension) { - result.push(extension) - } - return result - }, []) + const extensions = extractFileExtensions(files) const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[] const isCompletelySigned = createSignatureContent.signers.every((signer) => @@ -179,3 +166,15 @@ export const extractSigitCardDisplayInfo = async (meta: Meta) => { } } } + +export const extractFileExtensions = (fileNames: string[]) => { + const extensions = fileNames.reduce((result: string[], file: string) => { + const extension = file.split('.').pop() + if (extension) { + result.push(extension) + } + return result + }, []) + + return extensions +} From 5ffedb68d67a1a60177861d0897341ab10741558 Mon Sep 17 00:00:00 2001 From: enes Date: Wed, 14 Aug 2024 11:20:48 +0200 Subject: [PATCH 10/27] refactor: rename Files to StickySideColumns and update css --- ...odule.scss => StickySideColumns.module.scss} | 5 +++++ .../{Files.tsx => StickySideColumns.tsx} | 17 +++++++---------- 2 files changed, 12 insertions(+), 10 deletions(-) rename src/layouts/{Files.module.scss => StickySideColumns.module.scss} (84%) rename src/layouts/{Files.tsx => StickySideColumns.tsx} (58%) diff --git a/src/layouts/Files.module.scss b/src/layouts/StickySideColumns.module.scss similarity index 84% rename from src/layouts/Files.module.scss rename to src/layouts/StickySideColumns.module.scss index bda18dc..63c4314 100644 --- a/src/layouts/Files.module.scss +++ b/src/layouts/StickySideColumns.module.scss @@ -22,3 +22,8 @@ flex-direction: column; grid-gap: 15px; } +.content { + max-width: 550px; + width: 100%; + margin: 0 auto; +} diff --git a/src/layouts/Files.tsx b/src/layouts/StickySideColumns.tsx similarity index 58% rename from src/layouts/Files.tsx rename to src/layouts/StickySideColumns.tsx index a494293..1ada87f 100644 --- a/src/layouts/Files.tsx +++ b/src/layouts/StickySideColumns.tsx @@ -1,29 +1,26 @@ import { PropsWithChildren, ReactNode } from 'react' -import styles from './Files.module.scss' +import styles from './StickySideColumns.module.scss' -interface FilesProps { - left: ReactNode - right: ReactNode - content: ReactNode +interface StickySideColumnsProps { + left?: ReactNode + right?: ReactNode } -export const Files = ({ +export const StickySideColumns = ({ left, right, - content, children -}: PropsWithChildren) => { +}: PropsWithChildren) => { return (
{left}
-
{content}
+
{children}
{right}
- {children}
) } From 97c82718cb2991309894d2fd823f25035504b9be Mon Sep 17 00:00:00 2001 From: Eugene Date: Wed, 14 Aug 2024 12:24:15 +0300 Subject: [PATCH 11/27] fix: page scrolling --- src/components/FileList/style.module.scss | 10 ++-- src/components/PDFView/PdfItem.tsx | 44 ++++++++++------- src/components/PDFView/PdfMarking.tsx | 1 + src/components/PDFView/PdfPageItem.tsx | 34 ++++++++----- src/components/PDFView/index.tsx | 47 +++++++++++++----- src/pages/create/index.tsx | 58 +++++++++++------------ src/types/mark.ts | 1 + 7 files changed, 118 insertions(+), 77 deletions(-) diff --git a/src/components/FileList/style.module.scss b/src/components/FileList/style.module.scss index bbf9311..4103897 100644 --- a/src/components/FileList/style.module.scss +++ b/src/components/FileList/style.module.scss @@ -48,17 +48,17 @@ flex-grow: 1; font-size: 16px; font-weight: 500; + + &.active { + background: #4c82a3; + color: white; + } } .fileItem:hover { transition: ease 0.2s; background: #4c82a3; color: white; - - &.active { - background: #4c82a3; - color: white; - } } .fileName { diff --git a/src/components/PDFView/PdfItem.tsx b/src/components/PDFView/PdfItem.tsx index eb5ceff..6e8aa64 100644 --- a/src/components/PDFView/PdfItem.tsx +++ b/src/components/PDFView/PdfItem.tsx @@ -1,6 +1,6 @@ import { PdfFile } from '../../types/drawing.ts' import { CurrentUserMark } from '../../types/mark.ts' -import PdfPageItem from './PdfPageItem.tsx'; +import PdfPageItem from './PdfPageItem.tsx' interface PdfItemProps { pdfFile: PdfFile @@ -13,23 +13,31 @@ interface PdfItemProps { /** * Responsible for displaying pages of a single Pdf File. */ -const PdfItem = ({ pdfFile, currentUserMarks, handleMarkClick, selectedMarkValue, selectedMark }: PdfItemProps) => { - const filterByPage = (marks: CurrentUserMark[], page: number): CurrentUserMark[] => { - return marks.filter((m) => m.mark.location.page === page); +const PdfItem = ({ + pdfFile, + currentUserMarks, + handleMarkClick, + selectedMarkValue, + selectedMark +}: PdfItemProps) => { + const filterByPage = ( + marks: CurrentUserMark[], + page: number + ): CurrentUserMark[] => { + return marks.filter((m) => m.mark.location.page === page) } - return ( - pdfFile.pages.map((page, i) => { - return ( - - ) - })) + return pdfFile.pages.map((page, i) => { + return ( + + ) + }) } -export default PdfItem \ No newline at end of file +export default PdfItem diff --git a/src/components/PDFView/PdfMarking.tsx b/src/components/PDFView/PdfMarking.tsx index fc49f79..1d4b522 100644 --- a/src/components/PDFView/PdfMarking.tsx +++ b/src/components/PDFView/PdfMarking.tsx @@ -126,6 +126,7 @@ const PdfMarking = (props: PdfMarkingProps) => { {currentUserMarks?.length > 0 && (
{ +const PdfPageItem = ({ + page, + currentUserMarks, + handleMarkClick, + selectedMarkValue, + selectedMark +}: PdfPageProps) => { + useEffect(() => { + if (selectedMark !== null && !!markRefs.current[selectedMark.id]) { + markRefs.current[selectedMark.id]?.scrollIntoView({ + behavior: 'smooth', + block: 'end' + }) + } + }, [selectedMark]) + const markRefs = useRef<(HTMLDivElement | null)[]>([]) return (
- - { - currentUserMarks.map((m, i) => ( + + {currentUserMarks.map((m, i) => ( +
(markRefs.current[m.id] = el)}> + /> +
))}
) } -export default PdfPageItem \ No newline at end of file +export default PdfPageItem diff --git a/src/components/PDFView/index.tsx b/src/components/PDFView/index.tsx index 4024d1a..2936f59 100644 --- a/src/components/PDFView/index.tsx +++ b/src/components/PDFView/index.tsx @@ -1,7 +1,8 @@ -import { Box } from '@mui/material' +import { Box, Divider } from '@mui/material' import PdfItem from './PdfItem.tsx' import { CurrentUserMark } from '../../types/mark.ts' import { CurrentUserFile } from '../../types/file.ts' +import { useEffect, useRef } from 'react' interface PdfViewProps { files: CurrentUserFile[] @@ -9,6 +10,7 @@ interface PdfViewProps { handleMarkClick: (id: number) => void selectedMarkValue: string selectedMark: CurrentUserMark | null + currentFile: CurrentUserFile | null } /** @@ -19,29 +21,48 @@ const PdfView = ({ currentUserMarks, handleMarkClick, selectedMarkValue, - selectedMark + selectedMark, + currentFile }: PdfViewProps) => { + const pdfRefs = useRef<(HTMLDivElement | null)[]>([]) + useEffect(() => { + if (currentFile !== null && !!pdfRefs.current[currentFile.id]) { + pdfRefs.current[currentFile.id]?.scrollIntoView({ + behavior: 'smooth', + block: 'end' + }) + } + }, [currentFile]) const filterByFile = ( currentUserMarks: CurrentUserMark[], - hash: string + fileName: string ): CurrentUserMark[] => { return currentUserMarks.filter( - (currentUserMark) => currentUserMark.mark.pdfFileHash === hash + (currentUserMark) => currentUserMark.mark.fileName === fileName ) } + const isNotLastPdfFile = (index: number, files: CurrentUserFile[]): boolean => + !(index !== files.length - 1) return ( - {files.map(({ pdfFile, hash }, i) => { + {files.map((currentUserFile, index, arr) => { + const { hash, pdfFile, filename, id } = currentUserFile if (!hash) return return ( - +
(pdfRefs.current[id] = el)} + key={index} + > + + {isNotLastPdfFile(index, arr) && File Separator} +
) })}
diff --git a/src/pages/create/index.tsx b/src/pages/create/index.tsx index 830f9ef..8d6a278 100644 --- a/src/pages/create/index.tsx +++ b/src/pages/create/index.tsx @@ -338,32 +338,36 @@ export const CreatePage = () => { fileHashes[file.name] = hash } + console.log('file hashes: ', fileHashes) + return fileHashes } - const createMarks = (fileHashes: { [key: string]: string }) : Mark[] => { - return drawnPdfs.flatMap((drawnPdf) => { - const fileHash = fileHashes[drawnPdf.file.name]; - return drawnPdf.pages.flatMap((page, index) => { - return page.drawnFields.map((drawnField) => { - return { - type: drawnField.type, - location: { - page: index, - top: drawnField.top, - left: drawnField.left, - height: drawnField.height, - width: drawnField.width, - }, - npub: drawnField.counterpart, - pdfFileHash: fileHash - } + const createMarks = (fileHashes: { [key: string]: string }): Mark[] => { + return drawnPdfs + .flatMap((drawnPdf) => { + const fileHash = fileHashes[drawnPdf.file.name] + return drawnPdf.pages.flatMap((page, index) => { + return page.drawnFields.map((drawnField) => { + return { + type: drawnField.type, + location: { + page: index, + top: drawnField.top, + left: drawnField.left, + height: drawnField.height, + width: drawnField.width + }, + npub: drawnField.counterpart, + pdfFileHash: fileHash, + fileName: drawnPdf.file.name + } + }) }) }) - }) .map((mark, index) => { - return {...mark, id: index } - }); + return { ...mark, id: index } + }) } // Handle errors during zip file generation @@ -431,13 +435,9 @@ export const CreatePage = () => { if (!arraybuffer) return null - return new File( - [new Blob([arraybuffer])], - `${unixNow}.sigit.zip`, - { - type: 'application/zip' - } - ) + return new File([new Blob([arraybuffer])], `${unixNow}.sigit.zip`, { + type: 'application/zip' + }) } // Handle errors during file upload @@ -545,9 +545,7 @@ export const CreatePage = () => { : viewers.map((viewer) => viewer.pubkey) ).filter((receiver) => receiver !== usersPubkey) - return receivers.map((receiver) => - sendNotification(receiver, meta) - ) + return receivers.map((receiver) => sendNotification(receiver, meta)) } const handleCreate = async () => { diff --git a/src/types/mark.ts b/src/types/mark.ts index c0f9b88..efc1899 100644 --- a/src/types/mark.ts +++ b/src/types/mark.ts @@ -14,6 +14,7 @@ export interface Mark { pdfFileHash: string type: MarkType location: MarkLocation + fileName: string value?: string } From dfe67b99ad7d80b1ab7c3d41bd5f5281d1fc1f5e Mon Sep 17 00:00:00 2001 From: enes Date: Tue, 13 Aug 2024 17:27:08 +0200 Subject: [PATCH 12/27] feat: add sticky layout with slots --- src/layouts/Files.module.scss | 24 ++++++++++++++++++++++++ src/layouts/Files.tsx | 29 +++++++++++++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 src/layouts/Files.module.scss create mode 100644 src/layouts/Files.tsx diff --git a/src/layouts/Files.module.scss b/src/layouts/Files.module.scss new file mode 100644 index 0000000..bda18dc --- /dev/null +++ b/src/layouts/Files.module.scss @@ -0,0 +1,24 @@ +@import '../styles/colors.scss'; +@import '../styles/sizes.scss'; + +.container { + display: grid; + grid-template-columns: 0.75fr 1.5fr 0.75fr; + grid-gap: 30px; + flex-grow: 1; +} + +.sidesWrap { + position: relative; +} + +.sides { + position: sticky; + top: $header-height + $body-vertical-padding; +} + +.files { + display: flex; + flex-direction: column; + grid-gap: 15px; +} diff --git a/src/layouts/Files.tsx b/src/layouts/Files.tsx new file mode 100644 index 0000000..a494293 --- /dev/null +++ b/src/layouts/Files.tsx @@ -0,0 +1,29 @@ +import { PropsWithChildren, ReactNode } from 'react' + +import styles from './Files.module.scss' + +interface FilesProps { + left: ReactNode + right: ReactNode + content: ReactNode +} + +export const Files = ({ + left, + right, + content, + children +}: PropsWithChildren) => { + return ( +
+
+
{left}
+
+
{content}
+
+
{right}
+
+ {children} +
+ ) +} From 50c8f2b2d0806c820d5bbe39875f029e48bd38e7 Mon Sep 17 00:00:00 2001 From: enes Date: Wed, 14 Aug 2024 11:20:48 +0200 Subject: [PATCH 13/27] refactor: rename Files to StickySideColumns and update css --- ...odule.scss => StickySideColumns.module.scss} | 5 +++++ .../{Files.tsx => StickySideColumns.tsx} | 17 +++++++---------- 2 files changed, 12 insertions(+), 10 deletions(-) rename src/layouts/{Files.module.scss => StickySideColumns.module.scss} (84%) rename src/layouts/{Files.tsx => StickySideColumns.tsx} (58%) diff --git a/src/layouts/Files.module.scss b/src/layouts/StickySideColumns.module.scss similarity index 84% rename from src/layouts/Files.module.scss rename to src/layouts/StickySideColumns.module.scss index bda18dc..63c4314 100644 --- a/src/layouts/Files.module.scss +++ b/src/layouts/StickySideColumns.module.scss @@ -22,3 +22,8 @@ flex-direction: column; grid-gap: 15px; } +.content { + max-width: 550px; + width: 100%; + margin: 0 auto; +} diff --git a/src/layouts/Files.tsx b/src/layouts/StickySideColumns.tsx similarity index 58% rename from src/layouts/Files.tsx rename to src/layouts/StickySideColumns.tsx index a494293..1ada87f 100644 --- a/src/layouts/Files.tsx +++ b/src/layouts/StickySideColumns.tsx @@ -1,29 +1,26 @@ import { PropsWithChildren, ReactNode } from 'react' -import styles from './Files.module.scss' +import styles from './StickySideColumns.module.scss' -interface FilesProps { - left: ReactNode - right: ReactNode - content: ReactNode +interface StickySideColumnsProps { + left?: ReactNode + right?: ReactNode } -export const Files = ({ +export const StickySideColumns = ({ left, right, - content, children -}: PropsWithChildren) => { +}: PropsWithChildren) => { return (
{left}
-
{content}
+
{children}
{right}
- {children}
) } From 64dbd7d479bb4baebc43d72f04dbedf7a18d02a7 Mon Sep 17 00:00:00 2001 From: Eugene Date: Wed, 14 Aug 2024 12:36:51 +0300 Subject: [PATCH 14/27] feat(pdf-marking): integrates layouts --- src/components/PDFView/PdfMarking.tsx | 50 +++++++++++++---------- src/layouts/StickySideColumns.module.scss | 2 +- src/pages/sign/style.module.scss | 4 +- 3 files changed, 31 insertions(+), 25 deletions(-) diff --git a/src/components/PDFView/PdfMarking.tsx b/src/components/PDFView/PdfMarking.tsx index 1d4b522..02a9627 100644 --- a/src/components/PDFView/PdfMarking.tsx +++ b/src/components/PDFView/PdfMarking.tsx @@ -13,6 +13,7 @@ import signPageStyles from '../../pages/sign/style.module.scss' import styles from './style.module.scss' import { CurrentUserFile } from '../../types/file.ts' import FileList from '../FileList' +import { StickySideColumns } from '../../layouts/StickySideColumns.tsx' interface PdfMarkingProps { files: CurrentUserFile[] @@ -112,30 +113,35 @@ const PdfMarking = (props: PdfMarkingProps) => { return ( <> -
-
- {currentFile !== null && ( - + + {currentFile !== null && ( + + )} +
+ } + > +
+ {currentUserMarks?.length > 0 && ( +
+ +
)}
- {currentUserMarks?.length > 0 && ( -
- -
- )} -
+ {selectedMark !== null && ( Date: Wed, 14 Aug 2024 14:25:33 +0200 Subject: [PATCH 15/27] feat: add simple spinner wrapper --- src/components/Spinner/index.tsx | 6 ++++++ src/components/Spinner/style.module.scss | 12 ++++++++++++ 2 files changed, 18 insertions(+) create mode 100644 src/components/Spinner/index.tsx create mode 100644 src/components/Spinner/style.module.scss diff --git a/src/components/Spinner/index.tsx b/src/components/Spinner/index.tsx new file mode 100644 index 0000000..cbc6b43 --- /dev/null +++ b/src/components/Spinner/index.tsx @@ -0,0 +1,6 @@ +import { PropsWithChildren } from 'react' +import styles from './style.module.scss' + +export const Spinner = ({ children }: PropsWithChildren) => ( +
{children}
+) diff --git a/src/components/Spinner/style.module.scss b/src/components/Spinner/style.module.scss new file mode 100644 index 0000000..08d8032 --- /dev/null +++ b/src/components/Spinner/style.module.scss @@ -0,0 +1,12 @@ +.spin { + animation: spin 1s linear infinite; +} + +@keyframes spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} From 4b04bdf39e5cb66c9c4ae45623d4f86432628a32 Mon Sep 17 00:00:00 2001 From: enes Date: Wed, 14 Aug 2024 14:27:49 +0200 Subject: [PATCH 16/27] refactor: useSigitMeta, DisplaySigners and UserDetails section --- src/components/DisplaySigit/index.tsx | 5 +- src/components/DisplaySigner/index.tsx | 81 +++--- src/components/FilesUsers.tsx/index.tsx | 246 ------------------ src/components/UsersDetails.tsx/index.tsx | 224 ++++++++++++++++ .../style.module.scss | 5 + src/hooks/useSigitMeta.tsx | 82 ++++-- src/pages/verify/index.tsx | 67 ++++- src/utils/meta.ts | 4 +- 8 files changed, 384 insertions(+), 330 deletions(-) delete mode 100644 src/components/FilesUsers.tsx/index.tsx create mode 100644 src/components/UsersDetails.tsx/index.tsx rename src/components/{FilesUsers.tsx => UsersDetails.tsx}/style.module.scss (93%) diff --git a/src/components/DisplaySigit/index.tsx b/src/components/DisplaySigit/index.tsx index dfbcbba..0d7407f 100644 --- a/src/components/DisplaySigit/index.tsx +++ b/src/components/DisplaySigit/index.tsx @@ -20,6 +20,7 @@ import styles from './style.module.scss' import { TooltipChild } from '../TooltipChild' import { getExtensionIconLabel } from '../getExtensionIconLabel' import { useSigitProfiles } from '../../hooks/useSigitProfiles' +import { useSigitMeta } from '../../hooks/useSigitMeta' type SigitProps = { meta: Meta @@ -36,6 +37,8 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => { fileExtensions } = parsedMeta + const { signersStatus } = useSigitMeta(meta) + const profiles = useSigitProfiles([ ...(submittedBy ? [submittedBy] : []), ...signers @@ -94,7 +97,7 @@ export const DisplaySigit = ({ meta, parsedMeta }: SigitProps) => { > diff --git a/src/components/DisplaySigner/index.tsx b/src/components/DisplaySigner/index.tsx index dc4b9ce..4f3824f 100644 --- a/src/components/DisplaySigner/index.tsx +++ b/src/components/DisplaySigner/index.tsx @@ -1,58 +1,50 @@ import { Badge } from '@mui/material' -import { Event, verifyEvent } from 'nostr-tools' -import { useState, useEffect } from 'react' -import { Meta, ProfileMetadata } from '../../types' -import { hexToNpub, parseJson } from '../../utils' +import { ProfileMetadata } from '../../types' import styles from './style.module.scss' import { UserAvatar } from '../UserAvatar' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' -import { faCheck, faExclamation } from '@fortawesome/free-solid-svg-icons' - -enum SignStatus { - Signed = 'Signed', - Pending = 'Pending', - Invalid = 'Invalid Sign' -} +import { + faCheck, + faExclamation, + faEye, + faHourglass, + faQuestion +} from '@fortawesome/free-solid-svg-icons' +import { SignStatus } from '../../utils' +import { Spinner } from '../Spinner' type DisplaySignerProps = { - meta: Meta profile: ProfileMetadata pubkey: string + status: SignStatus } export const DisplaySigner = ({ - meta, + status, profile, pubkey }: DisplaySignerProps) => { - const [signStatus, setSignedStatus] = useState() + const getStatusIcon = (status: SignStatus) => { + switch (status) { + case SignStatus.Signed: + return + case SignStatus.Awaiting: + return ( + + + + ) + case SignStatus.Pending: + return + case SignStatus.Invalid: + return + case SignStatus.Viewer: + return - useEffect(() => { - if (!meta) return - - const updateSignStatus = async () => { - const npub = hexToNpub(pubkey) - if (npub in meta.docSignatures) { - parseJson(meta.docSignatures[npub]) - .then((event) => { - const isValidSignature = verifyEvent(event) - if (isValidSignature) { - setSignedStatus(SignStatus.Signed) - } else { - setSignedStatus(SignStatus.Invalid) - } - }) - .catch((err) => { - console.log(`err in parsing the docSignatures for ${npub}:>> `, err) - setSignedStatus(SignStatus.Invalid) - }) - } else { - setSignedStatus(SignStatus.Pending) - } + default: + return } - - updateSignStatus() - }, [meta, pubkey]) + } return ( - {signStatus === SignStatus.Signed && ( - - )} - {signStatus === SignStatus.Invalid && ( - - )} -
- ) +
{getStatusIcon(status)}
} > diff --git a/src/components/FilesUsers.tsx/index.tsx b/src/components/FilesUsers.tsx/index.tsx deleted file mode 100644 index 59e3a09..0000000 --- a/src/components/FilesUsers.tsx/index.tsx +++ /dev/null @@ -1,246 +0,0 @@ -import { CheckCircle, Cancel } from '@mui/icons-material' -import { Divider, Tooltip } from '@mui/material' -import { verifyEvent } from 'nostr-tools' -import { useSigitProfiles } from '../../hooks/useSigitProfiles' -import { Meta, SignedEventContent } from '../../types' -import { - extractFileExtensions, - formatTimestamp, - fromUnixTimestamp, - hexToNpub, - npubToHex, - shorten -} from '../../utils' -import { UserAvatar } from '../UserAvatar' -import { useSigitMeta } from '../../hooks/useSigitMeta' -import { UserAvatarGroup } from '../UserAvatarGroup' - -import styles from './style.module.scss' -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' -import { - faCalendar, - faCalendarCheck, - faCalendarPlus, - faEye, - faFile, - faFileCircleExclamation -} from '@fortawesome/free-solid-svg-icons' -import { getExtensionIconLabel } from '../getExtensionIconLabel' -import { useSelector } from 'react-redux' -import { State } from '../../store/rootReducer' - -interface FileUsersProps { - meta: Meta -} - -export const FileUsers = ({ meta }: FileUsersProps) => { - const { usersPubkey } = useSelector((state: State) => state.auth) - const { - submittedBy, - signers, - viewers, - fileHashes, - sig, - docSignatures, - parsedSignatureEvents, - createdAt, - signedStatus, - completedAt - } = useSigitMeta(meta) - const profiles = useSigitProfiles([ - ...(submittedBy ? [submittedBy] : []), - ...signers, - ...viewers - ]) - const userCanSign = - typeof usersPubkey !== 'undefined' && - signers.includes(hexToNpub(usersPubkey)) - - const ext = extractFileExtensions(Object.keys(fileHashes)) - - const getPrevSignersSig = (npub: string) => { - // if user is first signer then use creator's signature - if (signers[0] === npub) { - return sig - } - - // find the index of signer - const currentSignerIndex = signers.findIndex((signer) => signer === npub) - // return null if could not found user in signer's list - if (currentSignerIndex === -1) return null - // find prev signer - const prevSigner = signers[currentSignerIndex - 1] - - // get the signature of prev signer - try { - const prevSignersEvent = parsedSignatureEvents[prevSigner] - return prevSignersEvent.sig - } catch (error) { - return null - } - } - - const displayUser = (pubkey: string, verifySignature = false) => { - const profile = profiles[pubkey] - - let isValidSignature = false - - if (verifySignature) { - const npub = hexToNpub(pubkey) - const signedEventString = docSignatures[npub] - if (signedEventString) { - try { - const signedEvent = JSON.parse(signedEventString) - const isVerifiedEvent = verifyEvent(signedEvent) - - if (isVerifiedEvent) { - // get the actual signature of prev signer - const prevSignersSig = getPrevSignersSig(npub) - - // get the signature of prev signer from the content of current signers signedEvent - - try { - const obj: SignedEventContent = JSON.parse(signedEvent.content) - if ( - obj.prevSig && - prevSignersSig && - obj.prevSig === prevSignersSig - ) { - isValidSignature = true - } - } catch (error) { - isValidSignature = false - } - } - } catch (error) { - console.error( - `An error occurred in parsing and verifying the signature event for ${pubkey}`, - error - ) - } - } - } - - return ( - <> - - - {verifySignature && ( - <> - {isValidSignature && ( - - - - )} - - {!isValidSignature && ( - - - - )} - - )} - - ) - } - - return submittedBy ? ( -
-
-

Signers

- {displayUser(submittedBy)} - {submittedBy && signers.length ? ( - - ) : null} - - {signers.length > 0 && - signers.map((signer) => ( - {displayUser(npubToHex(signer)!, true)} - ))} - {viewers.length > 0 && - viewers.map((viewer) => ( - {displayUser(npubToHex(viewer)!)} - ))} - -
-
-

Details

- - - - {' '} - {createdAt ? formatTimestamp(createdAt) : <>—} - - - - - - {' '} - {completedAt ? formatTimestamp(completedAt) : <>—} - - - - {/* User signed date */} - {userCanSign ? ( - - - {' '} - {hexToNpub(usersPubkey) in parsedSignatureEvents ? ( - parsedSignatureEvents[hexToNpub(usersPubkey)].created_at ? ( - formatTimestamp( - fromUnixTimestamp( - parsedSignatureEvents[hexToNpub(usersPubkey)].created_at - ) - ) - ) : ( - <>— - ) - ) : ( - <>— - )} - - - ) : null} - - {signedStatus} - - {ext.length > 0 ? ( - - {ext.length > 1 ? ( - <> - Multiple File Types - - ) : ( - getExtensionIconLabel(ext[0]) - )} - - ) : ( - <> - — - - )} -
-
- ) : undefined -} diff --git a/src/components/UsersDetails.tsx/index.tsx b/src/components/UsersDetails.tsx/index.tsx new file mode 100644 index 0000000..8b9217b --- /dev/null +++ b/src/components/UsersDetails.tsx/index.tsx @@ -0,0 +1,224 @@ +import { Divider, Tooltip } from '@mui/material' +import { useSigitProfiles } from '../../hooks/useSigitProfiles' +import { + extractFileExtensions, + formatTimestamp, + fromUnixTimestamp, + hexToNpub, + npubToHex, + shorten, + SignStatus +} from '../../utils' +import { UserAvatar } from '../UserAvatar' +import { FlatMeta } from '../../hooks/useSigitMeta' +import { UserAvatarGroup } from '../UserAvatarGroup' + +import styles from './style.module.scss' +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' +import { + faCalendar, + faCalendarCheck, + faCalendarPlus, + faEye, + faFile, + faFileCircleExclamation +} from '@fortawesome/free-solid-svg-icons' +import { getExtensionIconLabel } from '../getExtensionIconLabel' +import { useSelector } from 'react-redux' +import { State } from '../../store/rootReducer' +import { TooltipChild } from '../TooltipChild' +import { DisplaySigner } from '../DisplaySigner' + +type UsersDetailsProps = Pick< + FlatMeta, + | 'submittedBy' + | 'signers' + | 'viewers' + | 'fileHashes' + | 'parsedSignatureEvents' + | 'createdAt' + | 'signedStatus' + | 'completedAt' + | 'signersStatus' +> + +export const UsersDetails = ({ + submittedBy, + signers, + viewers, + fileHashes, + parsedSignatureEvents, + createdAt, + signedStatus, + completedAt, + signersStatus +}: UsersDetailsProps) => { + const { usersPubkey } = useSelector((state: State) => state.auth) + const profiles = useSigitProfiles([ + ...(submittedBy ? [submittedBy] : []), + ...signers, + ...viewers + ]) + const userCanSign = + typeof usersPubkey !== 'undefined' && + signers.includes(hexToNpub(usersPubkey)) + + const ext = extractFileExtensions(Object.keys(fileHashes)) + + return submittedBy ? ( +
+
+

Signers

+
+ {submittedBy && + (function () { + const profile = profiles[submittedBy] + return ( + + + + + + ) + })()} + + {submittedBy && signers.length ? ( + + ) : null} + + + {signers.map((signer) => { + const pubkey = npubToHex(signer)! + const profile = profiles[pubkey] + + return ( + + + + + + ) + })} + {viewers.map((signer) => { + const pubkey = npubToHex(signer)! + const profile = profiles[pubkey] + + return ( + + + + + + ) + })} + +
+
+
+

Details

+ + + + {' '} + {createdAt ? formatTimestamp(createdAt) : <>—} + + + + + + {' '} + {completedAt ? formatTimestamp(completedAt) : <>—} + + + + {/* User signed date */} + {userCanSign ? ( + + + {' '} + {hexToNpub(usersPubkey) in parsedSignatureEvents ? ( + parsedSignatureEvents[hexToNpub(usersPubkey)].created_at ? ( + formatTimestamp( + fromUnixTimestamp( + parsedSignatureEvents[hexToNpub(usersPubkey)].created_at + ) + ) + ) : ( + <>— + ) + ) : ( + <>— + )} + + + ) : null} + + {signedStatus} + + {ext.length > 0 ? ( + + {ext.length > 1 ? ( + <> + Multiple File Types + + ) : ( + getExtensionIconLabel(ext[0]) + )} + + ) : ( + <> + — + + )} +
+
+ ) : undefined +} diff --git a/src/components/FilesUsers.tsx/style.module.scss b/src/components/UsersDetails.tsx/style.module.scss similarity index 93% rename from src/components/FilesUsers.tsx/style.module.scss rename to src/components/UsersDetails.tsx/style.module.scss index b6e0313..9d906c1 100644 --- a/src/components/FilesUsers.tsx/style.module.scss +++ b/src/components/UsersDetails.tsx/style.module.scss @@ -17,6 +17,11 @@ grid-gap: 10px; } +.users { + display: flex; + grid-gap: 10px; +} + .detailsItem { transition: ease 0.2s; color: rgba(0, 0, 0, 0.5); diff --git a/src/hooks/useSigitMeta.tsx b/src/hooks/useSigitMeta.tsx index 78516d5..ca8ea6d 100644 --- a/src/hooks/useSigitMeta.tsx +++ b/src/hooks/useSigitMeta.tsx @@ -1,5 +1,5 @@ import { useEffect, useState } from 'react' -import { CreateSignatureEventContent, Meta } from '../types' +import { CreateSignatureEventContent, Meta, SignedEventContent } from '../types' import { Mark } from '../types/mark' import { fromUnixTimestamp, @@ -118,7 +118,6 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { if (meta.keys) { const { sender, keys } = meta.keys - // Retrieve the user's public key from the state const usersPubkey = (store.getState().auth as AuthState).usersPubkey! const usersNpub = hexToNpub(usersPubkey) @@ -141,8 +140,28 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { } } - // Temp. map to hold events + // Temp. map to hold events and signers const parsedSignatureEventsMap = new Map<`npub1${string}`, Event>() + const signerStatusMap = new Map<`npub1${string}`, SignStatus>() + + const getPrevSignerSig = (npub: `npub1${string}`) => { + if (signers[0] === npub) { + return sig + } + + // find the index of signer + const currentSignerIndex = signers.findIndex( + (signer) => signer === npub + ) + // return if could not found user in signer's list + if (currentSignerIndex === -1) return + // find prev signer + const prevSigner = signers[currentSignerIndex - 1] + + // get the signature of prev signer + return parsedSignatureEventsMap.get(prevSigner)?.sig + } + for (const npub in meta.docSignatures) { try { // Parse each signature event @@ -150,34 +169,49 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { meta.docSignatures[npub as `npub1${string}`] ) - const isValidSignature = verifyEvent(event) - // Save events to a map, to save all at once outside loop // We need the object to find completedAt // Avoided using parsedSignatureEvents due to useEffect deps parsedSignatureEventsMap.set(npub as `npub1${string}`, event) - - setSignersStatus((prev) => { - return { - ...prev, - [npub]: isValidSignature - ? SignStatus.Signed - : SignStatus.Invalid - } - }) } catch (error) { - setSignersStatus((prev) => { - return { - ...prev, - [npub]: SignStatus.Invalid - } - }) + signerStatusMap.set(npub as `npub1${string}`, SignStatus.Invalid) } } - setParsedSignatureEvents( - Object.fromEntries(parsedSignatureEventsMap.entries()) - ) + parsedSignatureEventsMap.forEach((event, npub) => { + const isValidSignature = verifyEvent(event) + if (isValidSignature) { + // get the signature of prev signer from the content of current signers signedEvent + const prevSignersSig = getPrevSignerSig(npub) + + try { + const obj: SignedEventContent = JSON.parse(event.content) + if ( + obj.prevSig && + prevSignersSig && + obj.prevSig === prevSignersSig + ) { + signerStatusMap.set(npub as `npub1${string}`, SignStatus.Signed) + } + } catch (error) { + signerStatusMap.set(npub as `npub1${string}`, SignStatus.Invalid) + } + } + }) + + const nextSigner = signers.find((s) => !parsedSignatureEventsMap.has(s)) + if (nextSigner) { + signerStatusMap.set(nextSigner, SignStatus.Awaiting) + } + + signers + .filter((s) => !(s in meta.docSignatures)) + .forEach((s) => + signerStatusMap.set(s as `npub1${string}`, SignStatus.Pending) + ) + + setSignersStatus(Object.fromEntries(signerStatusMap)) + setParsedSignatureEvents(Object.fromEntries(parsedSignatureEventsMap)) const signedBy = Object.keys(meta.docSignatures) as `npub1${string}`[] const isCompletelySigned = signers.every((signer) => @@ -187,7 +221,7 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { isCompletelySigned ? SigitStatus.Complete : SigitStatus.Partial ) - // Check if all signers signed and are valid + // Check if all signers signed if (isCompletelySigned) { setCompletedAt( fromUnixTimestamp( diff --git a/src/pages/verify/index.tsx b/src/pages/verify/index.tsx index d6a297d..bd35f14 100644 --- a/src/pages/verify/index.tsx +++ b/src/pages/verify/index.tsx @@ -15,7 +15,8 @@ import { unixNow, parseJson, readContentOfZipEntry, - signEventForMetaFile + signEventForMetaFile, + shorten } from '../../utils' import styles from './style.module.scss' import { Cancel, CheckCircle } from '@mui/icons-material' @@ -34,8 +35,11 @@ import { getLastSignersSig } from '../../utils/sign.ts' import { saveAs } from 'file-saver' import { Container } from '../../components/Container' import { useSigitMeta } from '../../hooks/useSigitMeta.tsx' -import { Files } from '../../layouts/Files.tsx' -import { FileUsers } from '../../components/FilesUsers.tsx/index.tsx' +import { StickySideColumns } from '../../layouts/StickySideColumns.tsx' +import { UsersDetails } from '../../components/UsersDetails.tsx/index.tsx' +import { UserAvatar } from '../../components/UserAvatar/index.tsx' +import { useSigitProfiles } from '../../hooks/useSigitProfiles.tsx' +import { TooltipChild } from '../../components/TooltipChild.tsx' export const VerifyPage = () => { const theme = useTheme() @@ -50,8 +54,25 @@ export const VerifyPage = () => { */ const { uploadedZip, meta } = location.state || {} - const { submittedBy, zipUrl, encryptionKey, signers, viewers, fileHashes } = - useSigitMeta(meta) + const { + submittedBy, + zipUrl, + encryptionKey, + signers, + viewers, + fileHashes, + parsedSignatureEvents, + createdAt, + signedStatus, + completedAt, + signersStatus + } = useSigitMeta(meta) + + const profiles = useSigitProfiles([ + ...(submittedBy ? [submittedBy] : []), + ...signers, + ...viewers + ]) const [isLoading, setIsLoading] = useState(false) const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('') @@ -339,7 +360,24 @@ export const VerifyPage = () => { const exportSignatureEvent = JSON.parse(exportSignatureString) as Event if (verifyEvent(exportSignatureEvent)) { - // return displayUser(exportSignatureEvent.pubkey) + const exportedBy = exportSignatureEvent.pubkey + const profile = profiles[exportedBy] + return ( + + + + + + ) } else { toast.error(`Invalid export signature!`) return ( @@ -386,7 +424,7 @@ export const VerifyPage = () => { )} {meta && ( - @@ -432,8 +470,19 @@ export const VerifyPage = () => { } - right={} - content={
} + right={ + + } /> )} diff --git a/src/utils/meta.ts b/src/utils/meta.ts index dd29b60..4915f19 100644 --- a/src/utils/meta.ts +++ b/src/utils/meta.ts @@ -5,8 +5,10 @@ import { toast } from 'react-toastify' export enum SignStatus { Signed = 'Signed', + Awaiting = 'Awaiting', Pending = 'Pending', - Invalid = 'Invalid Sign' + Invalid = 'Invalid', + Viewer = 'Viewer' } export enum SigitStatus { From 3743a30ef62084c6c3a8cfdfcb63d1f08f0162ed Mon Sep 17 00:00:00 2001 From: enes Date: Wed, 14 Aug 2024 14:31:26 +0200 Subject: [PATCH 17/27] fix: use correct key for signer status, update signer badge icons --- src/components/DisplaySigner/index.tsx | 3 ++- src/components/UsersDetails.tsx/index.tsx | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/components/DisplaySigner/index.tsx b/src/components/DisplaySigner/index.tsx index 4f3824f..63aa154 100644 --- a/src/components/DisplaySigner/index.tsx +++ b/src/components/DisplaySigner/index.tsx @@ -5,6 +5,7 @@ import { UserAvatar } from '../UserAvatar' import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import { faCheck, + faEllipsis, faExclamation, faEye, faHourglass, @@ -35,7 +36,7 @@ export const DisplaySigner = ({ ) case SignStatus.Pending: - return + return case SignStatus.Invalid: return case SignStatus.Viewer: diff --git a/src/components/UsersDetails.tsx/index.tsx b/src/components/UsersDetails.tsx/index.tsx index 8b9217b..ea58f68 100644 --- a/src/components/UsersDetails.tsx/index.tsx +++ b/src/components/UsersDetails.tsx/index.tsx @@ -112,7 +112,7 @@ export const UsersDetails = ({ > From d8adb2c74471bf55351b3649c699f8b6d4360a47 Mon Sep 17 00:00:00 2001 From: enes Date: Wed, 14 Aug 2024 14:34:51 +0200 Subject: [PATCH 18/27] fix: next signer and spinner anim duration --- src/components/Spinner/style.module.scss | 2 +- src/hooks/useSigitMeta.tsx | 11 +++++------ 2 files changed, 6 insertions(+), 7 deletions(-) diff --git a/src/components/Spinner/style.module.scss b/src/components/Spinner/style.module.scss index 08d8032..60158f4 100644 --- a/src/components/Spinner/style.module.scss +++ b/src/components/Spinner/style.module.scss @@ -1,5 +1,5 @@ .spin { - animation: spin 1s linear infinite; + animation: spin 5s linear infinite; } @keyframes spin { diff --git a/src/hooks/useSigitMeta.tsx b/src/hooks/useSigitMeta.tsx index ca8ea6d..a393824 100644 --- a/src/hooks/useSigitMeta.tsx +++ b/src/hooks/useSigitMeta.tsx @@ -199,17 +199,16 @@ export const useSigitMeta = (meta: Meta): FlatMeta => { } }) + signers + .filter((s) => !parsedSignatureEventsMap.has(s)) + .forEach((s) => signerStatusMap.set(s, SignStatus.Pending)) + + // Get the first signer that hasn't signed const nextSigner = signers.find((s) => !parsedSignatureEventsMap.has(s)) if (nextSigner) { signerStatusMap.set(nextSigner, SignStatus.Awaiting) } - signers - .filter((s) => !(s in meta.docSignatures)) - .forEach((s) => - signerStatusMap.set(s as `npub1${string}`, SignStatus.Pending) - ) - setSignersStatus(Object.fromEntries(signerStatusMap)) setParsedSignatureEvents(Object.fromEntries(parsedSignatureEventsMap)) From 1c3d3ca88ff951a83bb1689384ea807733c0e14c Mon Sep 17 00:00:00 2001 From: enes Date: Wed, 14 Aug 2024 14:44:11 +0200 Subject: [PATCH 19/27] refactor: pass meta to UserDetails instead of individual props --- src/components/UsersDetails.tsx/index.tsx | 41 ++++++++++------------- src/pages/verify/index.tsx | 29 ++-------------- 2 files changed, 20 insertions(+), 50 deletions(-) diff --git a/src/components/UsersDetails.tsx/index.tsx b/src/components/UsersDetails.tsx/index.tsx index ea58f68..fc7d43d 100644 --- a/src/components/UsersDetails.tsx/index.tsx +++ b/src/components/UsersDetails.tsx/index.tsx @@ -10,7 +10,7 @@ import { SignStatus } from '../../utils' import { UserAvatar } from '../UserAvatar' -import { FlatMeta } from '../../hooks/useSigitMeta' +import { useSigitMeta } from '../../hooks/useSigitMeta' import { UserAvatarGroup } from '../UserAvatarGroup' import styles from './style.module.scss' @@ -28,31 +28,24 @@ import { useSelector } from 'react-redux' import { State } from '../../store/rootReducer' import { TooltipChild } from '../TooltipChild' import { DisplaySigner } from '../DisplaySigner' +import { Meta } from '../../types' -type UsersDetailsProps = Pick< - FlatMeta, - | 'submittedBy' - | 'signers' - | 'viewers' - | 'fileHashes' - | 'parsedSignatureEvents' - | 'createdAt' - | 'signedStatus' - | 'completedAt' - | 'signersStatus' -> +interface UsersDetailsProps { + meta: Meta +} -export const UsersDetails = ({ - submittedBy, - signers, - viewers, - fileHashes, - parsedSignatureEvents, - createdAt, - signedStatus, - completedAt, - signersStatus -}: UsersDetailsProps) => { +export const UsersDetails = ({ meta }: UsersDetailsProps) => { + const { + submittedBy, + signers, + viewers, + fileHashes, + signersStatus, + createdAt, + completedAt, + parsedSignatureEvents, + signedStatus + } = useSigitMeta(meta) const { usersPubkey } = useSelector((state: State) => state.auth) const profiles = useSigitProfiles([ ...(submittedBy ? [submittedBy] : []), diff --git a/src/pages/verify/index.tsx b/src/pages/verify/index.tsx index bd35f14..d991666 100644 --- a/src/pages/verify/index.tsx +++ b/src/pages/verify/index.tsx @@ -54,19 +54,8 @@ export const VerifyPage = () => { */ const { uploadedZip, meta } = location.state || {} - const { - submittedBy, - zipUrl, - encryptionKey, - signers, - viewers, - fileHashes, - parsedSignatureEvents, - createdAt, - signedStatus, - completedAt, - signersStatus - } = useSigitMeta(meta) + const { submittedBy, zipUrl, encryptionKey, signers, viewers, fileHashes } = + useSigitMeta(meta) const profiles = useSigitProfiles([ ...(submittedBy ? [submittedBy] : []), @@ -470,19 +459,7 @@ export const VerifyPage = () => { } - right={ - - } + right={} /> )} From d41d577c29af2135e4352186af1b4b434d22cc95 Mon Sep 17 00:00:00 2001 From: Eugene Date: Wed, 14 Aug 2024 16:08:42 +0300 Subject: [PATCH 20/27] fix: styling --- .../DrawPDFFields/style.module.scss | 1 + src/components/FileList/index.tsx | 29 ++++++++++--------- src/components/FileList/style.module.scss | 28 ++++++++++++++++++ src/components/PDFView/PdfPageItem.tsx | 4 +-- src/components/PDFView/index.tsx | 6 ++-- src/components/PDFView/style.module.scss | 2 ++ 6 files changed, 50 insertions(+), 20 deletions(-) diff --git a/src/components/DrawPDFFields/style.module.scss b/src/components/DrawPDFFields/style.module.scss index f1993eb..1b13c31 100644 --- a/src/components/DrawPDFFields/style.module.scss +++ b/src/components/DrawPDFFields/style.module.scss @@ -50,6 +50,7 @@ .pdfImageWrapper { position: relative; user-select: none; + margin-bottom: 10px; &.drawing { cursor: crosshair; diff --git a/src/components/FileList/index.tsx b/src/components/FileList/index.tsx index ba69332..f1fdcd8 100644 --- a/src/components/FileList/index.tsx +++ b/src/components/FileList/index.tsx @@ -17,20 +17,21 @@ const FileList = ({ }: FileListProps) => { const isActive = (file: CurrentUserFile) => file.id === currentFile.id return ( -
-
-
    - {files.map((file: CurrentUserFile) => ( -
  • setCurrentFile(file)} - > - {file.id} - {file.filename} -
  • - ))} -
+
+
+
    + {files.map((file: CurrentUserFile) => ( +
  • setCurrentFile(file)} + > + {file.id} + {file.filename} +
  • + ))} +
+
diff --git a/src/components/FileList/style.module.scss b/src/components/FileList/style.module.scss index 4103897..b754bdb 100644 --- a/src/components/FileList/style.module.scss +++ b/src/components/FileList/style.module.scss @@ -7,6 +7,29 @@ grid-gap: 0px; } +.filesPageContainer { + width: 100%; + display: grid; + grid-template-columns: 0.75fr 1.5fr 0.75fr; + grid-gap: 30px; + flex-grow: 1; +} + +ul { + list-style-type: none; /* Removes bullet points */ + margin: 0; /* Removes default margin */ + padding: 0; /* Removes default padding */ +} + + +.wrap { + position: sticky; + top: 15px; + display: flex; + flex-direction: column; + grid-gap: 15px; +} + .files { display: flex; flex-direction: column; @@ -33,6 +56,10 @@ cursor: grab; } +.wrap { + margin-top: 5px; +} + .fileItem { transition: ease 0.2s; display: flex; @@ -49,6 +76,7 @@ font-size: 16px; font-weight: 500; + &.active { background: #4c82a3; color: white; diff --git a/src/components/PDFView/PdfPageItem.tsx b/src/components/PDFView/PdfPageItem.tsx index 01ab512..a670f2f 100644 --- a/src/components/PDFView/PdfPageItem.tsx +++ b/src/components/PDFView/PdfPageItem.tsx @@ -34,9 +34,7 @@ const PdfPageItem = ({
diff --git a/src/components/PDFView/index.tsx b/src/components/PDFView/index.tsx index 2936f59..c032a3c 100644 --- a/src/components/PDFView/index.tsx +++ b/src/components/PDFView/index.tsx @@ -42,9 +42,9 @@ const PdfView = ({ ) } const isNotLastPdfFile = (index: number, files: CurrentUserFile[]): boolean => - !(index !== files.length - 1) + index !== files.length - 1 return ( - + <> {files.map((currentUserFile, index, arr) => { const { hash, pdfFile, filename, id } = currentUserFile if (!hash) return @@ -65,7 +65,7 @@ const PdfView = ({
) })} - + ) } diff --git a/src/components/PDFView/style.module.scss b/src/components/PDFView/style.module.scss index 3ebbc85..5029747 100644 --- a/src/components/PDFView/style.module.scss +++ b/src/components/PDFView/style.module.scss @@ -19,6 +19,7 @@ display: flex; width: 100%; flex-direction: column; + } .pdfView { @@ -26,4 +27,5 @@ flex-direction: column; width: 100%; height: 100%; + gap: 10px; } From 2f29ea9f35ad1c3285a9c01e7e51dfc37942c02f Mon Sep 17 00:00:00 2001 From: Eugene Date: Wed, 14 Aug 2024 16:34:20 +0300 Subject: [PATCH 21/27] fix: styling --- src/components/DrawPDFFields/style.module.scss | 7 +++++++ src/components/FileList/style.module.scss | 6 ------ src/components/MarkFormField/style.module.scss | 1 + 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/components/DrawPDFFields/style.module.scss b/src/components/DrawPDFFields/style.module.scss index 1b13c31..8773d0d 100644 --- a/src/components/DrawPDFFields/style.module.scss +++ b/src/components/DrawPDFFields/style.module.scss @@ -51,6 +51,13 @@ position: relative; user-select: none; margin-bottom: 10px; + + > img { + display: block; + max-width: 100%; + max-height: 100%; + object-fit: contain; /* Ensure the image fits within the container */ + } &.drawing { cursor: crosshair; diff --git a/src/components/FileList/style.module.scss b/src/components/FileList/style.module.scss index b754bdb..40b83a3 100644 --- a/src/components/FileList/style.module.scss +++ b/src/components/FileList/style.module.scss @@ -23,8 +23,6 @@ ul { .wrap { - position: sticky; - top: 15px; display: flex; flex-direction: column; grid-gap: 15px; @@ -56,10 +54,6 @@ ul { cursor: grab; } -.wrap { - margin-top: 5px; -} - .fileItem { transition: ease 0.2s; display: flex; diff --git a/src/components/MarkFormField/style.module.scss b/src/components/MarkFormField/style.module.scss index f3fa5d5..b5c6bb9 100644 --- a/src/components/MarkFormField/style.module.scss +++ b/src/components/MarkFormField/style.module.scss @@ -7,6 +7,7 @@ right: 0; left: 0; align-items: center; + z-index: 1000; } .actions { From 2becab9f79e1cb3aaf91178d67c70f9e98c4f98b Mon Sep 17 00:00:00 2001 From: Eugene Date: Thu, 15 Aug 2024 12:23:35 +0300 Subject: [PATCH 22/27] feat(pdf-marking): integrates UserDetails --- src/components/PDFView/PdfMarking.tsx | 11 ++++++++--- src/pages/sign/index.tsx | 1 + 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/components/PDFView/PdfMarking.tsx b/src/components/PDFView/PdfMarking.tsx index 943b032..8d3a369 100644 --- a/src/components/PDFView/PdfMarking.tsx +++ b/src/components/PDFView/PdfMarking.tsx @@ -14,6 +14,8 @@ import styles from './style.module.scss' import { CurrentUserFile } from '../../types/file.ts' import FileList from '../FileList' import { StickySideColumns } from '../../layouts/StickySideColumns.tsx' +import { UsersDetails } from '../UsersDetails.tsx' +import { Meta } from '../../types' interface PdfMarkingProps { files: CurrentUserFile[] @@ -22,6 +24,7 @@ interface PdfMarkingProps { setCurrentUserMarks: (currentUserMarks: CurrentUserMark[]) => void setUpdatedMarks: (markToUpdate: Mark) => void handleDownload: () => void + meta: Meta | null } /** @@ -37,7 +40,8 @@ const PdfMarking = (props: PdfMarkingProps) => { setIsReadyToSign, setCurrentUserMarks, setUpdatedMarks, - handleDownload + handleDownload, + meta } = props const [selectedMark, setSelectedMark] = useState(null) const [selectedMarkValue, setSelectedMarkValue] = useState('') @@ -81,8 +85,8 @@ const PdfMarking = (props: PdfMarkingProps) => { } const handleSubmit = (event: React.FormEvent) => { - event.preventDefault(); - if (!selectedMarkValue || !selectedMark) return; + event.preventDefault() + if (!selectedMarkValue || !selectedMark) return const updatedMark: CurrentUserMark = getUpdatedMark( selectedMark, @@ -126,6 +130,7 @@ const PdfMarking = (props: PdfMarkingProps) => { )}
} + right={meta !== null && } >
{currentUserMarks?.length > 0 && ( diff --git a/src/pages/sign/index.tsx b/src/pages/sign/index.tsx index 72ee3f4..9f2ab7c 100644 --- a/src/pages/sign/index.tsx +++ b/src/pages/sign/index.tsx @@ -958,6 +958,7 @@ export const SignPage = () => { setCurrentUserMarks={setCurrentUserMarks} setUpdatedMarks={setUpdatedMarks} handleDownload={handleDownload} + meta={meta} /> ) } From b22f577cc2de21bb1f8370c84a1d263f09fd7eb6 Mon Sep 17 00:00:00 2001 From: Eugene Date: Thu, 15 Aug 2024 12:25:37 +0300 Subject: [PATCH 23/27] fix: marking --- src/components/PDFView/index.tsx | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/components/PDFView/index.tsx b/src/components/PDFView/index.tsx index 3ac05d0..d67d372 100644 --- a/src/components/PDFView/index.tsx +++ b/src/components/PDFView/index.tsx @@ -35,10 +35,10 @@ const PdfView = ({ }, [currentFile]) const filterByFile = ( currentUserMarks: CurrentUserMark[], - fileName: string + hash: string ): CurrentUserMark[] => { return currentUserMarks.filter( - (currentUserMark) => currentUserMark.mark.fileName === fileName + (currentUserMark) => currentUserMark.mark.pdfFileHash === hash ) } const isNotLastPdfFile = (index: number, files: CurrentUserFile[]): boolean => @@ -46,7 +46,7 @@ const PdfView = ({ return ( <> {files.map((currentUserFile, index, arr) => { - const { hash, pdfFile, filename, id } = currentUserFile + const { hash, pdfFile, id } = currentUserFile if (!hash) return return (
Date: Thu, 15 Aug 2024 15:35:37 +0300 Subject: [PATCH 24/27] feat(pdf-marking): adds file validity check --- src/components/FileList/index.tsx | 12 ++++++++++-- src/components/FileList/style.module.scss | 23 +++++++++++++++++++++++ src/pages/sign/index.tsx | 2 +- src/types/file.ts | 1 + src/utils/utils.ts | 7 +++++-- 5 files changed, 40 insertions(+), 5 deletions(-) diff --git a/src/components/FileList/index.tsx b/src/components/FileList/index.tsx index f1fdcd8..7cd30eb 100644 --- a/src/components/FileList/index.tsx +++ b/src/components/FileList/index.tsx @@ -1,6 +1,8 @@ import { CurrentUserFile } from '../../types/file.ts' import styles from './style.module.scss' import { Button } from '@mui/material' +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' +import { faCheck } from '@fortawesome/free-solid-svg-icons' interface FileListProps { files: CurrentUserFile[] @@ -26,8 +28,14 @@ const FileList = ({ className={`${styles.fileItem} ${isActive(file) && styles.active}`} onClick={() => setCurrentFile(file)} > - {file.id} - {file.filename} +
{file.id}
+
+
{file.filename}
+
+ +
+ {file.isHashValid && } +
))} diff --git a/src/components/FileList/style.module.scss b/src/components/FileList/style.module.scss index 40b83a3..6f7b64a 100644 --- a/src/components/FileList/style.module.scss +++ b/src/components/FileList/style.module.scss @@ -21,6 +21,12 @@ ul { padding: 0; /* Removes default padding */ } +li { + list-style-type: none; /* Removes the bullets */ + margin: 0; /* Removes any default margin */ + padding: 0; /* Removes any default padding */ +} + .wrap { display: flex; @@ -83,6 +89,12 @@ ul { color: white; } +.fileInfo { + flex-grow: 1; + font-size: 16px; + font-weight: 500; +} + .fileName { display: -webkit-box; -webkit-box-orient: vertical; @@ -97,4 +109,15 @@ ul { flex-direction: column; justify-content: center; align-items: center; + width: 10px; +} + +.fileVisual { + display: flex; + flex-shrink: 0; + flex-direction: column; + justify-content: center; + align-items: center; + height: 25px; + width: 25px; } \ No newline at end of file diff --git a/src/pages/sign/index.tsx b/src/pages/sign/index.tsx index 9f2ab7c..a762292 100644 --- a/src/pages/sign/index.tsx +++ b/src/pages/sign/index.tsx @@ -952,7 +952,7 @@ export const SignPage = () => { return ( { * including its name, hash, and content * @param files * @param fileHashes + * @param creatorFileHashes */ export const getCurrentUserFiles = ( files: { [filename: string]: PdfFile }, - fileHashes: { [key: string]: string | null } + fileHashes: { [key: string]: string | null }, + creatorFileHashes: { [key: string]: string } ): CurrentUserFile[] => { return Object.entries(files).map(([filename, pdfFile], index) => { return { pdfFile, filename, id: index + 1, - ...(!!fileHashes[filename] && { hash: fileHashes[filename]! }) + ...(!!fileHashes[filename] && { hash: fileHashes[filename]! }), + isHashValid: creatorFileHashes[filename] === fileHashes[filename] } }) } From 79f37a842f919f052b08ca2afe341a296e55a18c Mon Sep 17 00:00:00 2001 From: Eugene Date: Mon, 19 Aug 2024 11:07:19 +0300 Subject: [PATCH 25/27] fix: file path --- src/pages/verify/index.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/pages/verify/index.tsx b/src/pages/verify/index.tsx index 8987191..69f7f0b 100644 --- a/src/pages/verify/index.tsx +++ b/src/pages/verify/index.tsx @@ -312,7 +312,7 @@ export const VerifyPage = () => { for (const [fileName, pdf] of Object.entries(files)) { const pages = await addMarks(pdf.file, marksByPage) const blob = await convertToPdfBlob(pages) - zip.file(`/files/${fileName}`, blob) + zip.file(`files/${fileName}`, blob) } const arrayBuffer = await zip From 55bf90e93c05b06467bc70199ebc36de4d3950f9 Mon Sep 17 00:00:00 2001 From: Eugene Date: Tue, 20 Aug 2024 14:21:45 +0300 Subject: [PATCH 26/27] chore: linting --- src/components/DrawPDFFields/index.tsx | 73 ++++++++++++++++---------- src/components/MarkFormField/index.tsx | 12 +++-- 2 files changed, 53 insertions(+), 32 deletions(-) diff --git a/src/components/DrawPDFFields/index.tsx b/src/components/DrawPDFFields/index.tsx index e98187c..5318361 100644 --- a/src/components/DrawPDFFields/index.tsx +++ b/src/components/DrawPDFFields/index.tsx @@ -49,7 +49,7 @@ interface Props { } export const DrawPDFFields = (props: Props) => { - const { selectedFiles } = props + const { selectedFiles, onDrawFieldsChange, users } = props const [pdfFiles, setPdfFiles] = useState([]) const [parsingPdf, setParsingPdf] = useState(false) @@ -94,6 +94,15 @@ export const DrawPDFFields = (props: Props) => { }) useEffect(() => { + /** + * Reads the pdf binary files and converts it's pages to images + * creates the pdfFiles object and sets to a state + */ + const parsePdfPages = async () => { + const pdfFiles: PdfFile[] = await toPdfFiles(selectedFiles) + + setPdfFiles(pdfFiles) + } if (selectedFiles) { setParsingPdf(true) @@ -104,8 +113,8 @@ export const DrawPDFFields = (props: Props) => { }, [selectedFiles]) useEffect(() => { - if (pdfFiles) props.onDrawFieldsChange(pdfFiles) - }, [pdfFiles]) + if (pdfFiles) onDrawFieldsChange(pdfFiles) + }, [onDrawFieldsChange, pdfFiles]) /** * Drawing events @@ -132,12 +141,16 @@ export const DrawPDFFields = (props: Props) => { * @param event Mouse event * @param page PdfPage where press happened */ - const onMouseDown = (event: any, page: PdfPage) => { + const onMouseDown = ( + event: React.MouseEvent, + page: PdfPage + ) => { // Proceed only if left click if (event.button !== 0) return // Only allow drawing if mouse is not over other drawn element - const isOverPdfImageWrapper = event.target.tagName === 'IMG' + const target = event.target as HTMLElement + const isOverPdfImageWrapper = target.tagName === 'IMG' if (!selectedTool || !isOverPdfImageWrapper) { return @@ -185,7 +198,10 @@ export const DrawPDFFields = (props: Props) => { * @param event Mouse event * @param page PdfPage where moving is happening */ - const onMouseMove = (event: any, page: PdfPage) => { + const onMouseMove = ( + event: React.MouseEvent, + page: PdfPage + ) => { if (mouseState.clicked && selectedTool) { const lastElementIndex = page.drawnFields.length - 1 const lastDrawnField = page.drawnFields[lastElementIndex] @@ -216,7 +232,7 @@ export const DrawPDFFields = (props: Props) => { * @param event Mouse event * @param drawnField Which we are moving */ - const onDrawnFieldMouseDown = (event: any) => { + const onDrawnFieldMouseDown = (event: React.MouseEvent) => { event.stopPropagation() // Proceed only if left click @@ -239,11 +255,15 @@ export const DrawPDFFields = (props: Props) => { * @param event Mouse event * @param drawnField which we are moving */ - const onDranwFieldMouseMove = (event: any, drawnField: DrawnField) => { + const onDranwFieldMouseMove = ( + event: React.MouseEvent, + drawnField: DrawnField + ) => { + const target = event.target as HTMLElement | null if (mouseState.dragging) { const { mouseX, mouseY, rect } = getMouseCoordinates( event, - event.target.parentNode + target?.parentNode as HTMLElement ) const coordsOffset = mouseState.coordsInWrapper @@ -272,7 +292,7 @@ export const DrawPDFFields = (props: Props) => { * @param event Mouse event * @param drawnField which we are resizing */ - const onResizeHandleMouseDown = (event: any) => { + const onResizeHandleMouseDown = (event: React.MouseEvent) => { // Proceed only if left click if (event.button !== 0) return @@ -288,11 +308,15 @@ export const DrawPDFFields = (props: Props) => { * @param event Mouse event * @param drawnField which we are resizing */ - const onResizeHandleMouseMove = (event: any, drawnField: DrawnField) => { + const onResizeHandleMouseMove = ( + event: React.MouseEvent, + drawnField: DrawnField + ) => { + const target = event.target as HTMLElement | null if (mouseState.resizing) { const { mouseX, mouseY } = getMouseCoordinates( event, - event.target.parentNode.parentNode + target?.parentNode?.parentNode as HTMLElement ) const width = mouseX - drawnField.left @@ -313,7 +337,7 @@ export const DrawPDFFields = (props: Props) => { * @param drawnFileIndex drawn file index */ const onRemoveHandleMouseDown = ( - event: any, + event: React.MouseEvent, pdfFileIndex: number, pdfPageIndex: number, drawnFileIndex: number @@ -331,7 +355,9 @@ export const DrawPDFFields = (props: Props) => { * so select can work properly * @param event Mouse event */ - const onUserSelectHandleMouseDown = (event: any) => { + const onUserSelectHandleMouseDown = ( + event: React.MouseEvent + ) => { event.stopPropagation() } @@ -341,8 +367,11 @@ export const DrawPDFFields = (props: Props) => { * @param customTarget mouse coordinates relative to this element, if not provided * event.target will be used */ - const getMouseCoordinates = (event: any, customTarget?: any) => { - const target = customTarget ? customTarget : event.target + const getMouseCoordinates = ( + event: React.MouseEvent, + customTarget?: HTMLElement + ) => { + const target = (customTarget ? customTarget : event.target) as HTMLElement const rect = target.getBoundingClientRect() const mouseX = event.clientX - rect.left //x position within the element. const mouseY = event.clientY - rect.top //y position within the element. @@ -354,16 +383,6 @@ export const DrawPDFFields = (props: Props) => { } } - /** - * Reads the pdf binary files and converts it's pages to images - * creates the pdfFiles object and sets to a state - */ - const parsePdfPages = async () => { - const pdfFiles: PdfFile[] = await toPdfFiles(selectedFiles) - - setPdfFiles(pdfFiles) - } - /** * * @returns if expanded pdf accordion is present @@ -477,7 +496,7 @@ export const DrawPDFFields = (props: Props) => { labelId="counterparts" label="Counterparts" > - {props.users.map((user, index) => { + {users.map((user, index) => { let displayValue = truncate( hexToNpub(user.pubkey), { diff --git a/src/components/MarkFormField/index.tsx b/src/components/MarkFormField/index.tsx index 2fa2780..e1003a0 100644 --- a/src/components/MarkFormField/index.tsx +++ b/src/components/MarkFormField/index.tsx @@ -7,15 +7,17 @@ import { isCurrentUserMarksComplete, isCurrentValueLast } from '../../utils' -import { useState } from 'react' +import React, { useState } from 'react' interface MarkFormFieldProps { - handleSubmit: (event: any) => void - handleSelectedMarkValueChange: (event: any) => void - selectedMark: CurrentUserMark - selectedMarkValue: string currentUserMarks: CurrentUserMark[] handleCurrentUserMarkChange: (mark: CurrentUserMark) => void + handleSelectedMarkValueChange: ( + event: React.ChangeEvent + ) => void + handleSubmit: (event: React.FormEvent) => void + selectedMark: CurrentUserMark + selectedMarkValue: string } /** From 3a6c5ae8e39a65853424d7cd7a6dc18d7e5c7bab Mon Sep 17 00:00:00 2001 From: Eugene Date: Tue, 20 Aug 2024 14:27:35 +0300 Subject: [PATCH 27/27] chore: formatting --- src/types/mark.ts | 2 +- src/utils/pdf.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/types/mark.ts b/src/types/mark.ts index 1e6039b..efc1899 100644 --- a/src/types/mark.ts +++ b/src/types/mark.ts @@ -1,4 +1,4 @@ -import { MarkType } from "./drawing"; +import { MarkType } from './drawing' export interface CurrentUserMark { id: number diff --git a/src/utils/pdf.ts b/src/utils/pdf.ts index cef12c2..622a259 100644 --- a/src/utils/pdf.ts +++ b/src/utils/pdf.ts @@ -260,4 +260,4 @@ export { addMarks, convertToPdfBlob, groupMarksByPage -} \ No newline at end of file +}