aboutsummaryrefslogtreecommitdiff
path: root/src/client/views/nodes/PDFBox.tsx
blob: eb45ea2734660414dbb6c47920f5a1a0809dda4c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import * as htmlToImage from "html-to-image";
import { action, computed, IReactionDisposer, observable, reaction, Reaction, trace } from 'mobx';
import { observer } from "mobx-react";
import 'react-image-lightbox/style.css';
import Measure from "react-measure";
//@ts-ignore
import { Document, Page } from "react-pdf";
import 'react-pdf/dist/Page/AnnotationLayer.css';
import { RouteStore } from "../../../server/RouteStore";
import { Utils } from '../../../Utils';
import { Annotation } from './Annotation';
import { FieldView, FieldViewProps } from './FieldView';
import "./PDFBox.scss";
import React = require("react");
import { SelectionManager } from "../../util/SelectionManager";
import { Cast, FieldValue, NumCast } from "../../../new_fields/Types";
import { Opt } from "../../../new_fields/Doc";
import { DocComponent } from "../DocComponent";
import { makeInterface } from "../../../new_fields/Schema";
import { positionSchema } from "./DocumentView";
import { pageSchema } from "./ImageBox";
import { ImageField, PdfField } from "../../../new_fields/URLField";
import { InkingControl } from "../InkingControl";

/** ALSO LOOK AT: Annotation.tsx, Sticky.tsx
 * This method renders PDF and puts all kinds of functionalities such as annotation, highlighting, 
 * area selection (I call it stickies), embedded ink node for directly annotating using a pen or 
 * mouse, and pagination. 
 *
 * 
 * HOW TO USE: 
 * AREA selection: 
 *          1) Click on Area button. 
 *          2) click on any part of the PDF, and drag to get desired sized area shape
 *          3) You can write on the area (hence the reason why it's called sticky)
 *          4) to make another area, you need to click on area button AGAIN. 
 * 
 * HIGHLIGHT: (Buggy. No multiline/multidiv text highlighting for now...)
 *          1) just click and drag on a text
 *          2) click highlight
 *          3) for annotation, just pull your cursor over to that text
 *          4) another method: click on highlight first and then drag on your desired text
 *          5) To make another highlight, you need to reclick on the button 
 * 
 * written by: Andrew Kim 
 */

type PdfDocument = makeInterface<[typeof positionSchema, typeof pageSchema]>;
const PdfDocument = makeInterface(positionSchema, pageSchema);

@observer
export class PDFBox extends DocComponent<FieldViewProps, PdfDocument>(PdfDocument) {
    public static LayoutString() { return FieldView.LayoutString(PDFBox); }

    private _mainDiv = React.createRef<HTMLDivElement>();

    @observable private _renderAsSvg = true;

    private _reactionDisposer: Opt<IReactionDisposer>;

    @observable private _perPageInfo: Object[] = []; //stores pageInfo
    @observable private _pageInfo: any = { area: [], divs: [], anno: [] }; //divs is array of objects linked to anno

    @observable private _currAnno: any = [];
    @observable private _interactive: boolean = false;
    @observable private _loaded: boolean = false;

    @computed private get curPage() { return FieldValue(this.Document.curPage, 1); }
    @computed private get thumbnailPage() { return Cast(this.props.Document.thumbnailPage, "number", -1); }

    componentDidMount() {
        this._reactionDisposer = reaction(
            () => [SelectionManager.SelectedDocuments().slice()],
            () => {
                if (this.curPage > 0 && this.thumbnailPage > 0 && this.curPage !== this.thumbnailPage && !this.props.isSelected()) {
                    this.saveThumbnail();
                    this._interactive = true;
                }
            },
            { fireImmediately: true });

    }

    componentWillUnmount() {
        if (this._reactionDisposer) {
            this._reactionDisposer();
        }
    }

