@scaleflex/widget-pdf-js 4.4.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,14 @@
3
3
  All notable changes to this project will be documented in this file.
4
4
  See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
5
5
 
6
+ # [4.5.0](https://code.scaleflex.cloud/scaleflex/widget/compare/v4.4.0...v4.5.0) (2025-10-08)
7
+
8
+ **Note:** Version bump only for package @scaleflex/widget-pdf-js
9
+
10
+
11
+
12
+
13
+
6
14
  # [4.4.0](https://code.scaleflex.cloud/scaleflex/widget/compare/v4.1.0...v4.4.0) (2025-10-07)
7
15
 
8
16
  **Note:** Version bump only for package @scaleflex/widget-pdf-js
@@ -0,0 +1,48 @@
1
+ var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10;
2
+ function _taggedTemplateLiteral(e, t) { return t || (t = e.slice(0)), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } })); }
3
+ import { FV, PC } from '@scaleflex/widget-common';
4
+ import { Arrow } from '@scaleflex/icons';
5
+ import { IconButton, Input } from '@scaleflex/ui/core';
6
+ import styled, { css } from 'styled-components';
7
+ var Footer = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n height: 62px;\n width: 100%;\n display: flex;\n align-items: center;\n justify-content: space-between;\n background-color: ", ";\n padding: 0 24px;\n padding-left: calc(24px - 10px);\n\n ", "\n"])), function (_ref) {
8
+ var palette = _ref.theme.palette;
9
+ return palette[PC.BackgroundStateless];
10
+ }, function (_ref2) {
11
+ var theme = _ref2.theme;
12
+ return css(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n ", " {\n height: 52px;\n border-bottom: 1px solid ", ";\n }\n "])), theme.breakpoints.down('lg'), theme.palette[PC.BordersSecondary]);
13
+ });
14
+ var NumPagesLabel = styled.p(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n margin: 0;\n white-space: nowrap;\n color: ", ";\n ", ";\n"])), function (_ref3) {
15
+ var palette = _ref3.theme.palette;
16
+ return palette[PC.TextSecondary];
17
+ }, function (_ref4) {
18
+ var typography = _ref4.theme.typography;
19
+ return typography.font[FV.LabelMedium];
20
+ });
21
+ var PagesInput = styled(Input)(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n width: 48px;\n"])));
22
+ var ControlsWrapper = styled.div(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["\n display: flex;\n align-items: center;\n column-gap: 8px;\n"])));
23
+ var ZoomWrapper = styled.div(_templateObject6 || (_templateObject6 = _taggedTemplateLiteral(["\n"])));
24
+ var ZoomControllersWrapper = styled.div(_templateObject7 || (_templateObject7 = _taggedTemplateLiteral(["\n display: flex;\n width: fit-content;\n align-items: center;\n overflow-x: auto;\n"])));
25
+ var ZoomButtons = styled.div(_templateObject8 || (_templateObject8 = _taggedTemplateLiteral(["\n display: flex;\n align-items: center;\n justify-content: center;\n padding: 8px;\n border-radius: 4px;\n height: 32px;\n width: 130px;\n\n span {\n ", ";\n color: ", ";\n padding: 0 8px;\n cursor: pointer;\n }\n"])), function (_ref5) {
26
+ var theme = _ref5.theme;
27
+ return theme.typography.font[FV.LabelMedium];
28
+ }, function (_ref6) {
29
+ var theme = _ref6.theme;
30
+ return theme.palette[PC.TextSecondary];
31
+ });
32
+ var ZoomButton = styled(IconButton)(_templateObject9 || (_templateObject9 = _taggedTemplateLiteral(["\n display: inline-flex;\n"])));
33
+ var ArrowIcon = styled(Arrow)(_templateObject10 || (_templateObject10 = _taggedTemplateLiteral(["\n transform: ", ";\n"])), function (_ref7) {
34
+ var $flip = _ref7.$flip;
35
+ return $flip ? 'scale(-1)' : 'none';
36
+ });
37
+ var Styled = {
38
+ Footer: Footer,
39
+ NumPagesLabel: NumPagesLabel,
40
+ PagesInput: PagesInput,
41
+ ControlsWrapper: ControlsWrapper,
42
+ ZoomWrapper: ZoomWrapper,
43
+ ZoomControllersWrapper: ZoomControllersWrapper,
44
+ ZoomButtons: ZoomButtons,
45
+ ZoomButton: ZoomButton,
46
+ ArrowIcon: ArrowIcon
47
+ };
48
+ export default Styled;
@@ -0,0 +1,47 @@
1
+ import { BTN_ZOOM_RATIO_PERCENTAGE, DEFAULT_ZOOM_RATIO, MAX_ZOOM_RATIO } from '@scaleflex/widget-explorer/lib/components/FileWindowPanel/Body/Body.constants';
2
+ import { Minus, Plus, PositionCenter } from '@scaleflex/icons';
3
+ import Styled from './Footer.styled';
4
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
5
+ var ZoomControllers = function ZoomControllers(_ref) {
6
+ var zoomRatio = _ref.zoomRatio,
7
+ setZoomRatio = _ref.setZoomRatio;
8
+ var zoomIn = function zoomIn() {
9
+ var nextZoomRatio = Math.min(zoomRatio + BTN_ZOOM_RATIO_PERCENTAGE, MAX_ZOOM_RATIO);
10
+ setZoomRatio(nextZoomRatio);
11
+ };
12
+ var zoomOut = function zoomOut() {
13
+ var nextZoomRatio = Math.min(Math.max(zoomRatio - BTN_ZOOM_RATIO_PERCENTAGE, BTN_ZOOM_RATIO_PERCENTAGE));
14
+ setZoomRatio(nextZoomRatio);
15
+ };
16
+ var resetZoom = function resetZoom() {
17
+ setZoomRatio(DEFAULT_ZOOM_RATIO);
18
+ };
19
+ return /*#__PURE__*/_jsxs(Styled.ZoomControllersWrapper, {
20
+ children: [/*#__PURE__*/_jsxs(Styled.ZoomButtons, {
21
+ children: [/*#__PURE__*/_jsx(Styled.ZoomButton, {
22
+ size: "lg",
23
+ color: "basic",
24
+ onClick: zoomOut,
25
+ children: /*#__PURE__*/_jsx(Minus, {})
26
+ }), /*#__PURE__*/_jsxs("span", {
27
+ onClick: resetZoom,
28
+ children: [parseInt(zoomRatio * 100), "%"]
29
+ }), /*#__PURE__*/_jsx(Styled.ZoomButton, {
30
+ size: "lg",
31
+ color: "basic",
32
+ onClick: zoomIn,
33
+ children: /*#__PURE__*/_jsx(Plus, {
34
+ size: 18
35
+ })
36
+ })]
37
+ }), /*#__PURE__*/_jsx(Styled.ZoomButton, {
38
+ size: "lg",
39
+ color: "basic",
40
+ onClick: resetZoom,
41
+ children: /*#__PURE__*/_jsx(PositionCenter, {
42
+ size: 18
43
+ })
44
+ })]
45
+ });
46
+ };
47
+ export default ZoomControllers;
@@ -0,0 +1,101 @@
1
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
+ import { IconButton, TooltipV2 } from '@scaleflex/ui/core';
8
+ import { useState } from 'react';
9
+ import { useUpdateEffect } from '@scaleflex/widget-common/lib/hooks';
10
+ import Styled from './Footer.styled';
11
+ import ZoomControllers from './ZoomControllers';
12
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
13
+ var Footer = function Footer(_ref) {
14
+ var i18n = _ref.i18n,
15
+ isLoading = _ref.isLoading,
16
+ numOfPages = _ref.numOfPages,
17
+ currentPage = _ref.currentPage,
18
+ setCurrentPage = _ref.setCurrentPage,
19
+ zoomRatio = _ref.zoomRatio,
20
+ setZoomRatio = _ref.setZoomRatio;
21
+ var isReachedPdfMaxPages = currentPage >= numOfPages;
22
+ var isReachedPdfMinPages = currentPage <= 1;
23
+ var _useState = useState(currentPage),
24
+ _useState2 = _slicedToArray(_useState, 2),
25
+ pdfPage = _useState2[0],
26
+ setPdfPage = _useState2[1];
27
+ useUpdateEffect(function () {
28
+ if (currentPage !== pdfPage) {
29
+ setPdfPage(currentPage);
30
+ }
31
+ }, [currentPage]);
32
+ var goPrevPage = function goPrevPage() {
33
+ if (isReachedPdfMinPages || isLoading) return;
34
+ var prevPage = currentPage - 1;
35
+ setCurrentPage(prevPage);
36
+ };
37
+ var goNextPage = function goNextPage() {
38
+ if (isReachedPdfMaxPages || isLoading) return;
39
+ var nextPage = currentPage + 1;
40
+ setCurrentPage(nextPage);
41
+ };
42
+ var handleChangePage = function handleChangePage(event) {
43
+ var pageNumber = parseInt(event.target.value, 10) || '';
44
+ var isValid = Number.isFinite(pageNumber);
45
+ if (isValid || !pageNumber) {
46
+ setPdfPage(pageNumber);
47
+ }
48
+ };
49
+ var handleSubmitPage = function handleSubmitPage(event) {
50
+ var keyCode = event.keyCode;
51
+ if (keyCode === 13) {
52
+ // Enter key
53
+ var validPageNumber = Math.min(Math.max(pdfPage, 1), numOfPages);
54
+ setPdfPage(validPageNumber);
55
+ setCurrentPage(validPageNumber);
56
+ }
57
+ };
58
+ return /*#__PURE__*/_jsxs(Styled.Footer, {
59
+ children: [/*#__PURE__*/_jsxs(Styled.ControlsWrapper, {
60
+ children: [/*#__PURE__*/_jsx(IconButton, {
61
+ color: "basic",
62
+ size: "sm",
63
+ onClick: goPrevPage,
64
+ disabled: isLoading || isReachedPdfMinPages,
65
+ children: /*#__PURE__*/_jsx(Styled.ArrowIcon, {
66
+ size: 14,
67
+ $flip: true
68
+ })
69
+ }), /*#__PURE__*/_jsx(TooltipV2, {
70
+ position: "top",
71
+ title: i18n('pdfJsPageChangeInputTooltipHint'),
72
+ arrow: true,
73
+ children: /*#__PURE__*/_jsx(Styled.PagesInput, {
74
+ size: "sm",
75
+ onKeyDown: handleSubmitPage,
76
+ value: pdfPage || '',
77
+ disabled: isLoading || !(numOfPages > 1),
78
+ onChange: handleChangePage
79
+ })
80
+ }), /*#__PURE__*/_jsx(Styled.NumPagesLabel, {
81
+ children: i18n('pdfPreviewNumOfPages', {
82
+ count: numOfPages
83
+ })
84
+ }), /*#__PURE__*/_jsx(IconButton, {
85
+ color: "basic",
86
+ size: "sm",
87
+ onClick: goNextPage,
88
+ disabled: isLoading || isReachedPdfMaxPages,
89
+ children: /*#__PURE__*/_jsx(Styled.ArrowIcon, {
90
+ size: 14
91
+ })
92
+ })]
93
+ }), /*#__PURE__*/_jsx(Styled.ZoomWrapper, {
94
+ children: /*#__PURE__*/_jsx(ZoomControllers, {
95
+ zoomRatio: zoomRatio,
96
+ setZoomRatio: setZoomRatio
97
+ })
98
+ })]
99
+ });
100
+ };
101
+ export default Footer;
@@ -0,0 +1,257 @@
1
+ function _slicedToArray(r, e) { return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest(); }
2
+ function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
3
+ function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
4
+ function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
5
+ function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t["return"] && (u = t["return"](), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
6
+ function _arrayWithHoles(r) { if (Array.isArray(r)) return r; }
7
+ import { useEffect, useRef, useState } from 'react';
8
+ import { Skeleton } from '@scaleflex/ui/core';
9
+ import { useIsUnMountedRef } from '@scaleflex/widget-common/lib/hooks';
10
+ import handlePromise from '@scaleflex/widget-utils/lib/handlePromise';
11
+ import Footer from './Footer';
12
+ import Styled from './PdfPreview.styled';
13
+
14
+ // pdfSource === pdf's link/path or file class/object's data (in-case of uploadable file)
15
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
16
+ var PdfPreview = function PdfPreview(_ref) {
17
+ var pdfSource = _ref.pdfSource,
18
+ prepareDocument = _ref.prepareDocument,
19
+ i18n = _ref.i18n,
20
+ onError = _ref.onError;
21
+ var containerRef = useRef();
22
+ var canvasRef = useRef();
23
+ var mousePosition = useRef();
24
+ var cursorDisplacement = useRef();
25
+ var transformation = useRef();
26
+ var pdfLoadedDocument = useRef();
27
+ var isUnMountedRef = useIsUnMountedRef();
28
+ var pendingPageNumToRender = useRef(null);
29
+ var _useState = useState(false),
30
+ _useState2 = _slicedToArray(_useState, 2),
31
+ isMouseDown = _useState2[0],
32
+ setIsMouseDown = _useState2[1];
33
+ var _useState3 = useState(1),
34
+ _useState4 = _slicedToArray(_useState3, 2),
35
+ currentPage = _useState4[0],
36
+ setCurrentPage = _useState4[1];
37
+ var _useState5 = useState(1),
38
+ _useState6 = _slicedToArray(_useState5, 2),
39
+ zoomRatio = _useState6[0],
40
+ setZoomRatio = _useState6[1];
41
+ var _useState7 = useState(),
42
+ _useState8 = _slicedToArray(_useState7, 2),
43
+ numOfPages = _useState8[0],
44
+ setNumOfPages = _useState8[1];
45
+ var _useState9 = useState(!pdfSource),
46
+ _useState10 = _slicedToArray(_useState9, 2),
47
+ isLoading = _useState10[0],
48
+ setIsLoading = _useState10[1];
49
+ var loadPdfDocument = async function loadPdfDocument() {
50
+ if (!pdfSource) {
51
+ onError(i18n('pdfJsPdfPreviewErrorInvalidPath'));
52
+ return;
53
+ }
54
+ try {
55
+ setIsLoading(true);
56
+ var docSrc = typeof pdfSource === 'string' ? pdfSource : await pdfSource.arrayBuffer();
57
+ pdfLoadedDocument.current = prepareDocument(docSrc);
58
+ pdfLoadedDocument.current = await pdfLoadedDocument.current.promise;
59
+ var pdf = pdfLoadedDocument.current;
60
+ if (isUnMountedRef.current) {
61
+ return;
62
+ }
63
+ setNumOfPages(pdf.numPages);
64
+ changePage(1);
65
+ } catch (error) {
66
+ onError(error.message);
67
+ }
68
+ };
69
+ var changePage = async function changePage(pageNum) {
70
+ if (!pdfLoadedDocument.current || !pageNum) {
71
+ return;
72
+ }
73
+ try {
74
+ setCurrentPage(pageNum);
75
+ setIsLoading(true);
76
+
77
+ // For avoiding can't use the same canvas during multiple render operations error from pdfjs
78
+ // This might happen on changing the page while some current page being rendered (ex. clicking next/back arrows of pages multiple times)
79
+ if (pendingPageNumToRender.current) {
80
+ pendingPageNumToRender.current = pageNum;
81
+ return;
82
+ }
83
+ pendingPageNumToRender.current = pageNum;
84
+ var page = await pdfLoadedDocument.current.getPage(pageNum);
85
+ if (isUnMountedRef.current) {
86
+ return;
87
+ }
88
+ updateCanvas(page);
89
+ setIsLoading(false);
90
+ } catch (error) {
91
+ onError(error.message);
92
+ }
93
+ };
94
+ var updateCanvas = function updateCanvas(page) {
95
+ var _containerRef$current = containerRef.current,
96
+ containerWidth = _containerRef$current.offsetWidth,
97
+ containerHeight = _containerRef$current.offsetHeight;
98
+ var canvas = canvasRef.current;
99
+ var canvasContext = canvas.getContext('2d');
100
+ var viewport = page.getViewport({
101
+ scale: 1
102
+ });
103
+ var widthRatio = containerWidth / viewport.width;
104
+ var heightRatio = containerHeight / viewport.height;
105
+ canvas.width = Math.floor(viewport.width * devicePixelRatio * 2);
106
+ canvas.height = Math.floor(viewport.height * devicePixelRatio * 2);
107
+ if (widthRatio < heightRatio) {
108
+ canvas.style.width = Math.floor(viewport.width * widthRatio) + 'px';
109
+ canvas.style.height = Math.floor(viewport.height * widthRatio) + 'px';
110
+ } else {
111
+ canvas.style.width = Math.floor(viewport.width * heightRatio) + 'px';
112
+ canvas.style.height = Math.floor(viewport.height * heightRatio) + 'px';
113
+ }
114
+ var transform = [
115
+ // Transfrom Matrix
116
+ canvas.width / viewport.width, 0, 0, canvas.height / viewport.height, 0, 0];
117
+ var renderContext = {
118
+ canvasContext: canvasContext,
119
+ viewport: viewport,
120
+ transform: transform
121
+ };
122
+ page.render(renderContext).promise["finally"](function () {
123
+ var pageNum = pendingPageNumToRender.current;
124
+ pendingPageNumToRender.current = null;
125
+ if (pageNum && page.pageNumber !== pageNum) {
126
+ changePage(pageNum);
127
+ }
128
+ });
129
+ };
130
+ var setCursorPosition = function setCursorPosition(event) {
131
+ mousePosition.current = {
132
+ x: event.clientX,
133
+ y: event.clientY
134
+ };
135
+ };
136
+ var getCursorPositionInCanvas = function getCursorPositionInCanvas() {
137
+ var cursorPosition = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {
138
+ x: 0,
139
+ y: 0
140
+ };
141
+ var canvas = canvasRef.current;
142
+ var canvasRect = canvas.getBoundingClientRect();
143
+ return {
144
+ x: cursorPosition.x - canvasRect.left,
145
+ y: cursorPosition.y - canvasRect.top
146
+ };
147
+ };
148
+ var getMouseDisplacement = function getMouseDisplacement(event) {
149
+ var clientX = event.clientX,
150
+ clientY = event.clientY;
151
+ var _mousePosition = mousePosition.current || {};
152
+ var prevPosition = getCursorPositionInCanvas(_mousePosition);
153
+ var nextPosition = getCursorPositionInCanvas({
154
+ x: clientX,
155
+ y: clientY
156
+ });
157
+ return {
158
+ x: (nextPosition.x - prevPosition.x) / zoomRatio,
159
+ y: (nextPosition.y - prevPosition.y) / zoomRatio
160
+ };
161
+ };
162
+ var changeZoomRatio = function changeZoomRatio(newRatio) {
163
+ setZoomRatio(newRatio);
164
+ zoomCanvas(newRatio);
165
+ };
166
+ var zoomCanvas = function zoomCanvas() {
167
+ var currentZoomRatio = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1;
168
+ var mouseDisplacement = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
169
+ x: 0,
170
+ y: 0
171
+ };
172
+ var container = containerRef.current;
173
+ var prevTransformation = transformation.current || {
174
+ x: 0,
175
+ y: 0
176
+ };
177
+ var scaledWidth = container.offsetWidth * currentZoomRatio;
178
+ var scaledHeight = container.offsetHeight * currentZoomRatio;
179
+ var nextTransformation = {
180
+ x: 0,
181
+ y: 0
182
+ };
183
+ if (currentZoomRatio > 1) {
184
+ nextTransformation = {
185
+ x: prevTransformation.x + mouseDisplacement.x,
186
+ y: prevTransformation.y + mouseDisplacement.y
187
+ };
188
+ var panningArea = {
189
+ x: (scaledWidth - container.offsetWidth) / (2 * currentZoomRatio),
190
+ y: (scaledHeight - container.offsetHeight) / (2 * currentZoomRatio)
191
+ };
192
+ nextTransformation = {
193
+ x: Math.min(Math.max(nextTransformation.x, -panningArea.x), panningArea.x),
194
+ y: Math.min(Math.max(nextTransformation.y, -panningArea.y), panningArea.y)
195
+ };
196
+ }
197
+ cursorDisplacement.current = nextTransformation;
198
+ container.style.transform = "scale(".concat(currentZoomRatio, ") translate(").concat(nextTransformation.x, "px, ").concat(nextTransformation.y, "px)");
199
+ };
200
+ var handleStartPanning = function handleStartPanning(event) {
201
+ if (zoomRatio > 1) {
202
+ setIsMouseDown(true);
203
+ setCursorPosition(event);
204
+ }
205
+ };
206
+ var handleReleasePanning = function handleReleasePanning() {
207
+ setIsMouseDown(false);
208
+ transformation.current = cursorDisplacement.current;
209
+ };
210
+ var handleMouseMove = function handleMouseMove(event) {
211
+ if (!isMouseDown) return;
212
+ var mouseDisplacement = getMouseDisplacement(event);
213
+ zoomCanvas(zoomRatio, mouseDisplacement);
214
+ };
215
+ useEffect(function () {
216
+ loadPdfDocument();
217
+ return function () {
218
+ var _pdfLoadedDocument$cu;
219
+ if ((_pdfLoadedDocument$cu = pdfLoadedDocument.current) !== null && _pdfLoadedDocument$cu !== void 0 && _pdfLoadedDocument$cu.destroy) {
220
+ handlePromise(pdfLoadedDocument.current.destroy());
221
+ }
222
+ setCurrentPage(1);
223
+ setZoomRatio(1);
224
+ };
225
+ }, [pdfSource]);
226
+ if (!pdfSource) {
227
+ return null;
228
+ }
229
+ return /*#__PURE__*/_jsxs(Styled.Container, {
230
+ children: [/*#__PURE__*/_jsxs(Styled.PreviewExtraWrapper, {
231
+ children: [isLoading && /*#__PURE__*/_jsx(Skeleton, {
232
+ width: "100%",
233
+ height: "100%"
234
+ }), /*#__PURE__*/_jsx(Styled.PreviewContainer, {
235
+ ref: containerRef,
236
+ onMouseDown: handleStartPanning,
237
+ onMouseUp: handleReleasePanning,
238
+ onMouseLeave: handleReleasePanning,
239
+ $isMouseDown: isMouseDown,
240
+ $scale: zoomRatio || 1,
241
+ onMouseMove: handleMouseMove,
242
+ children: /*#__PURE__*/_jsx("canvas", {
243
+ ref: canvasRef
244
+ })
245
+ })]
246
+ }), /*#__PURE__*/_jsx(Footer, {
247
+ i18n: i18n,
248
+ numOfPages: numOfPages,
249
+ isLoading: isLoading,
250
+ currentPage: currentPage,
251
+ setCurrentPage: changePage,
252
+ zoomRatio: zoomRatio,
253
+ setZoomRatio: changeZoomRatio
254
+ })]
255
+ });
256
+ };
257
+ export default PdfPreview;
@@ -0,0 +1,43 @@
1
+ var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7, _templateObject8, _templateObject9, _templateObject10, _templateObject11;
2
+ function _taggedTemplateLiteral(e, t) { return t || (t = e.slice(0)), Object.freeze(Object.defineProperties(e, { raw: { value: Object.freeze(t) } })); }
3
+ import styled, { css } from 'styled-components';
4
+ import { IconButton as SfxIconButton } from '@scaleflex/ui/core';
5
+ import { PC } from '@scaleflex/widget-common';
6
+ import { Spinner as SfxSpinner } from '@scaleflex/icons';
7
+ var Container = styled.div(_templateObject || (_templateObject = _taggedTemplateLiteral(["\n width: 100%;\n height: 100%;\n ", "\n"])), function (_ref) {
8
+ var theme = _ref.theme;
9
+ return css(_templateObject2 || (_templateObject2 = _taggedTemplateLiteral(["\n ", " {\n background-color: ", ";\n }\n "])), theme.breakpoints.down('lg'), theme.palette[PC.BackgroundActive]);
10
+ });
11
+ var PreviewExtraWrapper = styled.div(_templateObject3 || (_templateObject3 = _taggedTemplateLiteral(["\n width: calc(100% - (24px * 2));\n max-width: calc(100% - (24px * 2));\n height: calc(100% - 62px);\n max-height: calc(100% - 62px);\n overflow: hidden;\n margin: 0 auto;\n position: relative;\n background-color: ", ";\n\n ", "\n"])), function (_ref2) {
12
+ var palette = _ref2.theme.palette;
13
+ return palette[PC.BackgroundActive];
14
+ }, function (_ref3) {
15
+ var theme = _ref3.theme;
16
+ return css(_templateObject4 || (_templateObject4 = _taggedTemplateLiteral(["\n ", " {\n height: calc(100% - 52px);\n max-height: calc(100% - 52px);\n }\n "])), theme.breakpoints.down('lg'));
17
+ });
18
+ var PreviewContainer = styled.div(_templateObject5 || (_templateObject5 = _taggedTemplateLiteral(["\n position: relative;\n width: 100%;\n height: 100%;\n max-width: 100%;\n display: flex;\n justify-content: center;\n align-items: center;\n\n ", "\n\n canvas {\n margin: 0;\n padding: 0;\n }\n"])), function (_ref4) {
19
+ var $scale = _ref4.$scale,
20
+ $isMouseDown = _ref4.$isMouseDown;
21
+ return css(_templateObject6 || (_templateObject6 = _taggedTemplateLiteral(["\n transition: ", ";\n cursor: ", ";\n "])), $isMouseDown ? 'none' : 'transform 200ms linear', $scale > 1 ? 'grab' : 'default');
22
+ });
23
+ var IconButton = styled(SfxIconButton)(_templateObject7 || (_templateObject7 = _taggedTemplateLiteral(["\n position: absolute;\n top: 50%;\n transform: translateY(-50%);\n z-index: 1;\n width: 40px;\n height: 40px;\n padding: 10px;\n background-color: ", ";\n\n ", "\n"])), function (_ref5) {
24
+ var palette = _ref5.theme.palette;
25
+ return palette[PC.Accent_1_8_Opacity];
26
+ }, function (_ref6) {
27
+ var left = _ref6.left;
28
+ return left ? css(_templateObject8 || (_templateObject8 = _taggedTemplateLiteral(["\n left: 12px;\n "]))) : css(_templateObject9 || (_templateObject9 = _taggedTemplateLiteral(["\n right: 12px;\n "])));
29
+ });
30
+ var SpinnerWrapper = styled.div(_templateObject10 || (_templateObject10 = _taggedTemplateLiteral(["\n position: absolute;\n top: 50%;\n left: 50%;\n z-index: 100;\n transform: translate(-50%, 50%);\n"])));
31
+ var Spinner = styled(SfxSpinner)(_templateObject11 || (_templateObject11 = _taggedTemplateLiteral(["\n animation: spinner 1.2s linear infinite;\n color: ", ";\n"])), function (_ref7) {
32
+ var palette = _ref7.theme.palette;
33
+ return palette[PC.AccentStateless];
34
+ });
35
+ var Styled = {
36
+ Container: Container,
37
+ PreviewExtraWrapper: PreviewExtraWrapper,
38
+ PreviewContainer: PreviewContainer,
39
+ IconButton: IconButton,
40
+ SpinnerWrapper: SpinnerWrapper,
41
+ Spinner: Spinner
42
+ };
43
+ export default Styled;
@@ -0,0 +1,6 @@
1
+ export default {
2
+ pdfPreviewNumOfPages: 'of %{count} pages',
3
+ pdfJsPageChangeInputTooltipHint: 'Press enter after change',
4
+ pdfJsPdfPreviewErrorLabel: 'Unable to view this PDF document',
5
+ pdfJsPdfPreviewErrorInvalidPath: 'Invalid PDF document source provided'
6
+ };
package/lib/index.js ADDED
@@ -0,0 +1,186 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _classCallCheck(a, n) { if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function"); }
3
+ function _defineProperties(e, r) { for (var t = 0; t < r.length; t++) { var o = r[t]; o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o); } }
4
+ function _createClass(e, r, t) { return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", { writable: !1 }), e; }
5
+ function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
6
+ function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
7
+ function _callSuper(t, o, e) { return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e)); }
8
+ function _possibleConstructorReturn(t, e) { if (e && ("object" == _typeof(e) || "function" == typeof e)) return e; if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined"); return _assertThisInitialized(t); }
9
+ function _assertThisInitialized(e) { if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return e; }
10
+ function _isNativeReflectConstruct() { try { var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); } catch (t) {} return (_isNativeReflectConstruct = function _isNativeReflectConstruct() { return !!t; })(); }
11
+ function _getPrototypeOf(t) { return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) { return t.__proto__ || Object.getPrototypeOf(t); }, _getPrototypeOf(t); }
12
+ function _inherits(t, e) { if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function"); t.prototype = Object.create(e && e.prototype, { constructor: { value: t, writable: !0, configurable: !0 } }), Object.defineProperty(t, "prototype", { writable: !1 }), e && _setPrototypeOf(t, e); }
13
+ function _setPrototypeOf(t, e) { return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) { return t.__proto__ = e, t; }, _setPrototypeOf(t, e); }
14
+ import { Plugin, ScaleflexWidget } from '@scaleflex/widget-core';
15
+ import Explorer from '@scaleflex/widget-explorer';
16
+ import Translator from '@scaleflex/widget-utils/lib/Translator';
17
+ import { PLUGINS_IDS } from '@scaleflex/widget-utils/lib/constants';
18
+ import getFileLink from '@scaleflex/widget-utils/lib/getFileLink';
19
+ import isUploadableFile from '@scaleflex/widget-utils/lib/isUploadableFile';
20
+ import defaultLocale from './defaultLocale';
21
+ import PdfPreview from './components/PdfPreview';
22
+
23
+ // TODO: find a way to show version of the current plugin
24
+ // why solution below isn't good?
25
+ // first import doesn't work with webpack 5 as it was deprecated
26
+ // second import fixes webpack 5 issue as it was mentioned in their docs
27
+ // but it exposes our package.json to the client and it is mentioned as security rist in mutiple places
28
+ // https://github.com/axelpale/genversion
29
+ // https://stackoverflow.com/questions/64993118/error-should-not-import-the-named-export-version-imported-as-version
30
+ // https://stackoverflow.com/questions/9153571/is-there-a-way-to-get-version-from-package-json-in-nodejs-code/10855054#10855054
31
+ // import { version } from '../package.json'
32
+ // import packageInfo from '../package.json'
33
+ var PdfJs = /*#__PURE__*/function (_Plugin) {
34
+ // static VERSION = packageInfo.version
35
+
36
+ function PdfJs(filerobot) {
37
+ var _this;
38
+ var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
39
+ _classCallCheck(this, PdfJs);
40
+ _this = _callSuper(this, PdfJs, [filerobot, opts]);
41
+ _this.id = PLUGINS_IDS.PDF_JS;
42
+ _this.libId = 'pdfjs-lib';
43
+ _this.title = 'Pdf-js';
44
+ _this.type = 'editor';
45
+ _this.defaultLocale = {
46
+ strings: defaultLocale
47
+ };
48
+ _this.opts = opts;
49
+ _this.i18nInit();
50
+ _this.prepareDocument = _this.prepareDocument.bind(_this);
51
+ _this.render = _this.render.bind(_this);
52
+ return _this;
53
+ }
54
+ _inherits(PdfJs, _Plugin);
55
+ return _createClass(PdfJs, [{
56
+ key: "i18nInit",
57
+ value: function i18nInit() {
58
+ this.translator = new Translator([this.defaultLocale, this.filerobot.locale, this.opts.locale]);
59
+ this.i18n = this.translator.translate.bind(this.translator);
60
+ this.i18nArray = this.translator.translateArray.bind(this.translator);
61
+ }
62
+ }, {
63
+ key: "install",
64
+ value: function install() {
65
+ if (Explorer) {
66
+ this.mount(Explorer, this);
67
+ this.loadLib();
68
+ }
69
+ }
70
+ }, {
71
+ key: "uninstall",
72
+ value: function uninstall() {
73
+ this.unmount();
74
+ this.removeLib();
75
+ }
76
+ }, {
77
+ key: "loadLib",
78
+ value: function loadLib() {
79
+ var _this2 = this;
80
+ if (this.isPdfJsLibLoading) {
81
+ return;
82
+ }
83
+ this.isPdfJsLibLoading = true;
84
+
85
+ // We are using both pdfjs & its worker from CDN as they needs dynamic import, that would cause a change in vite's build target
86
+ // Also would cause to change the bundled JS bundle type from umd to es, so using the CDN avoids that.
87
+ var script = document.createElement('script');
88
+ script.id = this.libId;
89
+ script.src = 'https://cdn.scaleflex.com/plugins/widget/assets/js/pdf.min.js?vh=a4641a&func=proxy';
90
+ script.async = true;
91
+ script.onload = function () {
92
+ _this2.pdfJsLib = window.pdfjsLib;
93
+ _this2.pdfJsLib.GlobalWorkerOptions.workerSrc = 'https://cdn.scaleflex.com/plugins/widget/assets/js/pdf.worker.js?vh=49162d&func=proxy';
94
+ _this2.isPdfJsLibLoading = false;
95
+ if (typeof _this2.onLoadPdfJsLib === 'function') {
96
+ _this2.onLoadPdfJsLib();
97
+ _this2.onLoadPdfJsLib = null;
98
+ }
99
+ };
100
+ script.onerror = function () {
101
+ _this2.isPdfJsLibLoading = false;
102
+ _this2.removeLib();
103
+ if (typeof _this2.onErrorPdfJsLib === 'function') {
104
+ _this2.onErrorPdfJsLib();
105
+ _this2.onErrorPdfJsLib = null;
106
+ }
107
+ };
108
+ document.body.appendChild(script);
109
+ }
110
+ }, {
111
+ key: "removeLib",
112
+ value: function removeLib() {
113
+ this.isPdfJsLibLoading = false;
114
+ var element = document.getElementById(this.libId);
115
+ if (element) {
116
+ document.body.removeChild(element);
117
+ }
118
+ }
119
+ }, {
120
+ key: "handleLoadingDocumentError",
121
+ value: function handleLoadingDocumentError(setIsFailedToViewPdf, reason) {
122
+ var abortMsgsToDismiss = ['worker was destroyed', 'transport destroyed', 'canceled'];
123
+ if (abortMsgsToDismiss.includes(reason === null || reason === void 0 ? void 0 : reason.toLowerCase())) {
124
+ return;
125
+ }
126
+ this.info({
127
+ message: this.i18n('pdfJsPdfPreviewErrorLabel'),
128
+ details: reason || ''
129
+ }, 'warning', 5000);
130
+ setIsFailedToViewPdf(true);
131
+ }
132
+ }, {
133
+ key: "waitForLibLoadingThenPrepareDocument",
134
+ value: function waitForLibLoadingThenPrepareDocument(pdfPath) {
135
+ var _this3 = this;
136
+ var isPrepareCancelled = false;
137
+ var destroyPendingDocPrepare = function destroyPendingDocPrepare() {
138
+ isPrepareCancelled = true;
139
+ };
140
+ var waitLibAndPrepareDocPromise = new Promise(function (resolve, reject) {
141
+ _this3.onLoadPdfJsLib = async function () {
142
+ if (isPrepareCancelled) {
143
+ reject(new Error('canceled'));
144
+ return;
145
+ }
146
+ var doc = await _this3.prepareDocument(pdfPath).promise;
147
+ resolve(doc);
148
+ };
149
+ _this3.onErrorPdfJsLib = function () {
150
+ reject(new Error('canceled'));
151
+ };
152
+ // Making sure that the loading request is sent (maybe it's failed at some point so we are re-sending it)
153
+ // If it is already loading/in-progress its safe guard condition there won't re-trigger it.
154
+ _this3.loadLib();
155
+ });
156
+
157
+ // Simulating used properties in PdfPreview and same as the ones returned from getDocument of the lib.
158
+ return {
159
+ promise: waitLibAndPrepareDocPromise,
160
+ destroy: destroyPendingDocPrepare
161
+ };
162
+ }
163
+ }, {
164
+ key: "prepareDocument",
165
+ value: function prepareDocument(pdfPath) {
166
+ if (!this.pdfJsLib) {
167
+ return this.waitForLibLoadingThenPrepareDocument(pdfPath);
168
+ }
169
+ return this.pdfJsLib.getDocument(pdfPath);
170
+ }
171
+ }, {
172
+ key: "render",
173
+ value: function render(_ref) {
174
+ var file = _ref.file,
175
+ setIsFailedToViewPdf = _ref.setIsFailedToViewPdf;
176
+ var pdfSource = isUploadableFile(file) ? ScaleflexWidget.uploadFilesData[file.id] : getFileLink(file);
177
+ return PdfPreview({
178
+ pdfSource: pdfSource,
179
+ i18n: this.i18n,
180
+ prepareDocument: this.prepareDocument,
181
+ onError: this.handleLoadingDocumentError.bind(this, setIsFailedToViewPdf)
182
+ });
183
+ }
184
+ }]);
185
+ }(Plugin);
186
+ export default PdfJs;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scaleflex/widget-pdf-js",
3
- "version": "4.4.0",
3
+ "version": "4.5.0",
4
4
  "description": "Pdf-js integration with Scaleflex",
5
5
  "license": "MIT",
6
6
  "main": "lib/index.js",
@@ -15,7 +15,7 @@
15
15
  "dependencies": {
16
16
  "@scaleflex/icons": "^3.0.0-beta.11",
17
17
  "@scaleflex/ui": "^3.0.0-beta.11",
18
- "@scaleflex/widget-common": "^4.4.0"
18
+ "@scaleflex/widget-common": "^4.5.0"
19
19
  },
20
20
  "devDependencies": {
21
21
  "react": "^19.0.0",
@@ -27,5 +27,5 @@
27
27
  "react": ">=19.0.0",
28
28
  "react-dom": ">=19.0.0"
29
29
  },
30
- "gitHead": "04b8ec545c4f10be89f5a44eed954acf8433360c"
30
+ "gitHead": "df64ca68034ed6c33e123e7dfa215176aa0a1196"
31
31
  }