Compare commits

..

No commits in common. "7dafcf65c9e9ebf28248ef6609711d0a6c31fecd" and "e280e873424d6e92839e64d274997e51c1c135ed" have entirely different histories.

31 changed files with 232 additions and 2443 deletions

578
package-lock.json generated
View File

@ -30,8 +30,6 @@
"lodash": "4.17.21",
"mui-file-input": "4.0.4",
"nostr-tools": "2.7.0",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^4.4.168",
"react": "^18.2.0",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
@ -46,7 +44,6 @@
"@types/crypto-js": "^4.2.2",
"@types/file-saver": "2.0.7",
"@types/lodash": "4.14.202",
"@types/pdfjs-dist": "^2.10.378",
"@types/react": "^18.2.56",
"@types/react-dom": "^18.2.19",
"@typescript-eslint/eslint-plugin": "^7.0.2",
@ -1261,46 +1258,6 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
"node_modules/@mapbox/node-pre-gyp": {
"version": "1.0.11",
"resolved": "https://registry.npmjs.org/@mapbox/node-pre-gyp/-/node-pre-gyp-1.0.11.tgz",
"integrity": "sha512-Yhlar6v9WQgUp/He7BdgzOz8lqMQ8sU+jkCq7Wx8Myc5YFJLbEe7lgui/V7G1qB1DJykHSGwreceSaD60Y0PUQ==",
"optional": true,
"dependencies": {
"detect-libc": "^2.0.0",
"https-proxy-agent": "^5.0.0",
"make-dir": "^3.1.0",
"node-fetch": "^2.6.7",
"nopt": "^5.0.0",
"npmlog": "^5.0.1",
"rimraf": "^3.0.2",
"semver": "^7.3.5",
"tar": "^6.1.11"
},
"bin": {
"node-pre-gyp": "bin/node-pre-gyp"
}
},
"node_modules/@mapbox/node-pre-gyp/node_modules/node-fetch": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
"integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
"optional": true,
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
},
"peerDependencies": {
"encoding": "^0.1.0"
},
"peerDependenciesMeta": {
"encoding": {
"optional": true
}
}
},
"node_modules/@mui/base": {
"version": "5.0.0-beta.37",
"resolved": "https://registry.npmjs.org/@mui/base/-/base-5.0.0-beta.37.tgz",
@ -1742,24 +1699,6 @@
}
}
},
"node_modules/@pdf-lib/standard-fonts": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@pdf-lib/standard-fonts/-/standard-fonts-1.0.0.tgz",
"integrity": "sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==",
"license": "MIT",
"dependencies": {
"pako": "^1.0.6"
}
},
"node_modules/@pdf-lib/upng": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/@pdf-lib/upng/-/upng-1.0.1.tgz",
"integrity": "sha512-dQK2FUMQtowVP00mtIksrlZhdFXQZPC+taih1q4CvPZ5vqdxR/LKBaFg0oAfzd1GlHZXXSPdQfzQnt+ViGvEIQ==",
"license": "MIT",
"dependencies": {
"pako": "^1.0.10"
}
},
"node_modules/@popperjs/core": {
"version": "2.11.8",
"resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz",
@ -2213,16 +2152,6 @@
"resolved": "https://registry.npmjs.org/@types/parse-json/-/parse-json-4.0.2.tgz",
"integrity": "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw=="
},
"node_modules/@types/pdfjs-dist": {
"version": "2.10.378",
"resolved": "https://registry.npmjs.org/@types/pdfjs-dist/-/pdfjs-dist-2.10.378.tgz",
"integrity": "sha512-TRdIPqdsvKmPla44kVy4jv5Nt5vjMfVjbIEke1CRULIrwKNRC4lIiZvNYDJvbUMNCFPNIUcOKhXTyMJrX18IMA==",
"deprecated": "This is a stub types definition. pdfjs-dist provides its own type definitions, so you do not need this installed.",
"dev": true,
"dependencies": {
"pdfjs-dist": "*"
}
},
"node_modules/@types/prop-types": {
"version": "15.7.11",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.11.tgz",
@ -2486,12 +2415,6 @@
"vite": "^4.2.0 || ^5.0.0"
}
},
"node_modules/abbrev": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz",
"integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==",
"optional": true
},
"node_modules/acorn": {
"version": "8.11.3",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.3.tgz",
@ -2522,18 +2445,6 @@
"node": ">=0.4.0"
}
},
"node_modules/agent-base": {
"version": "6.0.2",
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz",
"integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==",
"optional": true,
"dependencies": {
"debug": "4"
},
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/ajv": {
"version": "6.12.6",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
@ -2554,7 +2465,7 @@
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"devOptional": true,
"dev": true,
"engines": {
"node": ">=8"
}
@ -2583,40 +2494,6 @@
"node": ">= 8"
}
},
"node_modules/aproba": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/aproba/-/aproba-2.0.0.tgz",
"integrity": "sha512-lYe4Gx7QT+MKGbDsA+Z+he/Wtef0BiwDOlK/XkBrdfsh9J/jPPXbX0tE9x9cl27Tmu5gg3QUbUrQYa/y+KOHPQ==",
"optional": true
},
"node_modules/are-we-there-yet": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz",
"integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==",
"deprecated": "This package is no longer supported.",
"optional": true,
"dependencies": {
"delegates": "^1.0.0",
"readable-stream": "^3.6.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/are-we-there-yet/node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"optional": true,
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/arg": {
"version": "4.1.3",
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
@ -2671,7 +2548,7 @@
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
"integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==",
"devOptional": true
"dev": true
},
"node_modules/binary-extensions": {
"version": "2.2.0",
@ -2784,21 +2661,6 @@
}
]
},
"node_modules/canvas": {
"version": "2.11.2",
"resolved": "https://registry.npmjs.org/canvas/-/canvas-2.11.2.tgz",
"integrity": "sha512-ItanGBMrmRV7Py2Z+Xhs7cT+FNt5K0vPL4p9EZ/UX/Mu7hFbkxSjKF2KVtPwX7UYWp7dRKnrTvReflgrItJbdw==",
"hasInstallScript": true,
"optional": true,
"dependencies": {
"@mapbox/node-pre-gyp": "^1.0.0",
"nan": "^2.17.0",
"simple-get": "^3.0.3"
},
"engines": {
"node": ">=6"
}
},
"node_modules/chalk": {
"version": "2.4.2",
"resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz",
@ -2848,15 +2710,6 @@
"node": ">= 6"
}
},
"node_modules/chownr": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz",
"integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==",
"optional": true,
"engines": {
"node": ">=10"
}
},
"node_modules/clsx": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/clsx/-/clsx-2.1.0.tgz",
@ -2878,15 +2731,6 @@
"resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz",
"integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw=="
},
"node_modules/color-support": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz",
"integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==",
"optional": true,
"bin": {
"color-support": "bin.js"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
@ -2902,13 +2746,7 @@
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz",
"integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==",
"devOptional": true
},
"node_modules/console-control-strings": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz",
"integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==",
"optional": true
"dev": true
},
"node_modules/convert-source-map": {
"version": "2.0.0",
@ -3010,18 +2848,6 @@
}
}
},
"node_modules/decompress-response": {
"version": "4.2.1",
"resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-4.2.1.tgz",
"integrity": "sha512-jOSne2qbyE+/r8G1VU+G/82LBs2Fs4LAsTiLSHOCOMZQl2OKZ6i8i4IyHemTe+/yIXOtTcRQMzPcgyhoFlqPkw==",
"optional": true,
"dependencies": {
"mimic-response": "^2.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@ -3036,21 +2862,6 @@
"node": ">=0.4.0"
}
},
"node_modules/delegates": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz",
"integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==",
"optional": true
},
"node_modules/detect-libc": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.0.3.tgz",
"integrity": "sha512-bwy0MGW55bG41VqxxypOsdSdGqLwXPI/focwgTYCFMbdUiBAxLg9CFzG08sz2aqzknwiX7Hkl0bQENjg8iLByw==",
"optional": true,
"engines": {
"node": ">=8"
}
},
"node_modules/diff": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz",
@ -3117,12 +2928,6 @@
"integrity": "sha512-oCglfs8yYKs9RQjJFOHonSnhikPK3y+0SvSYc/YpYJV//6rqc0/hbwd0c7vgK4vrl6y2gJAwjkhkSGWK+z4KRA==",
"dev": true
},
"node_modules/emoji-regex": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
"integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
"optional": true
},
"node_modules/error-ex": {
"version": "1.3.2",
"resolved": "https://registry.npmjs.org/error-ex/-/error-ex-1.3.2.tgz",
@ -3732,41 +3537,11 @@
"node": ">=12.20.0"
}
},
"node_modules/fs-minipass": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz",
"integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==",
"optional": true,
"dependencies": {
"minipass": "^3.0.0"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/fs-minipass/node_modules/minipass": {
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
"optional": true,
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/fs-minipass/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"optional": true
},
"node_modules/fs.realpath": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz",
"integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==",
"devOptional": true
"dev": true
},
"node_modules/fsevents": {
"version": "2.3.3",
@ -3790,27 +3565,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/gauge": {
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz",
"integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==",
"deprecated": "This package is no longer supported.",
"optional": true,
"dependencies": {
"aproba": "^1.0.3 || ^2.0.0",
"color-support": "^1.1.2",
"console-control-strings": "^1.0.0",
"has-unicode": "^2.0.1",
"object-assign": "^4.1.1",
"signal-exit": "^3.0.0",
"string-width": "^4.2.3",
"strip-ansi": "^6.0.1",
"wide-align": "^1.1.2"
},
"engines": {
"node": ">=10"
}
},
"node_modules/gensync": {
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
@ -3824,7 +3578,7 @@
"version": "7.2.3",
"resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz",
"integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==",
"devOptional": true,
"dev": true,
"dependencies": {
"fs.realpath": "^1.0.0",
"inflight": "^1.0.4",
@ -3856,7 +3610,7 @@
"version": "1.1.11",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz",
"integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==",
"devOptional": true,
"dev": true,
"dependencies": {
"balanced-match": "^1.0.0",
"concat-map": "0.0.1"
@ -3866,7 +3620,7 @@
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz",
"integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==",
"devOptional": true,
"dev": true,
"dependencies": {
"brace-expansion": "^1.1.7"
},
@ -3923,12 +3677,6 @@
"node": ">=4"
}
},
"node_modules/has-unicode": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz",
"integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==",
"optional": true
},
"node_modules/hasown": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.1.tgz",
@ -3953,19 +3701,6 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="
},
"node_modules/https-proxy-agent": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz",
"integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==",
"optional": true,
"dependencies": {
"agent-base": "6",
"debug": "4"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/idb": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/idb/-/idb-8.0.0.tgz",
@ -4028,7 +3763,7 @@
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz",
"integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==",
"devOptional": true,
"dev": true,
"dependencies": {
"once": "^1.3.0",
"wrappy": "1"
@ -4076,15 +3811,6 @@
"node": ">=0.10.0"
}
},
"node_modules/is-fullwidth-code-point": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
"integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
"optional": true,
"engines": {
"node": ">=8"
}
},
"node_modules/is-glob": {
"version": "4.0.3",
"resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz",
@ -4295,30 +4021,6 @@
"yallist": "^3.0.2"
}
},
"node_modules/make-dir": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz",
"integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==",
"optional": true,
"dependencies": {
"semver": "^6.0.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/make-dir/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"optional": true,
"bin": {
"semver": "bin/semver.js"
}
},
"node_modules/make-error": {
"version": "1.3.6",
"resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz",
@ -4366,18 +4068,6 @@
"node": ">= 0.6"
}
},
"node_modules/mimic-response": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-2.1.0.tgz",
"integrity": "sha512-wXqjST+SLt7R009ySCglWBCFpjUygmCIfD790/kVbiGmUgfYGuB14PiTd5DwVxSV4NcYHjzMkoj5LjQZwTQLEA==",
"optional": true,
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/minimatch": {
"version": "9.0.3",
"resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.3.tgz",
@ -4393,58 +4083,6 @@
"url": "https://github.com/sponsors/isaacs"
}
},
"node_modules/minipass": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz",
"integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==",
"optional": true,
"engines": {
"node": ">=8"
}
},
"node_modules/minizlib": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz",
"integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==",
"optional": true,
"dependencies": {
"minipass": "^3.0.0",
"yallist": "^4.0.0"
},
"engines": {
"node": ">= 8"
}
},
"node_modules/minizlib/node_modules/minipass": {
"version": "3.3.6",
"resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz",
"integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==",
"optional": true,
"dependencies": {
"yallist": "^4.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/minizlib/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"optional": true
},
"node_modules/mkdirp": {
"version": "1.0.4",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz",
"integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==",
"optional": true,
"bin": {
"mkdirp": "bin/cmd.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/ms": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz",
@ -4471,12 +4109,6 @@
}
}
},
"node_modules/nan": {
"version": "2.20.0",
"resolved": "https://registry.npmjs.org/nan/-/nan-2.20.0.tgz",
"integrity": "sha512-bk3gXBZDGILuuo/6sKtr0DQmSThYHLtNCdSdXk9YkxD/jK6X2vmCyyXBBxyqZ4XcnzTyYEAThfX3DCEnLf6igw==",
"optional": true
},
"node_modules/nanoid": {
"version": "3.3.7",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz",
@ -4557,21 +4189,6 @@
"integrity": "sha512-y10wOWt8yZpqXmOgRo77WaHEmhYQYGNA6y421PKsKYWEK8aW+cqAphborZDhqfyKrbZEN92CN1X2KbafY2s7Yw==",
"dev": true
},
"node_modules/nopt": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz",
"integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==",
"optional": true,
"dependencies": {
"abbrev": "1"
},
"bin": {
"nopt": "bin/nopt.js"
},
"engines": {
"node": ">=6"
}
},
"node_modules/normalize-path": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz",
@ -4622,19 +4239,6 @@
"integrity": "sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==",
"optional": true
},
"node_modules/npmlog": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz",
"integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==",
"deprecated": "This package is no longer supported.",
"optional": true,
"dependencies": {
"are-we-there-yet": "^2.0.0",
"console-control-strings": "^1.1.0",
"gauge": "^3.0.0",
"set-blocking": "^2.0.0"
}
},
"node_modules/object-assign": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
@ -4647,7 +4251,7 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz",
"integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==",
"devOptional": true,
"dev": true,
"dependencies": {
"wrappy": "1"
}
@ -4745,7 +4349,7 @@
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz",
"integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==",
"devOptional": true,
"dev": true,
"engines": {
"node": ">=0.10.0"
}
@ -4772,39 +4376,6 @@
"node": ">=8"
}
},
"node_modules/path2d": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/path2d/-/path2d-0.2.0.tgz",
"integrity": "sha512-KdPAykQX6kmLSOO6Jpu2KNcCED7CKjmaBNGGNuctOsG0hgYO1OdYQaan6cYXJiG0WmXOwZZPILPBimu5QAIw3A==",
"optional": true,
"engines": {
"node": ">=6"
}
},
"node_modules/pdf-lib": {
"version": "1.17.1",
"resolved": "https://registry.npmjs.org/pdf-lib/-/pdf-lib-1.17.1.tgz",
"integrity": "sha512-V/mpyJAoTsN4cnP31vc0wfNA1+p20evqqnap0KLoRUN0Yk/p3wN52DOEsL4oBFcLdb76hlpKPtzJIgo67j/XLw==",
"license": "MIT",
"dependencies": {
"@pdf-lib/standard-fonts": "^1.0.0",
"@pdf-lib/upng": "^1.0.1",
"pako": "^1.0.11",
"tslib": "^1.11.1"
}
},
"node_modules/pdfjs-dist": {
"version": "4.4.168",
"resolved": "https://registry.npmjs.org/pdfjs-dist/-/pdfjs-dist-4.4.168.tgz",
"integrity": "sha512-MbkAjpwka/dMHaCfQ75RY1FXX3IewBVu6NGZOcxerRFlaBiIkZmUoR0jotX5VUzYZEXAGzSFtknWs5xRKliXPA==",
"engines": {
"node": ">=18"
},
"optionalDependencies": {
"canvas": "^2.11.2",
"path2d": "^0.2.0"
}
},
"node_modules/picocolors": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.0.0.tgz",
@ -5203,7 +4774,7 @@
"version": "3.0.2",
"resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz",
"integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==",
"devOptional": true,
"dev": true,
"dependencies": {
"glob": "^7.1.3"
},
@ -5306,7 +4877,7 @@
"version": "7.6.0",
"resolved": "https://registry.npmjs.org/semver/-/semver-7.6.0.tgz",
"integrity": "sha512-EnwXhrlwXMk9gKu5/flx5sv/an57AkRplG3hTK68W7FRDN+k+OWBj65M7719OkA82XLBxrcX0KSHj+X5COhOVg==",
"devOptional": true,
"dev": true,
"dependencies": {
"lru-cache": "^6.0.0"
},
@ -5321,7 +4892,7 @@
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz",
"integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==",
"devOptional": true,
"dev": true,
"dependencies": {
"yallist": "^4.0.0"
},
@ -5333,13 +4904,7 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"devOptional": true
},
"node_modules/set-blocking": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz",
"integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==",
"optional": true
"dev": true
},
"node_modules/setimmediate": {
"version": "1.0.5",
@ -5367,43 +4932,6 @@
"node": ">=8"
}
},
"node_modules/signal-exit": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz",
"integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==",
"optional": true
},
"node_modules/simple-concat": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz",
"integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/feross"
},
{
"type": "patreon",
"url": "https://www.patreon.com/feross"
},
{
"type": "consulting",
"url": "https://feross.org/support"
}
],
"optional": true
},
"node_modules/simple-get": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/simple-get/-/simple-get-3.1.1.tgz",
"integrity": "sha512-CQ5LTKGfCpvE1K0n2us+kuMPbk/q0EKl82s4aheV9oXjFEz6W/Y7oQFVJuU6QG77hRT4Ghb5RURteF5vnWjupA==",
"optional": true,
"dependencies": {
"decompress-response": "^4.2.0",
"once": "^1.3.1",
"simple-concat": "^1.0.0"
}
},
"node_modules/slash": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/slash/-/slash-3.0.0.tgz",
@ -5438,25 +4966,11 @@
"safe-buffer": "~5.1.0"
}
},
"node_modules/string-width": {
"version": "4.2.3",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
"integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
"optional": true,
"dependencies": {
"emoji-regex": "^8.0.0",
"is-fullwidth-code-point": "^3.0.0",
"strip-ansi": "^6.0.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
"integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
"devOptional": true,
"dev": true,
"dependencies": {
"ansi-regex": "^5.0.1"
},
@ -5503,29 +5017,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/tar": {
"version": "6.2.1",
"resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz",
"integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==",
"optional": true,
"dependencies": {
"chownr": "^2.0.0",
"fs-minipass": "^2.0.0",
"minipass": "^5.0.0",
"minizlib": "^2.1.1",
"mkdirp": "^1.0.3",
"yallist": "^4.0.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/tar/node_modules/yallist": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz",
"integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==",
"optional": true
},
"node_modules/text-table": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
@ -5552,12 +5043,6 @@
"node": ">=8.0"
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"optional": true
},
"node_modules/ts-api-utils": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-1.2.1.tgz",
@ -5649,12 +5134,6 @@
"resolved": "https://registry.npmjs.org/tseep/-/tseep-1.2.1.tgz",
"integrity": "sha512-VFnsNcPGC4qFJ1nxbIPSjTmtRZOhlqLmtwRqtLVos8mbRHki8HO9cy9Z1e89EiWyxFmq6LBviI9TQjijxw/mEw=="
},
"node_modules/tslib": {
"version": "1.14.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz",
"integrity": "sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==",
"license": "0BSD"
},
"node_modules/tstl": {
"version": "2.5.13",
"resolved": "https://registry.npmjs.org/tstl/-/tstl-2.5.13.tgz",
@ -5882,12 +5361,6 @@
"node": ">= 8"
}
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"optional": true
},
"node_modules/websocket": {
"version": "1.0.34",
"resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.34.tgz",
@ -5926,16 +5399,6 @@
"resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz",
"integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A=="
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"optional": true,
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@ -5951,20 +5414,11 @@
"node": ">= 8"
}
},
"node_modules/wide-align": {
"version": "1.1.5",
"resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz",
"integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==",
"optional": true,
"dependencies": {
"string-width": "^1.0.2 || 2 || 3 || 4"
}
},
"node_modules/wrappy": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz",
"integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==",
"devOptional": true
"dev": true
},
"node_modules/yaeti": {
"version": "0.0.6",

View File

@ -36,8 +36,6 @@
"lodash": "4.17.21",
"mui-file-input": "4.0.4",
"nostr-tools": "2.7.0",
"pdf-lib": "^1.17.1",
"pdfjs-dist": "^4.4.168",
"react": "^18.2.0",
"react-dnd": "16.0.1",
"react-dnd-html5-backend": "16.0.1",
@ -52,7 +50,6 @@
"@types/crypto-js": "^4.2.2",
"@types/file-saver": "2.0.7",
"@types/lodash": "4.14.202",
"@types/pdfjs-dist": "^2.10.378",
"@types/react": "^18.2.56",
"@types/react-dom": "^18.2.19",
"@typescript-eslint/eslint-plugin": "^7.0.2",

View File

@ -1,495 +0,0 @@
import { AccessTime, CalendarMonth, ExpandMore, Gesture, PictureAsPdf, Badge, Work, Close } from '@mui/icons-material'
import { Box, Typography, Accordion, AccordionDetails, AccordionSummary, CircularProgress, FormControl, InputLabel, MenuItem, Select } from '@mui/material'
import styles from './style.module.scss'
import { useEffect, useState } from 'react'
import * as PDFJS from "pdfjs-dist";
import { ProfileMetadata, User } from '../../types';
import { PdfFile, DrawTool, MouseState, PdfPage, DrawnField, MarkType } from '../../types/drawing';
import { truncate } from 'lodash';
import { hexToNpub } from '../../utils';
import { toPdfFiles } from '../../utils/pdf.ts'
PDFJS.GlobalWorkerOptions.workerSrc = 'node_modules/pdfjs-dist/build/pdf.worker.mjs';
interface Props {
selectedFiles: File[]
users: User[]
metadata: { [key: string]: ProfileMetadata }
onDrawFieldsChange: (pdfFiles: PdfFile[]) => void
}
export const DrawPDFFields = (props: Props) => {
const { selectedFiles } = props
const [pdfFiles, setPdfFiles] = useState<PdfFile[]>([])
const [parsingPdf, setParsingPdf] = useState<boolean>(false)
const [showDrawToolBox, setShowDrawToolBox] = useState<boolean>(false)
const [selectedTool, setSelectedTool] = useState<DrawTool | null>()
const [toolbox] = useState<DrawTool[]>([
{
identifier: MarkType.SIGNATURE,
icon: <Gesture/>,
label: 'Signature',
active: false
},
{
identifier: MarkType.FULLNAME,
icon: <Badge/>,
label: 'Full Name',
active: true
},
{
identifier: MarkType.JOBTITLE,
icon: <Work/>,
label: 'Job Title',
active: false
},
{
identifier: MarkType.DATE,
icon: <CalendarMonth/>,
label: 'Date',
active: false
},
{
identifier: MarkType.DATETIME,
icon: <AccessTime/>,
label: 'Datetime',
active: false
},
])
const [mouseState, setMouseState] = useState<MouseState>({
clicked: false
})
useEffect(() => {
if (selectedFiles) {
setParsingPdf(true)
parsePdfPages().finally(() => {
setParsingPdf(false)
})
}
}, [selectedFiles])
useEffect(() => {
if (pdfFiles) props.onDrawFieldsChange(pdfFiles)
}, [pdfFiles])
/**
* Drawing events
*/
useEffect(() => {
// window.addEventListener('mousedown', onMouseDown);
window.addEventListener('mouseup', onMouseUp);
return () => {
// window.removeEventListener('mousedown', onMouseDown);
window.removeEventListener('mouseup', onMouseUp);
}
}, [])
const refreshPdfFiles = () => {
setPdfFiles([...pdfFiles])
}
/**
* Fired only when left click and mouse over pdf page
* Creates new drawnElement and pushes in the array
* It is re rendered and visible right away
*
* @param event Mouse event
* @param page PdfPage where press happened
*/
const onMouseDown = (event: any, 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'
if (!selectedTool || !isOverPdfImageWrapper) {
return
}
const { mouseX, mouseY } = getMouseCoordinates(event)
const newField: DrawnField = {
left: mouseX,
top: mouseY,
width: 0,
height: 0,
counterpart: '',
type: selectedTool.identifier
}
page.drawnFields.push(newField)
setMouseState((prev) => {
return {
...prev,
clicked: true
}
})
}
/**
* Drawing is finished, resets all the variables used to draw
* @param event Mouse event
*/
const onMouseUp = () => {
setMouseState((prev) => {
return {
...prev,
clicked: false,
dragging: false,
resizing: false
}
})
}
/**
* After {@link onMouseDown} create an drawing element, this function gets called on every pixel moved
* which alters the newly created drawing element, resizing it while mouse move
* @param event Mouse event
* @param page PdfPage where moving is happening
*/
const onMouseMove = (event: any, page: PdfPage) => {
if (mouseState.clicked && selectedTool) {
const lastElementIndex = page.drawnFields.length -1
const lastDrawnField = page.drawnFields[lastElementIndex]
const { mouseX, mouseY } = getMouseCoordinates(event)
const width = mouseX - lastDrawnField.left
const height = mouseY - lastDrawnField.top
lastDrawnField.width = width
lastDrawnField.height = height
const currentDrawnFields = page.drawnFields
currentDrawnFields[lastElementIndex] = lastDrawnField
refreshPdfFiles()
}
}
/**
* Fired when event happens on the drawn element which will be moved
* mouse coordinates relative to drawn element will be stored
* so when we start moving, offset can be calculated
* mouseX - offsetX
* mouseY - offsetY
*
* @param event Mouse event
* @param drawnField Which we are moving
*/
const onDrawnFieldMouseDown = (event: any) => {
event.stopPropagation()
// Proceed only if left click
if (event.button !== 0) return
const drawingRectangleCoords = getMouseCoordinates(event)
setMouseState({
dragging: true,
clicked: false,
coordsInWrapper: {
mouseX: drawingRectangleCoords.mouseX,
mouseY: drawingRectangleCoords.mouseY
}
})
}
/**
* Moves the drawnElement by the mouse position (mouse can grab anywhere on the drawn element)
* @param event Mouse event
* @param drawnField which we are moving
*/
const onDranwFieldMouseMove = (event: any, drawnField: DrawnField) => {
if (mouseState.dragging) {
const { mouseX, mouseY, rect } = getMouseCoordinates(event, event.target.parentNode)
const coordsOffset = mouseState.coordsInWrapper
if (coordsOffset) {
let left = mouseX - coordsOffset.mouseX
let top = mouseY - coordsOffset.mouseY
const rightLimit = rect.width - drawnField.width - 3
const bottomLimit = rect.height - drawnField.height - 3
if (left < 0) left = 0
if (top < 0) top = 0
if (left > rightLimit) left = rightLimit
if (top > bottomLimit) top = bottomLimit
drawnField.left = left
drawnField.top = top
refreshPdfFiles()
}
}
}
/**
* Fired when clicked on the resize handle, sets the state for a resize action
* @param event Mouse event
* @param drawnField which we are resizing
*/
const onResizeHandleMouseDown = (event: any) => {
// Proceed only if left click
if (event.button !== 0) return
event.stopPropagation()
setMouseState({
resizing: true
})
}
/**
* Resizes the drawn element by the mouse position
* @param event Mouse event
* @param drawnField which we are resizing
*/
const onResizeHandleMouseMove = (event: any, drawnField: DrawnField) => {
if (mouseState.resizing) {
const { mouseX, mouseY } = getMouseCoordinates(event, event.target.parentNode.parentNode)
const width = mouseX - drawnField.left
const height = mouseY - drawnField.top
drawnField.width = width
drawnField.height = height
refreshPdfFiles()
}
}
/**
* Removes the drawn element using the indexes in the params
* @param event Mouse event
* @param pdfFileIndex pdf file index
* @param pdfPageIndex pdf page index
* @param drawnFileIndex drawn file index
*/
const onRemoveHandleMouseDown = (event: any, pdfFileIndex: number, pdfPageIndex: number, drawnFileIndex: number) => {
event.stopPropagation()
pdfFiles[pdfFileIndex].pages[pdfPageIndex].drawnFields.splice(drawnFileIndex, 1)
}
/**
* Used to stop mouse click propagating to the parent elements
* so select can work properly
* @param event Mouse event
*/
const onUserSelectHandleMouseDown = (event: any) => {
event.stopPropagation()
}
/**
* Gets the mouse coordinates relative to a element in the `event` param
* @param event MouseEvent
* @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 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.
return {
mouseX,
mouseY,
rect
}
}
/**
* 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
*/
const hasExpandedPdf = () => {
return !!pdfFiles.filter(pdfFile => !!pdfFile.expanded).length
}
const handleAccordionExpandChange = (expanded: boolean, pdfFile: PdfFile) => {
pdfFile.expanded = expanded
refreshPdfFiles()
setShowDrawToolBox(hasExpandedPdf())
}
/**
* Changes the drawing tool
* @param drawTool to draw with
*/
const handleToolSelect = (drawTool: DrawTool) => {
// If clicked on the same tool, unselect
if (drawTool.identifier === selectedTool?.identifier) {
setSelectedTool(null)
return
}
setSelectedTool(drawTool)
}
/**
* Renders the pdf pages and drawing elements
*/
const getPdfPages = (pdfFile: PdfFile, pdfFileIndex: number) => {
return (
<Box sx={{
width: '100%'
}}>
{pdfFile.pages.map((page, pdfPageIndex: number) => {
return (
<div
key={pdfPageIndex}
style={{
border: '1px solid #c4c4c4',
marginBottom: '10px'
}}
className={`${styles.pdfImageWrapper} ${selectedTool ? styles.drawing : ''}`}
onMouseMove={(event) => {onMouseMove(event, page)}}
onMouseDown={(event) => {onMouseDown(event, page)}}
>
<img draggable="false" style={{ width: '100%' }} src={page.image}/>
{page.drawnFields.map((drawnField, drawnFieldIndex: number) => {
return (
<div
key={drawnFieldIndex}
onMouseDown={onDrawnFieldMouseDown}
onMouseMove={(event) => { onDranwFieldMouseMove(event, drawnField)}}
className={styles.drawingRectangle}
style={{
left: `${drawnField.left}px`,
top: `${drawnField.top}px`,
width: `${drawnField.width}px`,
height: `${drawnField.height}px`,
pointerEvents: mouseState.clicked ? 'none' : 'all'
}}
>
<span
onMouseDown={onResizeHandleMouseDown}
onMouseMove={(event) => {onResizeHandleMouseMove(event, drawnField)}}
className={styles.resizeHandle}
></span>
<span
onMouseDown={(event) => {onRemoveHandleMouseDown(event, pdfFileIndex, pdfPageIndex, drawnFieldIndex)}}
className={styles.removeHandle}
>
<Close fontSize='small'/>
</span>
<div
onMouseDown={onUserSelectHandleMouseDown}
className={styles.userSelect}
>
<FormControl fullWidth size='small'>
<InputLabel id="counterparts">Counterpart</InputLabel>
<Select
value={drawnField.counterpart}
onChange={(event) => { drawnField.counterpart = event.target.value; refreshPdfFiles() }}
labelId="counterparts"
label="Counterparts"
>
{props.users.map((user, index) => {
let displayValue = truncate(hexToNpub(user.pubkey), {
length: 16
})
const metadata = props.metadata[user.pubkey]
if (metadata) {
displayValue = truncate(metadata.name || metadata.display_name || metadata.username, {
length: 16
})
}
return <MenuItem key={index} value={hexToNpub(user.pubkey)}>{displayValue}</MenuItem>
})}
</Select>
</FormControl>
</div>
</div>
)
})}
</div>
)
})}
</Box>
)
}
if (parsingPdf) {
return (
<Box sx={{ width: '100%', textAlign: 'center' }}>
<CircularProgress/>
</Box>
)
}
if (!pdfFiles.length) {
return ''
}
return (
<Box>
<Box sx={{ mt: 1 }}>
<Typography sx={{ mb: 1 }}>Draw fields on the PDFs:</Typography>
{pdfFiles.map((pdfFile, pdfFileIndex: number) => {
return (
<Accordion key={pdfFileIndex} expanded={pdfFile.expanded} onChange={(_event, expanded) => {handleAccordionExpandChange(expanded, pdfFile)}}>
<AccordionSummary
expandIcon={<ExpandMore />}
aria-controls={`panel${pdfFileIndex}-content`}
id={`panel${pdfFileIndex}header`}
>
<PictureAsPdf sx={{ mr: 1 }}/>
{pdfFile.file.name}
</AccordionSummary>
<AccordionDetails>
{getPdfPages(pdfFile, pdfFileIndex)}
</AccordionDetails>
</Accordion>
)
})}
</Box>
{showDrawToolBox && (
<Box className={styles.drawToolBoxContainer}>
<Box className={styles.drawToolBox}>
{toolbox.filter(drawTool => drawTool.active).map((drawTool: DrawTool, index: number) => {
return (
<Box
key={index}
onClick={() => {handleToolSelect(drawTool)}} className={`${styles.toolItem} ${selectedTool?.identifier === drawTool.identifier ? styles.selected : ''}`}>
{ drawTool.icon }
{ drawTool.label }
</Box>
)
})}
</Box>
</Box>
)}
</Box>
)
}

View File

@ -1,113 +0,0 @@
.pdfFieldItem {
background: white;
padding: 10px;
border-radius: 4px;
cursor: pointer;
}
.drawToolBoxContainer {
position: fixed;
bottom: 0;
left: 0;
right: 0;
display: flex;
justify-content: center;
z-index: 50;
.drawToolBox {
display: flex;
gap: 10px;
min-width: 100px;
background-color: white;
padding: 15px;
box-shadow: 0 0 10px 1px #0000003b;
border-radius: 4px;
.toolItem {
display: flex;
flex-direction: column;
align-items: center;
border: 1px solid rgba(0, 0, 0, 0.137);
padding: 5px;
cursor: pointer;
user-select: none;
&.selected {
border-color: #01aaad;
color: #01aaad;
}
&:not(.selected) {
&:hover {
border-color: #01aaad79;
}
}
}
}
}
.pdfImageWrapper {
position: relative;
user-select: none;
&.drawing {
cursor: crosshair;
}
}
.drawingRectangle {
position: absolute;
border: 1px solid #01aaad;
z-index: 50;
background-color: #01aaad4b;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
&.nonEditable {
cursor: default;
visibility: hidden;
}
.resizeHandle {
position: absolute;
right: -5px;
bottom: -5px;
width: 10px;
height: 10px;
background-color: #fff;
border: 1px solid rgb(160, 160, 160);
border-radius: 50%;
cursor: pointer;
}
.removeHandle {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
top: -30px;
width: 20px;
height: 20px;
background-color: #fff;
border: 1px solid rgb(160, 160, 160);
border-radius: 50%;
color: #E74C3C;
font-size: 10px;
cursor: pointer;
}
.userSelect {
position: absolute;
display: flex;
justify-content: center;
align-items: center;
bottom: -60px;
min-width: 170px;
min-height: 30px;
background: #fff;
padding: 5px 0;
}
}

View File

@ -1,35 +0,0 @@
import { PdfFile } from '../../types/drawing.ts'
import { CurrentUserMark } from '../../types/mark.ts'
import PdfPageItem from './PdfPageItem.tsx';
interface PdfItemProps {
pdfFile: PdfFile
currentUserMarks: CurrentUserMark[]
handleMarkClick: (id: number) => void
selectedMarkValue: string
selectedMark: CurrentUserMark | null
}
/**
* 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);
}
return (
pdfFile.pages.map((page, i) => {
return (
<PdfPageItem
page={page}
key={i}
currentUserMarks={filterByPage(currentUserMarks, i)}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
selectedMark={selectedMark}
/>
)
}))
}
export default PdfItem

View File

@ -1,37 +0,0 @@
import { CurrentUserMark } from '../../types/mark.ts'
import styles from '../DrawPDFFields/style.module.scss'
import { inPx } from '../../utils/pdf.ts'
interface PdfMarkItemProps {
userMark: CurrentUserMark
handleMarkClick: (id: number) => void
selectedMarkValue: string
selectedMark: CurrentUserMark | null
}
/**
* 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
)
return (
<div
onClick={handleClick}
className={styles.drawingRectangle}
style={{
left: inPx(location.left),
top: inPx(location.top),
width: inPx(location.width),
height: inPx(location.height)
}}
>{getMarkValue()}</div>
)
}
export default PdfMarkItem

View File

@ -1,100 +0,0 @@
import PdfView from './index.tsx'
import MarkFormField from '../../pages/sign/MarkFormField.tsx'
import { PdfFile } from '../../types/drawing.ts'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import React, { useState, useEffect } from 'react'
import {
findNextCurrentUserMark,
isCurrentUserMarksComplete,
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,
setUpdatedMarks: (markToUpdate: Mark) => void
}
/**
* Top-level component responsible for displaying Pdfs, Pages, and Marks,
* as well as tracking if the document is ready to be signed.
* @param props
* @constructor
*/
const PdfMarking = (props: PdfMarkingProps) => {
const {
files,
currentUserMarks,
setIsReadyToSign,
setCurrentUserMarks,
setUpdatedMarks
} = props
const [selectedMark, setSelectedMark] = useState<CurrentUserMark | null>(null)
const [selectedMarkValue, setSelectedMarkValue] = useState<string>("")
useEffect(() => {
setSelectedMark(findNextCurrentUserMark(currentUserMarks) || null)
}, [currentUserMarks])
const handleMarkClick = (id: number) => {
const nextMark = currentUserMarks.find((mark) => mark.mark.id === id);
setSelectedMark(nextMark!);
setSelectedMarkValue(nextMark?.mark.value ?? EMPTY);
}
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
if (!selectedMarkValue || !selectedMark) return;
const updatedMark: CurrentUserMark = {
...selectedMark,
mark: {
...selectedMark.mark,
value: selectedMarkValue
},
isCompleted: true
}
setSelectedMarkValue(EMPTY)
const updatedCurrentUserMarks = updateCurrentUserMarks(currentUserMarks, updatedMark);
setCurrentUserMarks(updatedCurrentUserMarks)
setSelectedMark(findNextCurrentUserMark(updatedCurrentUserMarks) || null)
console.log(isCurrentUserMarksComplete(updatedCurrentUserMarks))
setIsReadyToSign(isCurrentUserMarksComplete(updatedCurrentUserMarks))
setUpdatedMarks(updatedMark.mark)
}
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => setSelectedMarkValue(event.target.value)
return (
<>
<Container className={styles.container}>
{
currentUserMarks?.length > 0 && (
<PdfView
files={files}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
selectedMark={selectedMark}
currentUserMarks={currentUserMarks}
/>)}
{
selectedMark !== null && (
<MarkFormField
handleSubmit={handleSubmit}
handleChange={handleChange}
selectedMark={selectedMark}
selectedMarkValue={selectedMarkValue}
/>
)}
</Container>
</>
)
}
export default PdfMarking