    /**
     * highlighting helper function
     */
    makeEditableAndHighlight = (colour: string) => {
        var range, sel = window.getSelection();
        if (sel && sel.rangeCount && sel.getRangeAt) {
            range = sel.getRangeAt(0);
        }
        document.designMode = "on";
        if (!document.execCommand("HiliteColor", false, colour)) {
            document.execCommand("HiliteColor", false, colour);
        }

        if (range && sel) {
            sel.removeAllRanges();
            sel.addRange(range);

            let obj: Object = { parentDivs: [], spans: [] };
            //@ts-ignore
            if (range.commonAncestorContainer.className === 'react-pdf__Page__textContent') { //multiline highlighting case
                obj = this.highlightNodes(range.commonAncestorContainer.childNodes);
            } else { //single line highlighting case
                let parentDiv = range.commonAncestorContainer.parentElement;
                if (parentDiv) {
                    if (parentDiv.className === 'react-pdf__Page__textContent') { //when highlight is overwritten
                        obj = this.highlightNodes(parentDiv.childNodes);
                    } else {
                        parentDiv.childNodes.forEach((child) => {
                            if (child.nodeName === 'SPAN') {
                                //@ts-ignore
                                obj.parentDivs.push(parentDiv);
                                //@ts-ignore
                                child.id = "highlighted";
                                //@ts-ignore
                                obj.spans.push(child);
                                // child.addEventListener("mouseover", this.onEnter); //adds mouseover annotation handler
                            }
                        });
                    }
                }
            }
            this._pageInfo.divs.push(obj);

        }
        document.designMode = "off";
    }

    highlightNodes = (nodes: NodeListOf<ChildNode>) => {
        let temp = { parentDivs: [], spans: [] };
        nodes.forEach((div) => {
            div.childNodes.forEach((child) => {
                if (child.nodeName === 'SPAN') {
                    //@ts-ignore
                    temp.parentDivs.push(div);
                    //@ts-ignore
                    child.id = "highlighted";
                    //@ts-ignore
                    temp.spans.push(child);
                    // child.addEventListener("mouseover", this.onEnter); //adds mouseover annotation handler
                }
            });

        });
        return temp;
    }

    /**
     * when the cursor enters the highlight, it pops out annotation. ONLY WORKS FOR SINGLE DIV LINES
     */
    @action
    onEnter = (e: any) => {
        let span: HTMLSpanElement = e.toElement;
        let index: any;
        this._pageInfo.divs.forEach((obj: any) => {
            obj.spans.forEach((element: any) => {
                if (element === span) {
                    if (!index) {
                        index = this._pageInfo.divs.indexOf(obj);
                    }
                }
            });
        });

        if (this._pageInfo.anno.length >= index + 1) {
            if (this._currAnno.length === 0) {
                this._currAnno.push(this._pageInfo.anno[index]);
            }
        } else {
            if (this._currAnno.length === 0) { //if there are no current annotation
                let div = span.offsetParent;
                //@ts-ignore
                let divX = div.style.left;
                //@ts-ignore
                let divY = div.style.top;
                //slicing "px" from the end
                divX = divX.slice(0, divX.length - 2); //gets X of the DIV element (parent of Span)
                divY = divY.slice(0, divY.length - 2); //gets Y of the DIV element (parent of Span)
                let annotation = <Annotation key={Utils.GenerateGuid()} Span={span} X={divX} Y={divY - 300} Highlights={this._pageInfo.divs} Annotations={this._pageInfo.anno} CurrAnno={this._currAnno} />;
                this._pageInfo.anno.push(annotation);
                this._currAnno.push(annotation);
            }
        }

    }

    /**
     * highlight function for highlighting actual text. This works fine. 
     */
    highlight = (color: string) => {
        if (window.getSelection()) {
            try {
                if (!document.execCommand("hiliteColor", false, color)) {
                    this.makeEditableAndHighlight(color);
                }
            } catch (ex) {
                this.makeEditableAndHighlight(color);
            }
        }
    }

    /**
     * controls the area highlighting (stickies) Kinda temporary
     */
    onPointerDown = (e: React.PointerEvent) => {
        if (this.props.isSelected() && !InkingControl.Instance.selectedTool && e.buttons === 1) {
            if (e.altKey) {
                this._alt = true;
            } else {
                if (e.metaKey)
                    e.stopPropagation();
            }
            document.removeEventListener("pointerup", this.onPointerUp);
            document.addEventListener("pointerup", this.onPointerUp);
        }
        if (this.props.isSelected() && e.buttons === 2) {
            this._alt = true;
            document.removeEventListener("pointerup", this.onPointerUp);
            document.addEventListener("pointerup", this.onPointerUp);
        }
    }

    /**
     * controls area highlighting and partially highlighting. Kinda temporary
     */
    @action
    onPointerUp = (e: PointerEvent) => {
        this._alt = false;
        document.removeEventListener("pointerup", this.onPointerUp);
        if (this.props.isSelected()) {
            this.highlight("rgba(76, 175, 80, 0.3)"); //highlights to this default color. 
        }
        this._interactive = true;
    }



