@progress/kendo-pdfviewer-common 0.1.1 → 0.1.2

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.
@@ -0,0 +1,3 @@
1
+ export * from './scroller';
2
+ export * from './search';
3
+ export * from './utils';
@@ -0,0 +1,229 @@
1
+ import Draggable from '@progress/kendo-draggable';
2
+ const throttle = function (func, wait, options = {}) {
3
+ let timeout, context, args, result;
4
+ let previous = 0;
5
+ const later = function () {
6
+ previous = options.leading === false ? 0 : new Date().getTime();
7
+ timeout = undefined;
8
+ result = func.apply(context, args);
9
+ if (!timeout) {
10
+ context = args = null;
11
+ }
12
+ };
13
+ const throttled = function () {
14
+ const now = new Date().getTime();
15
+ if (!previous && options.leading === false) {
16
+ previous = now;
17
+ }
18
+ const remaining = wait - (now - previous);
19
+ context = undefined; // this
20
+ args = arguments;
21
+ if (remaining <= 0 || remaining > wait) {
22
+ if (timeout) {
23
+ clearTimeout(timeout);
24
+ timeout = undefined;
25
+ }
26
+ previous = now;
27
+ result = func.apply(context, args);
28
+ if (!timeout) {
29
+ context = args = null;
30
+ }
31
+ }
32
+ else if (!timeout && options.trailing !== false) {
33
+ timeout = window.setTimeout(later, remaining);
34
+ }
35
+ return result;
36
+ };
37
+ return throttled;
38
+ };
39
+ const preventDefault = (e) => {
40
+ if (e.preventDefault) {
41
+ e.preventDefault();
42
+ }
43
+ if (e.originalEvent) {
44
+ e.originalEvent.preventDefault();
45
+ }
46
+ };
47
+ const matchesElementSelector = (element, selector) => {
48
+ if (!element || !selector) {
49
+ return false;
50
+ }
51
+ return element.closest(selector);
52
+ };
53
+ const FRAMES_PER_SECOND = 1000 / 60;
54
+ const SCROLL = 'scroll';
55
+ /**
56
+ * @hidden
57
+ */
58
+ export class Scroller {
59
+ constructor(element, options) {
60
+ this.options = {
61
+ events: {
62
+ [SCROLL]: () => undefined
63
+ },
64
+ filter: '',
65
+ // throttle the scroll events to get a more similar experience
66
+ // to the scrolling behavior in Adobe Acrobat Reader
67
+ // as well as allow a way to improve the scrolling performance for large files
68
+ panScrollThrottleDelay: FRAMES_PER_SECOND,
69
+ // the drag directions are actually reversed, e.g.
70
+ // dragging to the right actually moves the document to the left
71
+ scrollDirectionModifier: -1,
72
+ scrollThrottleDelay: FRAMES_PER_SECOND
73
+ };
74
+ this.onElementScroll = () => {
75
+ const element = this.element;
76
+ if (this.state.trackNextElementScroll) {
77
+ this.scrollTo(element.scrollLeft, element.scrollTop);
78
+ }
79
+ else {
80
+ // reset the state, so that consecutive scroll events can be handled
81
+ this.state.trackNextElementScroll = true;
82
+ }
83
+ };
84
+ this.onDragStart = (e) => {
85
+ this.state.dragStarted = false;
86
+ if (!this.shouldTrackPanEvents()) {
87
+ return;
88
+ }
89
+ const target = e.target || (e.originalEvent || {}).target;
90
+ if (this.options.filter &&
91
+ !matchesElementSelector(target, this.options.filter)) {
92
+ return;
93
+ }
94
+ preventDefault(e);
95
+ this.setState({
96
+ dragStarted: true,
97
+ location: {
98
+ pageX: e.pageX,
99
+ pageY: e.pageY
100
+ },
101
+ locationDelta: {
102
+ x: 0,
103
+ y: 0
104
+ }
105
+ });
106
+ };
107
+ this.onDrag = (e) => {
108
+ if (!this.shouldTrackPanEvents() || !this.state.dragStarted) {
109
+ return;
110
+ }
111
+ this.calculateEventLocationDelta(e);
112
+ this.setState({
113
+ location: {
114
+ pageX: e.pageX,
115
+ pageY: e.pageY
116
+ }
117
+ });
118
+ const directionModifier = this.options.scrollDirectionModifier;
119
+ const scrollLeft = this.element.scrollLeft +
120
+ directionModifier * this.state.locationDelta.x;
121
+ const scrollTop = this.element.scrollTop +
122
+ directionModifier * this.state.locationDelta.y;
123
+ this.scrollTo(scrollLeft, scrollTop);
124
+ };
125
+ this.onDragEnd = () => {
126
+ if (!this.shouldTrackPanEvents()) {
127
+ return;
128
+ }
129
+ };
130
+ this.element = element;
131
+ this.options = Object.assign({}, this.options, options);
132
+ this.resetState();
133
+ this.bindEvents();
134
+ }
135
+ destroy() {
136
+ this.unbindEvents();
137
+ }
138
+ initDraggable() {
139
+ this.destroyDraggable();
140
+ if (this.options.panScrollThrottleDelay > 0) {
141
+ this.throttledOnDrag = throttle(this.onDrag, this.options.panScrollThrottleDelay);
142
+ }
143
+ else {
144
+ this.throttledOnDrag = this.onDrag;
145
+ }
146
+ this.draggable = new Draggable({
147
+ mouseOnly: false,
148
+ press: this.onDragStart,
149
+ drag: this.throttledOnDrag,
150
+ release: this.onDragEnd
151
+ });
152
+ this.draggable.bindTo(this.element);
153
+ }
154
+ destroyDraggable() {
155
+ if (this.draggable && this.draggable.destroy) {
156
+ this.draggable.destroy();
157
+ if (this.throttledOnDrag && this.throttledOnDrag.cancel) {
158
+ this.throttledOnDrag.cancel();
159
+ this.throttledOnDrag = null;
160
+ }
161
+ }
162
+ }
163
+ bindEvents() {
164
+ this.bindDraggableEvents();
165
+ this.bindElementScroll();
166
+ }
167
+ bindDraggableEvents() {
168
+ this.initDraggable();
169
+ }
170
+ bindElementScroll() {
171
+ if (this.options.scrollThrottleDelay > 0) {
172
+ this.throttledOnElementScroll = throttle(this.onElementScroll, this.options.scrollThrottleDelay);
173
+ }
174
+ else {
175
+ this.throttledOnElementScroll = this.onElementScroll;
176
+ }
177
+ this.element.addEventListener(SCROLL, this.throttledOnElementScroll);
178
+ }
179
+ unbindEvents() {
180
+ this.unbindElementScroll();
181
+ this.unbindDraggableEvents();
182
+ }
183
+ unbindDraggableEvents() {
184
+ this.destroyDraggable();
185
+ }
186
+ unbindElementScroll() {
187
+ if (this.throttledOnElementScroll &&
188
+ this.throttledOnElementScroll.cancel) {
189
+ this.throttledOnElementScroll.cancel();
190
+ this.throttledOnElementScroll = null;
191
+ }
192
+ this.element.removeEventListener(SCROLL, this.throttledOnElementScroll);
193
+ }
194
+ setState(newState) {
195
+ this.state = Object.assign({}, this.state || {}, newState);
196
+ }
197
+ resetState() {
198
+ this.setState({
199
+ trackPanEvents: false,
200
+ trackNextElementScroll: false,
201
+ location: { pageX: 0, pageY: 0 },
202
+ locationDelta: { x: 0, y: 0 }
203
+ });
204
+ }
205
+ enablePanEventsTracking() {
206
+ this.state.trackPanEvents = true;
207
+ this.bindDraggableEvents();
208
+ }
209
+ disablePanEventsTracking() {
210
+ this.unbindDraggableEvents();
211
+ this.state.trackPanEvents = false;
212
+ }
213
+ shouldTrackPanEvents() {
214
+ return this.state.trackPanEvents;
215
+ }
216
+ calculateEventLocationDelta(e) {
217
+ this.state.locationDelta = {
218
+ x: e.pageX - this.state.location.pageX,
219
+ y: e.pageY - this.state.location.pageY
220
+ };
221
+ }
222
+ scrollTo(x, y, options = { trackScrollEvent: true }) {
223
+ if (!options.trackScrollEvent) {
224
+ this.state.trackNextElementScroll = false;
225
+ }
226
+ this.element.scrollLeft = x;
227
+ this.element.scrollTop = y;
228
+ }
229
+ }
@@ -0,0 +1,256 @@
1
+ const unwrapElement = (element) => {
2
+ const parentElement = element.parentElement;
3
+ if (!element || !parentElement) {
4
+ return;
5
+ }
6
+ parentElement.replaceWith(...Array.from(parentElement.childNodes));
7
+ };
8
+ const unwrapElements = (elements) => {
9
+ if (!elements || !elements.length || elements.length <= 0) {
10
+ return;
11
+ }
12
+ for (let i = 0; i < elements.length; i++) {
13
+ unwrapElement(elements[i]);
14
+ }
15
+ };
16
+ const wrapElement = (element, wrapper) => {
17
+ if (element.parentNode) {
18
+ element.parentNode.insertBefore(wrapper, element);
19
+ wrapper.appendChild(element);
20
+ }
21
+ };
22
+ const wrapInnerElement = (element, wrapper) => {
23
+ if (!element || !element.parentNode || !wrapper) {
24
+ return;
25
+ }
26
+ element.appendChild(wrapper);
27
+ while (element.firstChild && element.firstChild !== wrapper) {
28
+ wrapper.appendChild(element.firstChild);
29
+ }
30
+ };
31
+ const addClass = (className, element) => {
32
+ element.classList.add(className);
33
+ };
34
+ const removeClass = (className, element) => {
35
+ element.classList.remove(className);
36
+ };
37
+ const toClassSelector = (className) => `.${className}`;
38
+ const CHAR_INDEX_DATA_ATTR = 'data-char-index';
39
+ const MATCH_INDEX_DATA_ATTR = 'data-match-index';
40
+ /**
41
+ * @hidden
42
+ */
43
+ export class SearchService {
44
+ constructor(options) {
45
+ this.options = {
46
+ highlightClass: 'k-search-highlight',
47
+ highlightMarkClass: 'k-search-highlight-mark',
48
+ charClass: 'k-text-char',
49
+ textContainers: []
50
+ };
51
+ this.extendOptions(options);
52
+ this.resetState();
53
+ }
54
+ destroy() {
55
+ this.clearSearch();
56
+ }
57
+ extendOptions(options) {
58
+ this.options = Object.assign({}, this.options, options);
59
+ }
60
+ setState(newState) {
61
+ this.state = Object.assign({}, this.state || {}, newState);
62
+ }
63
+ resetState() {
64
+ this.setState({
65
+ text: '',
66
+ textNodes: [],
67
+ charIndex: 0,
68
+ activeMatchIndex: 0,
69
+ matches: []
70
+ });
71
+ }
72
+ search({ text, matchCase }) {
73
+ let searchRegex = new RegExp(text, matchCase ? 'g' : 'ig');
74
+ let match;
75
+ if (this.shouldTransformText()) {
76
+ this.transformTextForSearch();
77
+ }
78
+ this.state.matches = [];
79
+ this.state.activeMatchIndex = 0;
80
+ this.removeIndicators();
81
+ if (text === '') {
82
+ return [];
83
+ }
84
+ match = searchRegex.exec(this.state.text);
85
+ while (match) {
86
+ this.state.matches.push({
87
+ startOffset: match.index,
88
+ endOffset: match.index + match[0].length
89
+ });
90
+ match = searchRegex.exec(this.state.text);
91
+ }
92
+ this.highlightAllMatches();
93
+ this.addActiveMatchMark();
94
+ return this.state.matches;
95
+ }
96
+ clearSearch() {
97
+ this.removeIndicators();
98
+ this.restoreOriginalText();
99
+ }
100
+ restoreOriginalText() {
101
+ this.forEachTextContainer((textContainer) => {
102
+ const nodes = Array.from(textContainer.querySelectorAll('span:not(.' + this.options.charClass + ')'));
103
+ nodes.forEach((node) => {
104
+ node.innerHTML = node.textContent;
105
+ });
106
+ });
107
+ }
108
+ shouldTransformText() {
109
+ return !this.state.text;
110
+ }
111
+ transformTextForSearch() {
112
+ this.state.textNodes = [];
113
+ this.state.charIndex = 0;
114
+ this.state.text = '';
115
+ this.forEachTextContainer((textContainer) => {
116
+ this.extractTextNodes(textContainer);
117
+ });
118
+ this.transformTextNodesForSearch(this.state.textNodes);
119
+ }
120
+ extractTextNodes(node) {
121
+ if (node.nodeType === Node.TEXT_NODE) {
122
+ this.state.textNodes.push(node);
123
+ }
124
+ else {
125
+ for (let i = 0; i < node.childNodes.length; i++) {
126
+ this.extractTextNodes(node.childNodes[i]);
127
+ }
128
+ }
129
+ }
130
+ transformTextNodesForSearch(textNodes) {
131
+ for (let i = 0; i < textNodes.length; i++) {
132
+ this.transformTextNodeForSearch(textNodes[i]);
133
+ }
134
+ }
135
+ transformTextNodeForSearch(node) {
136
+ const text = node.textContent;
137
+ if (text.length <= 0) {
138
+ return;
139
+ }
140
+ this.state.text = this.state.text + text;
141
+ const span = document.createElement('span');
142
+ wrapElement(node, span);
143
+ const splittedHtml = this.splitTextByChars(text);
144
+ span.innerHTML = splittedHtml;
145
+ unwrapElement(span.childNodes[0]);
146
+ }
147
+ splitTextByChars(text) {
148
+ let splittedTextHtml = '';
149
+ for (let i = 0; i < text.length; i++) {
150
+ splittedTextHtml += `<span class='${this.options.charClass}' ${CHAR_INDEX_DATA_ATTR}=${this.state.charIndex}>${text[i]}</span>`;
151
+ this.state.charIndex++;
152
+ }
153
+ return splittedTextHtml;
154
+ }
155
+ forEachTextContainer(callback) {
156
+ for (let i = 0; i < this.options.textContainers.length; i++) {
157
+ const textContainer = this.options.textContainers[i];
158
+ callback(textContainer, i);
159
+ }
160
+ }
161
+ highlightAllMatches() {
162
+ this.state.matches.forEach((match, matchIndex) => {
163
+ this.addMatchHighlight(match.startOffset, match.endOffset, matchIndex);
164
+ });
165
+ }
166
+ addMatchHighlight(matchStartOffset, matchEndOffset, matchIndex) {
167
+ for (let i = matchStartOffset; i < matchEndOffset; i++) {
168
+ this.forEachTextContainer((textContainer) => {
169
+ const highlights = Array.from(textContainer.querySelectorAll(toClassSelector(`${this.options.charClass}[${CHAR_INDEX_DATA_ATTR}='${i}']`)));
170
+ highlights.forEach((highlight) => {
171
+ addClass(this.options.highlightClass, highlight);
172
+ highlight.setAttribute(MATCH_INDEX_DATA_ATTR, matchIndex);
173
+ });
174
+ });
175
+ }
176
+ }
177
+ removeMatchHighlights() {
178
+ this.forEachTextContainer((textContainer) => {
179
+ const highlights = Array.from(textContainer.querySelectorAll(toClassSelector(this.options.highlightClass)));
180
+ highlights.forEach((highlight) => {
181
+ removeClass(this.options.highlightClass, highlight);
182
+ highlight.removeAttribute(MATCH_INDEX_DATA_ATTR);
183
+ });
184
+ });
185
+ }
186
+ addActiveMatchMark() {
187
+ if (!this.state.activeMatchIndex && this.state.activeMatchIndex !== 0) {
188
+ this.state.activeMatchIndex = 0;
189
+ }
190
+ else if (this.state.activeMatchIndex > this.state.matches.length) {
191
+ this.state.activeMatchIndex = this.state.matches.length;
192
+ }
193
+ else {
194
+ this.removeActiveMatchMark();
195
+ }
196
+ const mark = document.createElement('span');
197
+ mark.classList.add(this.options.highlightMarkClass);
198
+ this.forEachTextContainer((textContainer) => {
199
+ const matches = Array.from(textContainer.querySelectorAll(toClassSelector(this.options.charClass +
200
+ '[' +
201
+ MATCH_INDEX_DATA_ATTR +
202
+ "='" +
203
+ this.state.activeMatchIndex +
204
+ "']")));
205
+ matches.forEach((match) => {
206
+ wrapInnerElement(match, mark.cloneNode(true));
207
+ });
208
+ });
209
+ }
210
+ removeActiveMatchMark() {
211
+ this.forEachTextContainer((textContainer) => {
212
+ const marks = Array.from(textContainer.querySelectorAll(toClassSelector(this.options.highlightMarkClass)));
213
+ const childNodes = marks.flatMap((x) => Array.from(x.childNodes));
214
+ unwrapElements(childNodes);
215
+ });
216
+ }
217
+ removeIndicators() {
218
+ this.removeActiveMatchMark();
219
+ this.removeMatchHighlights();
220
+ }
221
+ markNextMatch() {
222
+ this.markNextMatchIndex();
223
+ this.addActiveMatchMark();
224
+ }
225
+ markPreviousMatch() {
226
+ this.markPreviousMatchIndex();
227
+ this.addActiveMatchMark();
228
+ }
229
+ markNextMatchIndex() {
230
+ this.moveActiveMatchIndex(1);
231
+ }
232
+ markPreviousMatchIndex() {
233
+ this.moveActiveMatchIndex(-1);
234
+ }
235
+ moveActiveMatchIndex(delta) {
236
+ this.state.activeMatchIndex += delta;
237
+ if (this.state.activeMatchIndex < 0) {
238
+ this.state.activeMatchIndex = Math.max(this.state.matches.length - 1, 0);
239
+ }
240
+ else if (this.state.activeMatchIndex >
241
+ this.state.matches.length - 1) {
242
+ this.state.activeMatchIndex = 0;
243
+ }
244
+ }
245
+ getActiveMatchElement() {
246
+ let markedMatch;
247
+ this.forEachTextContainer((textContainer) => {
248
+ const mark = textContainer.querySelector(toClassSelector(this.options.highlightMarkClass));
249
+ if (mark) {
250
+ markedMatch = mark;
251
+ return;
252
+ }
253
+ });
254
+ return markedMatch;
255
+ }
256
+ }
@@ -0,0 +1,315 @@
1
+ import { saveAs } from '@progress/kendo-file-saver';
2
+ import { getDocument, renderTextLayer } from 'pdfjs-dist';
3
+ /**
4
+ * @hidden
5
+ */
6
+ export const DEFAULT_ZOOM_LEVEL = 1.25;
7
+ const parsePdfFromBase64String = (base64String) => {
8
+ return atob(base64String.replace(/^(data:application\/pdf;base64,)/gi, ''));
9
+ };
10
+ const getDocumentParameters = (options) => {
11
+ let params = {
12
+ verbosity: 0
13
+ };
14
+ if (typeof options.data === 'string') {
15
+ params.data = parsePdfFromBase64String(options.data);
16
+ }
17
+ else if (typeof options.url === 'string') {
18
+ params.url = options.url;
19
+ }
20
+ else if (options.arrayBuffer instanceof ArrayBuffer) {
21
+ params = options.arrayBuffer;
22
+ }
23
+ else if (options.typedArray) {
24
+ params = options.typedArray;
25
+ }
26
+ return params;
27
+ };
28
+ /**
29
+ * @hidden
30
+ */
31
+ export const removeChildren = (dom) => {
32
+ while (dom.firstChild) {
33
+ dom.removeChild(dom.firstChild);
34
+ }
35
+ };
36
+ const appendPage = (dom, page, index) => {
37
+ if (index === 0) {
38
+ removeChildren(dom);
39
+ }
40
+ dom.appendChild(page);
41
+ };
42
+ /**
43
+ * @hidden
44
+ */
45
+ export const download = (options, fileName = 'Document', saveOptions = {}, onDownload) => {
46
+ if (options.pdf) {
47
+ options.pdf
48
+ .getData()
49
+ .then((data) => new Blob([data], { type: 'application/pdf' }))
50
+ .then((blob) => {
51
+ if (!onDownload(blob, fileName, saveOptions)) {
52
+ saveAs(blob, fileName, saveOptions);
53
+ }
54
+ })
55
+ .catch((reason) => {
56
+ options.error.call(undefined, reason);
57
+ });
58
+ }
59
+ };
60
+ /**
61
+ * @hidden
62
+ */
63
+ export const loadPDF = (options) => {
64
+ const params = getDocumentParameters(options);
65
+ const { dom, zoom, done, error } = options;
66
+ getDocument(params)
67
+ .promise.then((pdfDoc) => {
68
+ const pages = [];
69
+ for (let i = 1; i <= pdfDoc.numPages; i++) {
70
+ pages.push(pdfDoc.getPage(i));
71
+ }
72
+ return { pages, pdfDoc };
73
+ })
74
+ .then(({ pages, pdfDoc }) => {
75
+ Promise.all(pages)
76
+ .then((all) => all.map((page, i) => {
77
+ appendPage(dom, renderPage(page, zoom, error), i);
78
+ return page;
79
+ }))
80
+ .then((pdfPages) => {
81
+ done({ pdfPages, pdfDoc, zoom });
82
+ })
83
+ .catch((reason) => {
84
+ options.error(reason);
85
+ });
86
+ })
87
+ .catch((reason) => {
88
+ options.error(reason);
89
+ });
90
+ };
91
+ /**
92
+ * @hidden
93
+ */
94
+ export const reloadDocument = (params) => {
95
+ const { pdfDoc, zoom, dom, done, error } = params;
96
+ const pages = [];
97
+ for (let i = 1; i <= pdfDoc.numPages; i++) {
98
+ pages.push(pdfDoc.getPage(i));
99
+ }
100
+ Promise.all(pages)
101
+ .then((all) => all.map((page, i) => {
102
+ appendPage(dom, renderPage(page, zoom, error), i);
103
+ return page;
104
+ }))
105
+ .then(done)
106
+ .catch(error);
107
+ };
108
+ /**
109
+ * @hidden
110
+ */
111
+ export const print = (pages, done, error) => {
112
+ const dom = document.createElement('div');
113
+ let dones = pages.map(() => false);
114
+ pages.forEach((page, index) => {
115
+ const viewport = renderCanvas(page, (el) => {
116
+ dom.appendChild(el);
117
+ dones[index] = true;
118
+ if (dones.every(Boolean)) {
119
+ openPrintDialog(dom, viewport.width, viewport.height, done, error);
120
+ }
121
+ }, error);
122
+ });
123
+ };
124
+ const openPrintDialog = (dom, width, height, done, onError) => {
125
+ const printDialog = window.open('', '', 'innerWidth=' +
126
+ width +
127
+ ',innerHeight=' +
128
+ height +
129
+ 'location=no,titlebar=no,toolbar=no');
130
+ if (!printDialog || !printDialog.document) {
131
+ onError();
132
+ return;
133
+ }
134
+ if (printDialog) {
135
+ printDialog.document.body.appendChild(dom);
136
+ printDialog.focus();
137
+ setTimeout(() => {
138
+ printDialog.print();
139
+ done();
140
+ });
141
+ const onAfterPrint = () => {
142
+ printDialog.removeEventListener('afterprint', onAfterPrint);
143
+ printDialog.close();
144
+ };
145
+ printDialog.addEventListener('afterprint', onAfterPrint);
146
+ }
147
+ };
148
+ const renderCanvas = (page, done, error) => {
149
+ const viewport = page.getViewport({ scale: DEFAULT_ZOOM_LEVEL });
150
+ const styles = {};
151
+ const pageElement = createElement('div', '', styles);
152
+ const canvas = createElement('canvas', '', {
153
+ width: '100%',
154
+ height: '100%'
155
+ });
156
+ const canvasContext = canvas.getContext('2d');
157
+ canvas.height = viewport.height;
158
+ canvas.width = viewport.width;
159
+ pageElement.appendChild(canvas);
160
+ page.render({ canvasContext, viewport })
161
+ .promise.then(() => {
162
+ const printContent = new Image();
163
+ printContent.src = canvas.toDataURL();
164
+ pageElement.removeChild(canvas);
165
+ pageElement.appendChild(printContent);
166
+ printContent.width = canvas.width;
167
+ printContent.height = canvas.height;
168
+ const onload = () => {
169
+ printContent.removeEventListener('load', onload);
170
+ done(pageElement);
171
+ };
172
+ printContent.addEventListener('load', onload);
173
+ })
174
+ .catch(error);
175
+ return viewport;
176
+ };
177
+ const createElement = function (name, className, styles) {
178
+ const element = document.createElement(name);
179
+ if (className) {
180
+ element.className = className;
181
+ }
182
+ Object.keys(styles).forEach((key) => (element.style[key] = styles[key]));
183
+ return element;
184
+ };
185
+ const renderPage = (page, zoom, error) => {
186
+ const viewport = page.getViewport({ scale: zoom });
187
+ const styles = {
188
+ width: viewport.width + 'px',
189
+ height: viewport.height + 'px'
190
+ };
191
+ const pageElement = createElement('div', 'k-page', styles);
192
+ const canvas = createElement('canvas', '', {
193
+ width: '100%',
194
+ height: '100%'
195
+ });
196
+ const canvasContext = canvas.getContext('2d');
197
+ canvas.height = viewport.height;
198
+ canvas.width = viewport.width;
199
+ pageElement.appendChild(canvas);
200
+ page.render({ canvasContext, viewport })
201
+ .promise.then(() => {
202
+ page.getTextContent().then((textContent) => {
203
+ const textLayer = createElement('div', 'k-text-layer', styles);
204
+ renderTextLayer({
205
+ textContentSource: textContent,
206
+ container: textLayer,
207
+ viewport: viewport,
208
+ textDivs: []
209
+ })
210
+ .promise.then(() => {
211
+ pageElement.appendChild(textLayer);
212
+ })
213
+ .catch(error);
214
+ });
215
+ })
216
+ .catch(error);
217
+ return pageElement;
218
+ };
219
+ const searchMatchScrollLeftOffset = 0;
220
+ const searchMatchScrollTopOffset = -64;
221
+ const scrollToSearchMatch = (matchElement, ref) => {
222
+ if (!matchElement) {
223
+ return;
224
+ }
225
+ const closestCharElement = matchElement.closest('.k-text-char');
226
+ const closestTextElement = closestCharElement
227
+ ? closestCharElement.closest('span[role="presentation"]')
228
+ : null;
229
+ if (!closestTextElement) {
230
+ return;
231
+ }
232
+ const closestPageElement = closestTextElement.closest('.k-page');
233
+ if (!closestPageElement) {
234
+ return;
235
+ }
236
+ const scrollLeft = closestPageElement.offsetLeft +
237
+ -1 * ref.scroller.element.offsetLeft +
238
+ closestTextElement.offsetLeft +
239
+ searchMatchScrollLeftOffset;
240
+ const scrollTop = closestPageElement.offsetTop +
241
+ -1 * ref.scroller.element.offsetTop +
242
+ closestTextElement.offsetTop +
243
+ searchMatchScrollTopOffset;
244
+ ref.scroller.scrollTo(scrollLeft, scrollTop, { trackScrollEvent: false });
245
+ };
246
+ /**
247
+ * @hidden
248
+ */
249
+ export const goToNextSearchMatch = (ref) => {
250
+ ref.search.markNextMatch();
251
+ const matchElement = ref.search.getActiveMatchElement();
252
+ scrollToSearchMatch(matchElement, ref);
253
+ };
254
+ /**
255
+ * @hidden
256
+ */
257
+ export const goToPreviousSearchMatch = (ref) => {
258
+ ref.search.markPreviousMatch();
259
+ const matchElement = ref.search.getActiveMatchElement();
260
+ scrollToSearchMatch(matchElement, ref);
261
+ };
262
+ /**
263
+ * @hidden
264
+ */
265
+ export const calculateZoomLevel = (zoomLevel, zoomLevelType, currentZoom, dom) => {
266
+ const documentContainer = dom.closest('.k-pdf-viewer-canvas');
267
+ const page = dom.querySelector('.k-page');
268
+ const pageSize = { width: page.offsetWidth, height: page.offsetHeight };
269
+ let calculatedZoomLevel = zoomLevel;
270
+ if (zoomLevelType === 'ActualWidth') {
271
+ calculatedZoomLevel = 1;
272
+ }
273
+ else if (zoomLevelType === 'FitToWidth') {
274
+ calculatedZoomLevel =
275
+ documentContainer.offsetWidth / (pageSize.width / currentZoom);
276
+ }
277
+ else if (zoomLevelType === 'FitToPage') {
278
+ calculatedZoomLevel =
279
+ documentContainer.offsetHeight / (pageSize.height / currentZoom);
280
+ }
281
+ return calculatedZoomLevel;
282
+ };
283
+ /**
284
+ * Scrolls the PDFViewer document to the passed page number.
285
+ *
286
+ * @param rootElement The root HTML element of the PDFViewer component.
287
+ * @param pageNumber The page number.
288
+ */
289
+ export const scrollToPage = (rootElement, pageNumber) => {
290
+ const pages = rootElement.querySelectorAll('.k-page');
291
+ const page = pages[0];
292
+ if (page instanceof HTMLDivElement) {
293
+ const top = (page.offsetHeight + page.offsetTop) *
294
+ Math.max(0, Math.min(pageNumber, pages.length - 1));
295
+ const scrollElement = page.closest('.k-pdf-viewer-canvas');
296
+ if (scrollElement) {
297
+ scrollElement.scrollTo({ top, behavior: 'auto' });
298
+ }
299
+ }
300
+ };
301
+ /**
302
+ * A function which gives you the page number of the document according to the scroll position.
303
+ *
304
+ * @param rootElement The root HTML element of the PDFViewer component.
305
+ * @returns The page number.
306
+ */
307
+ export const currentPage = (rootElement) => {
308
+ const scrollElement = rootElement.querySelector('.k-pdf-viewer-canvas');
309
+ const page = rootElement.querySelector('.k-page');
310
+ return scrollElement && page
311
+ ? Math.floor(Math.round(scrollElement.scrollTop) /
312
+ (page.offsetHeight + page.offsetTop) +
313
+ 0.01)
314
+ : 0;
315
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@progress/kendo-pdfviewer-common",
3
3
  "description": "Kendo UI TypeScript package exporting functions for PDFViewer component",
4
- "version": "0.1.1",
4
+ "version": "0.1.2",
5
5
  "keywords": [
6
6
  "Kendo UI"
7
7
  ],