View File

@ -1,46 +0,0 @@
import styles from '../DrawPDFFields/style.module.scss'
import { PdfPage } from '../../types/drawing.ts'
import { CurrentUserMark } from '../../types/mark.ts'
import PdfMarkItem from './PdfMarkItem.tsx'
interface PdfPageProps {
page: PdfPage
currentUserMarks: CurrentUserMark[]
handleMarkClick: (id: number) => void
selectedMarkValue: string
selectedMark: CurrentUserMark | null
}
/**
* Responsible for rendering a single Pdf Page and its Marks
*/
const PdfPageItem = ({ page, currentUserMarks, handleMarkClick, selectedMarkValue, selectedMark }: PdfPageProps) => {
return (
<div
className={styles.pdfImageWrapper}
style={{
border: '1px solid #c4c4c4',
marginBottom: '10px',
marginTop: '10px'
}}
>
<img
draggable="false"
src={page.image}
style={{ width: '100%'}}
/>
{
currentUserMarks.map((m, i) => (
<PdfMarkItem
key={i}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
userMark={m}
selectedMark={selectedMark}
/>
))}
</div>
)
}
export default PdfPageItem

View File

@ -1,42 +0,0 @@
import { PdfFile } from '../../types/drawing.ts'
import { Box } from '@mui/material'
import PdfItem from './PdfItem.tsx'
import { CurrentUserMark } from '../../types/mark.ts'
interface PdfViewProps {
files: { pdfFile: PdfFile, filename: string, hash: string | null }[]
currentUserMarks: CurrentUserMark[]
handleMarkClick: (id: number) => void
selectedMarkValue: string
selectedMark: CurrentUserMark | null
}
/**
* 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)
}
return (
<Box sx={{ width: '100%' }}>
{
files.map(({ pdfFile, hash }, i) => {
if (!hash) return
return (
<PdfItem
pdfFile={pdfFile}
key={i}
currentUserMarks={filterByFile(currentUserMarks, hash)}
selectedMark={selectedMark}
handleMarkClick={handleMarkClick}
selectedMarkValue={selectedMarkValue}
/>
)
})
}
</Box>
)
}
export default PdfView;

View File

@ -1,16 +0,0 @@
.imageWrapper {
display: flex;
justify-content: center;
align-items: center;
width: 100%; /* Adjust as needed */
height: 100%; /* Adjust as needed */
overflow: hidden; /* Ensure no overflow */
border: 1px solid #ccc; /* Optional: for visual debugging */
background-color: #e0f7fa; /* Optional: for visual debugging */
}
.image {
max-width: 100%;
max-height: 100%;
object-fit: contain; /* Ensure the image fits within the container */
}