    @action
    saveThumbnail = () => {
        this._renderAsSvg = false;
        setTimeout(() => {
            let nwidth = FieldValue(this.Document.nativeWidth, 0);
            let nheight = FieldValue(this.Document.nativeHeight, 0);
            htmlToImage.toPng(this._mainDiv.current!, { width: nwidth, height: nheight, quality: 1 })
                .then(action((dataUrl: string) => {
                    this.props.Document.thumbnail = new ImageField(new URL(dataUrl));
                    this.props.Document.thumbnailPage = FieldValue(this.Document.curPage, -1);
                    this._renderAsSvg = true;
                }))
                .catch(function (error: any) {
                    console.error('oops, something went wrong!', error);
                });
        }, 250);
    }

    @action
    onLoaded = (page: any) => {
        // bcz: the number of pages should really be set when the document is imported.
        this.props.Document.numPages = page._transport.numPages;
        if (this._perPageInfo.length === 0) { //Makes sure it only runs once
            this._perPageInfo = [...Array(page._transport.numPages)];
        }
        this._loaded = true;
    }

    @action
    setScaling = (r: any) => {
        // bcz: the nativeHeight should really be set when the document is imported.
        //      also, the native dimensions could be different for different pages of the canvas
        //      so this design is flawed.
        var nativeWidth = FieldValue(this.Document.nativeWidth, 0);
        if (!FieldValue(this.Document.nativeHeight, 0)) {
            var nativeHeight = nativeWidth * r.entry.height / r.entry.width;
            this.props.Document.height = nativeHeight / nativeWidth * FieldValue(this.Document.width, 0);
            this.props.Document.nativeHeight = nativeHeight;
        }
    }
    renderHeight = 2400;
    @computed
    get pdfPage() {
        return <Page height={this.renderHeight} pageNumber={this.curPage} onLoadSuccess={this.onLoaded} />
    }
    @computed
    get pdfContent() {
        let page = this.curPage;
        const renderHeight = 2400;
        let pdfUrl = Cast(this.props.Document[this.props.fieldKey], PdfField);
        let xf = FieldValue(this.Document.nativeHeight, 0) / renderHeight;
        let body = NumCast(this.props.Document.nativeHeight) ?
            this.pdfPage :
            <Measure onResize={this.setScaling}>
                {({ measureRef }) =>
                    <div className="pdfBox-page" ref={measureRef}>
                        {this.pdfPage}
                    </div>
                }
            </Measure>;
        return <div className="pdfBox-contentContainer" key="container" style={{ transform: `scale(${xf}, ${xf})` }}>
            <Document file={window.origin + RouteStore.corsProxy + `/${pdfUrl}`} renderMode={this._renderAsSvg ? "svg" : "canvas"}>
                {body}
            </Document>
        </div >;
    }

    @computed
    get pdfRenderer() {
        let proxy = this._loaded ? (null) : this.imageProxyRenderer;
        let pdfUrl = Cast(this.props.Document[this.props.fieldKey], PdfField);
        if ((!this._interactive && proxy) || !pdfUrl) {
            return proxy;
        }
        return [
            this._pageInfo.area.filter(() => this._pageInfo.area).map((element: any) => element),
            this._currAnno.map((element: any) => element),
            this.pdfContent,
            proxy
        ];
    }

    @computed
    get imageProxyRenderer() {
        let thumbField = this.props.Document.thumbnail;
        if (thumbField) {
            let path = this.thumbnailPage !== this.curPage ? "https://image.flaticon.com/icons/svg/66/66163.svg" :
                thumbField instanceof ImageField ? thumbField.url.href : "http://cs.brown.edu/people/bcz/prairie.jpg";
            return <img src={path} width="100%" />;
        }
        return (null);
    }
    @observable _alt = false;
    @action
    onKeyDown = (e: React.KeyboardEvent) => {
        if (e.key === "Alt") {
            this._alt = true;
        }
    }
    @action
    onKeyUp = (e: React.KeyboardEvent) => {
        if (e.key === "Alt") {
            this._alt = false;
        }
    }
    render() {
        trace();
        let classname = "pdfBox-cont" + (this.props.isSelected() && !InkingControl.Instance.selectedTool && !this._alt ? "-interactive" : "");
        return (
            <div className={classname} tabIndex={0} ref={this._mainDiv} onPointerDown={this.onPointerDown} onKeyDown={this.onKeyDown} onKeyUp={this.onKeyUp} >
                {this.pdfRenderer}
            </div >
        );
    }

}