View File

@ -59,11 +59,7 @@ import {
updateUsersAppData,
uploadToFileStorage
} from '../../utils'
import { Container } from '../../components/Container'
import styles from './style.module.scss'
import { PdfFile } from '../../types/drawing'
import { DrawPDFFields } from '../../components/DrawPDFFields'
import { Mark } from '../../types/mark.ts'
export const CreatePage = () => {
const navigate = useNavigate()
@ -88,46 +84,6 @@ export const CreatePage = () => {
const nostrController = NostrController.getInstance()
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
const [drawnPdfs, setDrawnPdfs] = useState<PdfFile[]>([])
useEffect(() => {
users.forEach((user) => {
if (!(user.pubkey in metadata)) {
const metadataController = new MetadataController()
const handleMetadataEvent = (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user.pubkey]: metadataContent
}))
}
metadataController.on(user.pubkey, (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(event)
}
})
metadataController
.findMetadata(user.pubkey)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(metadataEvent)
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
})
}
})
}, [])
// Set up event listener for authentication event
nostrController.on('nsecbunker-auth', (url) => {
setAuthUrl(url)
@ -341,31 +297,6 @@ export const CreatePage = () => {
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
}
})
})
})
.map((mark, index) => {
return {...mark, id: index }
});
}
// Handle errors during zip file generation
const handleZipError = (err: any) => {
console.log('Error in zip:>> ', err)
@ -378,13 +309,15 @@ export const CreatePage = () => {
const generateZipFile = async (zip: JSZip): Promise<ArrayBuffer | null> => {
setLoadingSpinnerDesc('Generating zip file')
return await zip
const arraybuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
})
.catch(handleZipError)
return arraybuffer
}
// Encrypt the zip file with the generated encryption key
@ -431,13 +364,15 @@ export const CreatePage = () => {
if (!arraybuffer) return null
return new File(
const finalZipFile = new File(
[new Blob([arraybuffer])],
`${unixNow}.sigit.zip`,
{
type: 'application/zip'
}
)
return finalZipFile
}
// Handle errors during file upload
@ -459,12 +394,14 @@ export const CreatePage = () => {
type: 'application/sigit'
})
return await uploadToFileStorage(file)
const fileUrl = await uploadToFileStorage(file)
.then((url) => {
toast.success('files.zip uploaded to file storage')
return url
})
.catch(handleUploadError)
return fileUrl
}
// Manage offline scenarios for signing or viewing the file
@ -488,13 +425,15 @@ export const CreatePage = () => {
zip.file(file.name, file)
})
return await zip
const arraybuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: { level: 6 }
})
.catch(handleZipError)
return arraybuffer
}
const generateCreateSignature = async (
@ -505,13 +444,11 @@ export const CreatePage = () => {
) => {
const signers = users.filter((user) => user.role === UserRole.signer)
const viewers = users.filter((user) => user.role === UserRole.viewer)
const markConfig = createMarks(fileHashes)
const content: CreateSignatureEventContent = {
signers: signers.map((signer) => hexToNpub(signer.pubkey)),
viewers: viewers.map((viewer) => hexToNpub(viewer.pubkey)),
fileHashes,
markConfig,
zipUrl,
title
}
@ -545,9 +482,11 @@ export const CreatePage = () => {
: viewers.map((viewer) => viewer.pubkey)
).filter((receiver) => receiver !== usersPubkey)
return receivers.map((receiver) =>
const promises = receivers.map((receiver) =>
sendNotification(receiver, meta)
)
return promises
}
const handleCreate = async () => {
@ -676,10 +615,6 @@ export const CreatePage = () => {
}
}
const onDrawFieldsChange = (pdfFiles: PdfFile[]) => {
setDrawnPdfs(pdfFiles)
}
if (authUrl) {
return (
<iframe
@ -694,7 +629,7 @@ export const CreatePage = () => {
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Container className={styles.container}>
<Box className={styles.container}>
<TextField
label="Title"
value={title}
@ -762,34 +697,23 @@ export const CreatePage = () => {
</Box>
</Box>
</Box>
<DisplayUser
metadata={metadata}
users={users}
handleUserRoleChange={handleUserRoleChange}
handleRemoveUser={handleRemoveUser}
moveSigner={moveSigner}
/>
<DrawPDFFields
metadata={metadata}
users={users}
selectedFiles={selectedFiles}
onDrawFieldsChange={onDrawFieldsChange}
/>
<Box sx={{ mt: 1, mb: 5, display: 'flex', justifyContent: 'center' }}>
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleCreate} variant="contained">
Create
</Button>
</Box>
</Container>
</Box>
</>
)
}
type DisplayUsersProps = {
metadata: { [key: string]: ProfileMetadata }
users: User[]
handleUserRoleChange: (role: UserRole, pubkey: string) => void
handleRemoveUser: (pubkey: string) => void
@ -797,12 +721,51 @@ type DisplayUsersProps = {
}
const DisplayUser = ({
metadata,
users,
handleUserRoleChange,
handleRemoveUser,
moveSigner
}: DisplayUsersProps) => {
const [metadata, setMetadata] = useState<{ [key: string]: ProfileMetadata }>(
{}
)
useEffect(() => {
users.forEach((user) => {
if (!(user.pubkey in metadata)) {
const metadataController = new MetadataController()
const handleMetadataEvent = (event: Event) => {
const metadataContent =
metadataController.extractProfileMetadataContent(event)
if (metadataContent)
setMetadata((prev) => ({
...prev,
[user.pubkey]: metadataContent
}))
}
metadataController.on(user.pubkey, (kind: number, event: Event) => {
if (kind === kinds.Metadata) {
handleMetadataEvent(event)
}
})
metadataController
.findMetadata(user.pubkey)
.then((metadataEvent) => {
if (metadataEvent) handleMetadataEvent(metadataEvent)
})
.catch((err) => {
console.error(
`error occurred in finding metadata for: ${user.pubkey}`,
err
)
})
}
})
}, [users])
return (
<TableContainer component={Paper} elevation={3} sx={{ marginTop: '20px' }}>
<Table>

View File

@ -6,8 +6,6 @@
color: $text-color;
margin-top: 10px;
gap: 10px;
width: 550px;
max-width: 550px;
.inputBlock {
display: flex;

View File

@ -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 (
<div className={styles.fixedBottomForm}>
<Box component="form" onSubmit={handleSubmit}>
<TextField
id="mark-value"
label={MARK_TYPE_TRANSLATION[selectedMark.mark.type.valueOf()]}
value={selectedMarkValue}
onChange={handleChange}
/>
<Button type="submit" variant="contained">
{getSubmitButton()}
</Button>
</Box>
</div>
)
}
export default MarkFormField;

View File

@ -16,13 +16,13 @@ import { State } from '../../store/rootReducer'
import { CreateSignatureEventContent, Meta, SignedEvent } from '../../types'
import {
decryptArrayBuffer,
encryptArrayBuffer, extractMarksFromSignedMeta,
encryptArrayBuffer,
extractZipUrlAndEncryptionKey,
generateEncryptionKey,
generateKeysFile, getFilesWithHashes,
generateKeysFile,
getHash,
hexToNpub,
isOnline, loadZip,
isOnline,
now,
npubToHex,
parseJson,
@ -31,19 +31,9 @@ import {
signEventForMetaFile,
updateUsersAppData
} from '../../utils'
import { Container } from '../../components/Container'
import { DisplayMeta } from './internal/displayMeta'
import styles from './style.module.scss'
import { PdfFile } from '../../types/drawing.ts'
import { convertToPdfFile } from '../../utils/pdf.ts'
import { CurrentUserMark, Mark } from '../../types/mark.ts'
import { getLastSignersSig } from '../../utils/sign.ts'
import {
filterMarksByPubkey,
getCurrentUserMarks,
isCurrentUserMarksComplete, updateMarks
} from '../../utils'
import PdfMarking from '../../components/PDFView/PdfMarking.tsx'
import { Container } from '../../components/Container'
enum SignedStatus {
Fully_Signed,
User_Is_Next_Signer,
@ -69,7 +59,7 @@ export const SignPage = () => {
const [selectedFile, setSelectedFile] = useState<File | null>(null)
const [files, setFiles] = useState<{ [filename: string]: PdfFile }>({})
const [files, setFiles] = useState<{ [filename: string]: ArrayBuffer }>({})
const [isLoading, setIsLoading] = useState(true)
const [loadingSpinnerDesc, setLoadingSpinnerDesc] = useState('')
@ -81,7 +71,6 @@ export const SignPage = () => {
const [signers, setSigners] = useState<`npub1${string}`[]>([])
const [viewers, setViewers] = useState<`npub1${string}`[]>([])
const [marks, setMarks] = useState<Mark[] >([])
const [creatorFileHashes, setCreatorFileHashes] = useState<{
[key: string]: string
}>({})
@ -100,8 +89,6 @@ export const SignPage = () => {
const [authUrl, setAuthUrl] = useState<string>()
const nostrController = NostrController.getInstance()
const [currentUserMarks, setCurrentUserMarks] = useState<CurrentUserMark[]>([]);
const [isReadyToSign, setIsReadyToSign] = useState(false);
useEffect(() => {
if (signers.length > 0) {
@ -192,16 +179,6 @@ export const SignPage = () => {
setViewers(createSignatureContent.viewers)
setCreatorFileHashes(createSignatureContent.fileHashes)
setSubmittedBy(createSignatureEvent.pubkey)
setMarks(createSignatureContent.markConfig);
if (usersPubkey) {
const metaMarks = filterMarksByPubkey(createSignatureContent.markConfig, usersPubkey!)
const signedMarks = extractMarksFromSignedMeta(meta)
const currentUserMarks = getCurrentUserMarks(metaMarks, signedMarks);
setCurrentUserMarks(currentUserMarks);
// setCurrentUserMark(findNextCurrentUserMark(currentUserMarks) || null)
setIsReadyToSign(isCurrentUserMarksComplete(currentUserMarks))
}
setSignedBy(Object.keys(meta.docSignatures) as `npub1${string}`[])
}
@ -212,7 +189,6 @@ export const SignPage = () => {
}, [meta])
useEffect(() => {
// online mode - from create and home page views
if (metaInNavState) {
const processSigit = async () => {
setIsLoading(true)
@ -287,13 +263,16 @@ export const SignPage = () => {
if (!decrypted) return
const zip = await loadZip(decrypted)
if (!zip) {
const zip = await JSZip.loadAsync(decrypted).catch((err) => {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
setIsLoading(false)
return
}
return null
})
const files: { [filename: string]: PdfFile } = {}
if (!zip) return
const files: { [filename: string]: ArrayBuffer } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files).map((entry) => entry.name)
@ -307,7 +286,7 @@ export const SignPage = () => {
)
if (arrayBuffer) {
files[fileName] = await convertToPdfFile(arrayBuffer, fileName);
files[fileName] = arrayBuffer
const hash = await getHash(arrayBuffer)
if (hash) {
@ -322,11 +301,6 @@ export const SignPage = () => {
setCurrentFileHashes(fileHashes)
}
const setUpdatedMarks = (markToUpdate: Mark) => {
const updatedMarks = updateMarks(marks, markToUpdate)
setMarks(updatedMarks)
}
const parseKeysJson = async (zip: JSZip) => {
const keysFileContent = await readContentOfZipEntry(
zip,
@ -336,19 +310,25 @@ export const SignPage = () => {
if (!keysFileContent) return null
return await parseJson<{ sender: string; keys: string[] }>(
const parsedJSON = await parseJson<{ sender: string; keys: string[] }>(
keysFileContent
).catch((err) => {
console.log(`Error parsing content of keys.json:`, err)
toast.error(err.message || `Error parsing content of keys.json`)
return null
})
return parsedJSON
}
const decrypt = async (file: File) => {
setLoadingSpinnerDesc('Decrypting file')
const zip = await loadZip(file);
const zip = await JSZip.loadAsync(file).catch((err) => {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
return null
})
if (!zip) return
const parsedKeysJson = await parseKeysJson(zip)
@ -419,27 +399,32 @@ export const SignPage = () => {
setLoadingSpinnerDesc('Parsing zip file')
const zip = await loadZip(decryptedZipFile)
const zip = await JSZip.loadAsync(decryptedZipFile).catch((err) => {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
return null
})
if (!zip) return
const files: { [filename: string]: PdfFile } = {}
const files: { [filename: string]: ArrayBuffer } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files)
.filter((entry) => entry.name.startsWith('files/') && !entry.dir)
.map((entry) => entry.name)
.map((entry) => entry.replace(/^files\//, ''))
// generate hashes for all entries in files folder of zipArchive
// these hashes can be used to verify the originality of files
for (const fileName of fileNames) {
for (let fileName of fileNames) {
const arrayBuffer = await readContentOfZipEntry(
zip,
fileName,
'arraybuffer'
)
fileName = fileName.replace(/^files\//, '')
if (arrayBuffer) {
files[fileName] = await convertToPdfFile(arrayBuffer, fileName);
files[fileName] = arrayBuffer
const hash = await getHash(arrayBuffer)
if (hash) {
@ -503,10 +488,7 @@ export const SignPage = () => {
const prevSig = getPrevSignersSig(hexToNpub(usersPubkey!))
if (!prevSig) return
const marks = getSignerMarksForMeta()
if (!marks) return
const signedEvent = await signEventForMeta({ prevSig, marks })
const signedEvent = await signEventForMeta(prevSig)
if (!signedEvent) return
const updatedMeta = updateMetaSignatures(meta, signedEvent)
@ -520,19 +502,14 @@ export const SignPage = () => {
}
// Sign the event for the meta file
const signEventForMeta = async (signerContent: { prevSig: string, marks: Mark[] }) => {
const signEventForMeta = async (prevSig: string) => {
return await signEventForMetaFile(
JSON.stringify(signerContent),
JSON.stringify({ prevSig }),
nostrController,
setIsLoading
)
}
const getSignerMarksForMeta = (): Mark[] | undefined => {
if (currentUserMarks.length === 0) return;
return currentUserMarks.map(( { mark }: CurrentUserMark) => mark);
}
// Update the meta signatures
const updateMetaSignatures = (meta: Meta, signedEvent: SignedEvent): Meta => {
const metaCopy = _.cloneDeep(meta)
@ -550,7 +527,7 @@ export const SignPage = () => {
encryptionKey: string
): Promise<File | null> => {
// Get the current timestamp in seconds
const unixNow = now()
const unixNow = Math.floor(Date.now() / 1000)
const blob = new Blob([encryptedArrayBuffer])
// Create a File object with the Blob data
const file = new File([blob], `compressed.sigit`, {
@ -600,13 +577,15 @@ export const SignPage = () => {
if (!arraybuffer) return null
return new File(
const finalZipFile = new File(
[new Blob([arraybuffer])],
`${unixNow}.sigit.zip`,
{
type: 'application/zip'
}
)
return finalZipFile
}
// Handle errors during zip file generation
@ -694,9 +673,7 @@ export const SignPage = () => {
setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event')
if (!meta) return;
const prevSig = getLastSignersSig(meta, signers)
const prevSig = getLastSignersSig()
if (!prevSig) return
const signedEvent = await signEventForMetaFile(
@ -746,7 +723,7 @@ export const SignPage = () => {
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])
const unixNow = now()
const unixNow = Math.floor(Date.now() / 1000)
saveAs(blob, `exported-${unixNow}.sigit.zip`)
setIsLoading(false)
@ -792,7 +769,7 @@ export const SignPage = () => {
const finalZipFile = await createFinalZipFile(encryptedArrayBuffer, key)
if (!finalZipFile) return
const unixNow = now()
const unixNow = Math.floor(Date.now() / 1000)
saveAs(finalZipFile, `exported-${unixNow}.sigit.zip`)
}
@ -829,6 +806,37 @@ export const SignPage = () => {
}
}
/**
* This function returns the signature of last signer
* It will be used in the content of export signature's signedEvent
*/
const getLastSignersSig = () => {
if (!meta) return null
// if there're no signers then use creator's signature
if (signers.length === 0) {
try {
const createSignatureEvent: Event = JSON.parse(meta.createSignature)
return createSignatureEvent.sig
} catch (error) {
return null
}
}
// get last signer
const lastSigner = signers[signers.length - 1]
// get the signature of last signer
try {
const lastSignatureEvent: Event = JSON.parse(
meta.docSignatures[lastSigner]
)
return lastSignatureEvent.sig
} catch (error) {
return null
}
}
if (authUrl) {
return (
<iframe
@ -840,13 +848,9 @@ export const SignPage = () => {
)
}
if (isLoading) {
return <LoadingSpinner desc={loadingSpinnerDesc} />
}
if (isReadyToSign) {
return (
<>
{isLoading && <LoadingSpinner desc={loadingSpinnerDesc} />}
<Container className={styles.container}>
{displayInput && (
<>
@ -916,13 +920,4 @@ export const SignPage = () => {
</Container>
</>
)
}
return <PdfMarking
files={getFilesWithHashes(files, currentFileHashes)}
currentUserMarks={currentUserMarks}
setIsReadyToSign={setIsReadyToSign}
setCurrentUserMarks={setCurrentUserMarks}
setUpdatedMarks={setUpdatedMarks}
/>
}

View File

@ -34,11 +34,10 @@ import { UserAvatar } from '../../../components/UserAvatar'
import { MetadataController } from '../../../controllers'
import { npubToHex, shorten, hexToNpub, parseJson } from '../../../utils'
import styles from '../style.module.scss'
import { PdfFile } from '../../../types/drawing.ts'
type DisplayMetaProps = {
meta: Meta
files: { [filename: string]: PdfFile }
files: { [filename: string]: ArrayBuffer }
submittedBy: string
signers: `npub1${string}`[]
viewers: `npub1${string}`[]
@ -144,7 +143,7 @@ export const DisplayMeta = ({
}, [users, submittedBy])
const downloadFile = async (filename: string) => {
const arrayBuffer = await files[filename].file.arrayBuffer()
const arrayBuffer = files[filename]
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])

View File

@ -2,8 +2,6 @@
.container {
color: $text-color;
width: 550px;
max-width: 550px;
.inputBlock {
position: relative;
@ -49,40 +47,4 @@
@extend .user;
}
}
.fixedBottomForm {
position: fixed;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 100%;
max-width: 500px;
height: 100px;
border-top: 1px solid #ccc;
box-shadow: 0 -2px 5px rgba(0, 0, 0, 0.1);
padding: 10px 20px;
display: flex;
justify-content: center;
align-items: center;
//z-index: 200;
}
.fixedBottomForm input[type="text"] {
width: 80%;
padding: 10px;
font-size: 16px;
border: 1px solid #ccc;
border-radius: 4px;
}
.fixedBottomForm button {
background-color: #3f3d56;
color: white;
border: none;
padding: 10px 20px;
font-size: 16px;
margin-left: 10px;
border-radius: 4px;
cursor: pointer;
}
}

View File

@ -15,7 +15,7 @@ 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 { MetadataController } from '../../controllers'
import {
CreateSignatureEventContent,
Meta,
@ -23,30 +23,19 @@ import {
SignedEventContent
} from '../../types'
import {
decryptArrayBuffer, extractMarksFromSignedMeta,
decryptArrayBuffer,
extractZipUrlAndEncryptionKey,
getHash,
hexToNpub, now,
hexToNpub,
npubToHex,
parseJson,
readContentOfZipEntry,
shorten, signEventForMetaFile
shorten
} from '../../utils'
import styles from './style.module.scss'
import { Cancel, CheckCircle } from '@mui/icons-material'
import { useLocation } from 'react-router-dom'
import axios from 'axios'
import { PdfFile } from '../../types/drawing.ts'
import {
addMarks,
convertToPdfBlob,
convertToPdfFile,
groupMarksByPage,
} from '../../utils/pdf.ts'
import { State } from '../../store/rootReducer.ts'
import { useSelector } from 'react-redux'
import { getLastSignersSig } from '../../utils/sign.ts'
import { saveAs } from 'file-saver'
import { Container } from '../../components/Container'
export const VerifyPage = () => {
@ -78,13 +67,10 @@ export const VerifyPage = () => {
const [currentFileHashes, setCurrentFileHashes] = useState<{
[key: string]: string | null
}>({})
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) {
@ -139,7 +125,6 @@ export const VerifyPage = () => {
if (!zip) return
const files: { [filename: string]: PdfFile } = {}
const fileHashes: { [key: string]: string | null } = {}
const fileNames = Object.values(zip.files).map(
(entry) => entry.name
@ -155,7 +140,6 @@ export const VerifyPage = () => {
)
if (arrayBuffer) {
files[fileName] = await convertToPdfFile(arrayBuffer, fileName!)
const hash = await getHash(arrayBuffer)
if (hash) {
@ -167,8 +151,6 @@ export const VerifyPage = () => {
}
setCurrentFileHashes(fileHashes)
setFiles(files)
setSigners(createSignatureContent.signers)
setViewers(createSignatureContent.viewers)
@ -177,8 +159,6 @@ export const VerifyPage = () => {
setMeta(metaInNavState)
setIsLoading(false)
}
})
.catch((err) => {
@ -380,73 +360,6 @@ export const VerifyPage = () => {
}
}
const handleExport = async () => {
if (Object.entries(files).length === 0 ||!meta ||!usersPubkey) return;
const usersNpub = hexToNpub(usersPubkey)
if (
!signers.includes(usersNpub) &&
!viewers.includes(usersNpub) &&
submittedBy !== usersNpub
) {
return
}
setIsLoading(true)
setLoadingSpinnerDesc('Signing nostr event')
if (!meta) return;
const prevSig = getLastSignersSig(meta, signers)
if (!prevSig) return;
const signedEvent = await signEventForMetaFile(
JSON.stringify({ prevSig }),
nostrController,
setIsLoading
)
if (!signedEvent) return;
const exportSignature = JSON.stringify(signedEvent, null, 2)
const updatedMeta = {...meta, exportSignature }
const stringifiedMeta = JSON.stringify(updatedMeta, null, 2)
const zip = new JSZip()
zip.file('meta.json', stringifiedMeta)
const marks = extractMarksFromSignedMeta(updatedMeta)
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)
}
const arrayBuffer = await zip
.generateAsync({
type: 'arraybuffer',
compression: 'DEFLATE',
compressionOptions: {
level: 6
}
})
.catch((err) => {
console.log('err in zip:>> ', err)
setIsLoading(false)
toast.error(err.message || 'Error occurred in generating zip file')
return null
})
if (!arrayBuffer) return
const blob = new Blob([arrayBuffer])
saveAs(blob, `exported-${now()}.sigit.zip`)
setIsLoading(false)
}
const displayUser = (pubkey: string, verifySignature = false) => {
const profile = metadata[pubkey]
@ -609,11 +522,6 @@ export const VerifyPage = () => {
Exported By
</Typography>
{displayExportedBy()}
<Box sx={{ mt: 1, display: 'flex', justifyContent: 'center' }}>
<Button onClick={handleExport} variant="contained">
Export Sigit
</Button>
</Box>
</ListItem>
{signers.length > 0 && (

View File

@ -1,4 +1,3 @@
import { Mark } from './mark'
import { Keys } from '../store/auth/types'
export enum UserRole {
@ -23,14 +22,12 @@ export interface CreateSignatureEventContent {
signers: `npub1${string}`[]
viewers: `npub1${string}`[]
fileHashes: { [key: string]: string }
markConfig: Mark[]
title: string
zipUrl: string
}
export interface SignedEventContent {
prevSig: string
marks: Mark[]
}
export interface Sigit {

View File

@ -1,49 +0,0 @@
export interface MouseState {
clicked?: boolean
dragging?: boolean
resizing?: boolean
coordsInWrapper?: {
mouseX: number
mouseY: number
}
}
export interface PdfFile {
file: File,
pages: PdfPage[]
expanded?: boolean
}
export interface PdfPage {
image: string
drawnFields: DrawnField[]
}
export interface DrawnField {
left: number
top: number
width: number
height: number
type: MarkType
/**
* npub of a counter part
*/
counterpart: string
}
export interface DrawTool {
identifier: MarkType
label: string
icon: JSX.Element,
defaultValue?: string
selected?: boolean
active?: boolean
}
export enum MarkType {
SIGNATURE = 'SIGNATURE',
JOBTITLE = 'JOBTITLE',
FULLNAME = 'FULLNAME',
DATE = 'DATE',
DATETIME = 'DATETIME'
}

View File

@ -1,77 +0,0 @@
import { MarkType } from "./drawing";
export interface CurrentUserMark {
mark: Mark
isLast: boolean
isCompleted: boolean
}
export interface Mark {
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;
}
// Creator Meta Object Example
const creatorMetaExample = {
"fileHashes": {
// PDF Hash
"Lorem ipsum dolor sit amet.pdf": "da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05",
// PDF Pages (in png format) hashes
// Page 1
"da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/1.png": "hash123png1",
// Page 2
"da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/2.png": "hash321png2"
},
"markConfig": {
// Signer npub
'npub1x77qywdllzetv9ncnhlfpv62kshlgtt0uqlsq3v22uzzkk2xvvrsn6uyfy': {
// PDF Page 1 (PNG file hash)
'da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/1.png': [
{
markType: "FULLNAME",
markLocation: "X:56;Y:306"
}
],
// PDF Page 2 (PNG file hash)
'da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/2.png': [
{
markType: "FULLNAME",
markLocation: "X:76;Y:283.71875"
}
]
}
}
}
// Signer meta example
const signerExample = {
"prevSig": "10de030dd2bfafbbd34969645bd0b3f5e8ab71b3b32091fb29bbea5e272f8a3b7284ef667b6a02e9becc1036450d9fbe5c1c6d146fa91d70e0d8f3cd54d64f17",
"marks": {
// PDF Page 1 (PNG file hash)
'da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/1.png': {
// Mark coordinates
"X:56;Y:306": {
value: 'Pera Peric'
}
},
// PDF Page 2 (PNG file hash)
'da5f857e77d3aa59c461efad804116931c059b36e6b4da0b5d9452753ec70c05/2.png': {
// Mark coordinates
"X:76;Y:283.71875": {
value: 'Pera Peric'
}
}
}
}

View File

@ -1,7 +1,6 @@
export interface ProfileMetadata {
name?: string
display_name?: string
username?: string
picture?: string
banner?: string
about?: string

View File

@ -1,4 +1,4 @@
export interface OutputByType {
export interface OutputByType {
base64: string
string: string
text: string
@ -10,17 +10,4 @@
nodebuffer: Buffer
}
interface InputByType {
base64: string;
string: string;
text: string;
binarystring: string;
array: number[];
uint8array: Uint8Array;
arraybuffer: ArrayBuffer;
blob: Blob;
stream: NodeJS.ReadableStream;
}
export type OutputType = keyof OutputByType
export type InputFileFormat = InputByType[keyof InputByType] | Promise<InputByType[keyof InputByType]>;

View File

@ -1,6 +0,0 @@
import { MarkType } from '../types/drawing.ts'
export const EMPTY: string = ''
export const MARK_TYPE_TRANSLATION: { [key: string]: string } = {
[MarkType.FULLNAME.valueOf()]: 'Full Name'
}

View File

@ -6,4 +6,3 @@ export * from './nostr'
export * from './string'
export * from './zip'
export * from './utils'
export * from './mark'

View File

@ -1,98 +0,0 @@
import { CurrentUserMark, Mark } from '../types/mark.ts'
import { hexToNpub } from './nostr.ts'
import { Meta, SignedEventContent } from '../types'
import { Event } from 'nostr-tools'
/**
* Takes in an array of Marks already filtered by User.
* Returns an array of CurrentUserMarks with correct values mix-and-matched.
* @param marks - default Marks extracted from Meta
* @param signedMetaMarks - signed user Marks extracted from DocSignatures
*/
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
}
return {
mark,
isLast: isLast(index, arr),
isCompleted: !!mark.value
}
})
}
/**
* Returns next incomplete CurrentUserMark if there is one
* @param usersMarks
*/
const findNextCurrentUserMark = (usersMarks: CurrentUserMark[]): CurrentUserMark | undefined => {
return usersMarks.find((mark) => !mark.isCompleted);
}
/**
* Returns Marks that are assigned to a specific user
* @param marks
* @param pubkey
*/
const filterMarksByPubkey = (marks: Mark[], pubkey: string): Mark[] => {
return marks.filter(mark => mark.npub === hexToNpub(pubkey))
}
/**
* Takes Signed Doc Signatures part of Meta and extracts
* all Marks into one flar array, regardless of the user.
* @param meta
*/
const extractMarksFromSignedMeta = (meta: Meta): Mark[] => {
return Object.values(meta.docSignatures)
.map((val: string) => JSON.parse(val as string))
.map((val: Event) => JSON.parse(val.content))
.flatMap((val: SignedEventContent) => val.marks)
}
/**
* Checks the CurrentUserMarks array that every element in that array has been
* marked as complete.
* @param currentUserMarks
*/
const isCurrentUserMarksComplete = (currentUserMarks: CurrentUserMark[]): boolean => {
return currentUserMarks.every((mark) => mark.isCompleted)
}
/**
* Inserts an updated mark into an existing array of marks. Returns a copy of the
* existing array with a new value inserted
* @param marks
* @param markToUpdate
*/
const updateMarks = (marks: Mark[], markToUpdate: Mark): Mark[] => {
const indexToUpdate = marks.findIndex(mark => mark.id === markToUpdate.id);
return [
...marks.slice(0, indexToUpdate),
markToUpdate,
...marks.slice(indexToUpdate + 1)
]
}
const updateCurrentUserMarks = (currentUserMarks: CurrentUserMark[], markToUpdate: CurrentUserMark): CurrentUserMark[] => {
const indexToUpdate = currentUserMarks.findIndex((m) => m.mark.id === markToUpdate.mark.id)
return [
...currentUserMarks.slice(0, indexToUpdate),
markToUpdate,
...currentUserMarks.slice(indexToUpdate + 1)
]
}
const isLast = <T>(index: number, arr: T[]) => (index === (arr.length -1))
export {
getCurrentUserMarks,
filterMarksByPubkey,
extractMarksFromSignedMeta,
isCurrentUserMarksComplete,
findNextCurrentUserMark,
updateMarks,
updateCurrentUserMarks,
}

View File

@ -83,12 +83,14 @@ export const signEventForMetaFile = async (
}
// Sign the event
return await nostrController.signEvent(event).catch((err) => {
const signedEvent = await nostrController.signEvent(event).catch((err) => {
console.error(err)
toast.error(err.message || 'Error occurred in signing nostr event')
setIsLoading(false) // Set loading state to false
return null
})
return signedEvent // Return the signed event
}
/**

View File

@ -120,7 +120,7 @@ export const queryNip05 = async (
if (!match) throw new Error('Invalid nip05')
// Destructure the match result, assigning default value '_' to name if not provided
const [name = '_', domain] = match
const [_, name = '_', domain] = match
// Construct the URL to query the NIP-05 data
const url = `https://${domain}/.well-known/nostr.json?name=${name}`

View File

@ -1,256 +0,0 @@
import { PdfFile, PdfPage } from '../types/drawing.ts'
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';
/**
* Scale between the PDF page's natural size and rendered size
* @constant {number}
*/
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
* because it is dynamically rendered, and the final size.
* This should be fixed going forward.
* Switching to PDF-Lib will most likely make this problem redundant.
*/
const FONT_SIZE: number = 40;
/**
* Current font type used when generating a PDF.
*/
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" });
}
/**
* Converts a generic PDF File to Sigit's internal Pdf File type
* @param {File} file
* @return {PdfFile} Sigit's internal PDF File type
*/
const toPdfFile = async (file: File): Promise<PdfFile> => {
const data = await readPdf(file)
const pages = await pdfToImages(data)
return { file, pages, expanded: false }
}
/**
* Transforms an array of generic PDF Files into an array of Sigit's
* internal representation of Pdf Files
* @param selectedFiles - an array of generic PDF Files
* @return PdfFile[] - an array of Sigit's internal Pdf File type
*/
const toPdfFiles = async (selectedFiles: File[]): Promise<PdfFile[]> => {
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`;
/**
* A utility that checks if a given file is of the pdf type
* @param file
*/
const isPdf = (file: File) => file.type.toLowerCase().includes('pdf');
/**
* Reads the pdf file binaries
*/
const readPdf = (file: File): Promise<string> => {
return new Promise((resolve, reject) => {
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);
})
}
/**
* Converts pdf to the images
* @param data pdf file bytes
*/
const pdfToImages = async (data: any): Promise<PdfPage[]> => {
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());
}
return Promise.resolve(images.map((image) => {
return {
image,
drawnFields: []
}
}))
}
/**
* Takes in individual pdf file and an object with Marks grouped by Page number
* 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 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;
marksPerPage[i].forEach(mark => draw(mark, context!))
images.push(canvas.toDataURL());
}
return Promise.resolve(images);
}
/**
* Utility to scale mark in line with the PDF-to-PNG scale
*/
const scaleMark = (mark: Mark): Mark => {
const { location } = mark;
return {
...mark,
location: {
...location,
width: location.width * SCALE,
height: location.height * SCALE,
left: location.left * SCALE,
top: location.top * SCALE
}
}
}
/**
* Utility to check if a Mark has value
* @param mark
*/
const hasValue = (mark: Mark): boolean => !!mark.value;
/**
* Draws a Mark on a Canvas representation of a PDF Page
* @param mark to be drawn
* @param ctx a Canvas representation of a specific PDF Page
*/
const draw = (mark: Mark, ctx: CanvasRenderingContext2D) => {
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);
}
/**
* Takes an array of encoded PDF pages and returns a blob that is a complete PDF file
* @param markedPdfPages
*/
const convertToPdfBlob = async (markedPdfPages: string[]): Promise<Blob> => {
const pdfDoc = await PDFDocument.create();
for (const page of markedPdfPages) {
const pngImage = await pdfDoc.embedPng(page)
const p = pdfDoc.addPage([pngImage.width, pngImage.height])
p.drawImage(pngImage, {
x: 0,
y: 0,
width: pngImage.width,
height: pngImage.height
})
}
const pdfBytes = await pdfDoc.save()
return new Blob([pdfBytes], { type: 'application/pdf' })
}
/**
* Takes an ArrayBuffer of a PDF file and converts to Sigit's Internal Pdf File type
* @param arrayBuffer
* @param fileName
*/
const convertToPdfFile = async (arrayBuffer: ArrayBuffer, fileName: string): Promise<PdfFile> => {
const file = toFile(arrayBuffer, fileName);
return toPdfFile(file);
}
/**
* @param marks - an array of Marks
* @function hasValue removes any Mark without a property
* @function scaleMark scales remaining marks in line with SCALE
* @function byPage groups remaining Marks by their page marks.location.page
*/
const groupMarksByPage = (marks: Mark[]) => {
return marks
.filter(hasValue)
.map(scaleMark)
.reduce<{[key: number]: Mark[]}>(byPage, {})
}
/**
* A reducer callback that transforms an array of marks into an object grouped by the page number
* Can be replaced by Object.groupBy https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/groupBy
* when it is implemented in TypeScript
* Implementation is standard from the Array.prototype.reduce documentation
* @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]
}
}
export {
toFile,
toPdfFile,
toPdfFiles,
inPx,
convertToPdfFile,
addMarks,
convertToPdfBlob,
groupMarksByPage,
}

View File

@ -1,33 +0,0 @@
import { Event } from 'nostr-tools'
import { Meta } from '../types'
/**
* This function returns the signature of last signer
* It will be used in the content of export signature's signedEvent
*/
const getLastSignersSig = (meta: Meta, signers: `npub1${string}`[]): string | null => {
// if there're no signers then use creator's signature
if (signers.length === 0) {
try {
const createSignatureEvent: Event = JSON.parse(meta.createSignature)
return createSignatureEvent.sig
} catch (error) {
return null
}
}
// get last signer
const lastSigner = signers[signers.length - 1]
// get the signature of last signer
try {
const lastSignatureEvent: Event = JSON.parse(
meta.docSignatures[lastSigner]
)
return lastSignatureEvent.sig
} catch (error) {
return null
}
}
export { getLastSignersSig }

View File

@ -1,5 +1,3 @@
import { PdfFile } from '../types/drawing.ts'
export const compareObjects = (
obj1: object | null | undefined,
obj2: object | null | undefined
@ -66,17 +64,3 @@ export const timeout = (ms: number = 60000) => {
}, ms) // Timeout duration in milliseconds
})
}
/**
* Creates a flat array where each object contains all required information about a Pdf File,
* including its name, hash, and content
* @param files
* @param fileHashes
*/
export const getFilesWithHashes = (
files: { [filename: string ]: PdfFile },
fileHashes: { [key: string]: string | null }
) => {
return Object.entries(files).map(([filename, pdfFile]) => {
return { pdfFile, filename, hash: fileHashes[filename] }
})
}

View File

@ -1,6 +1,6 @@
import JSZip from 'jszip'
import { toast } from 'react-toastify'
import { InputFileFormat, OutputByType, OutputType } from '../types'
import { OutputByType, OutputType } from '../types'
/**
* Read the content of a file within a zip archive.
@ -9,7 +9,7 @@ import { InputFileFormat, OutputByType, OutputType } from '../types'
* @param outputType The type of output to return (e.g., 'string', 'arraybuffer', 'uint8array', etc.).
* @returns A Promise resolving to the content of the file, or null if an error occurs.
*/
const readContentOfZipEntry = async <T extends OutputType>(
export const readContentOfZipEntry = async <T extends OutputType>(
zip: JSZip,
filePath: string,
outputType: T
@ -22,9 +22,8 @@ const readContentOfZipEntry = async <T extends OutputType>(
return null
}
// Read and return the content of the zip entry asynchronously
// or null if an error has occurred
return await zipEntry.async(outputType).catch((err) => {
// Read the content of the zip entry asynchronously
const fileContent = await zipEntry.async(outputType).catch((err) => {
// Handle any errors that occur during the read operation
console.log(`Error reading content of ${filePath}:`, err)
toast.error(
@ -32,21 +31,7 @@ const readContentOfZipEntry = async <T extends OutputType>(
)
return null
})
// Return the file content or null if an error occurred
return fileContent
}
const loadZip = async (data: InputFileFormat): Promise<JSZip | null> => {
try {
return await JSZip.loadAsync(data);
} catch (err: any) {
console.log('err in loading zip file :>> ', err)
toast.error(err.message || 'An error occurred in loading zip file.')
return null;
}
}
export {
readContentOfZipEntry,
loadZip
}