summaryrefslogtreecommitdiff
path: root/addons/mail/static/src/components/attachment_viewer/attachment_viewer.js
blob: 30755fd916b710ab0a015f80be67fd07ad59b61b (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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
odoo.define('mail/static/src/components/attachment_viewer/attachment_viewer.js', function (require) {
'use strict';

const useRefs = require('mail/static/src/component_hooks/use_refs/use_refs.js');
const useShouldUpdateBasedOnProps = require('mail/static/src/component_hooks/use_should_update_based_on_props/use_should_update_based_on_props.js');
const useStore = require('mail/static/src/component_hooks/use_store/use_store.js');

const { Component, QWeb } = owl;
const { useRef } = owl.hooks;

const MIN_SCALE = 0.5;
const SCROLL_ZOOM_STEP = 0.1;
const ZOOM_STEP = 0.5;

class AttachmentViewer extends Component {

    /**
     * @override
     */
    constructor(...args) {
        super(...args);
        this.MIN_SCALE = MIN_SCALE;
        useShouldUpdateBasedOnProps();
        useStore(props => {
            const attachmentViewer = this.env.models['mail.attachment_viewer'].get(props.localId);
            return {
                attachment: attachmentViewer && attachmentViewer.attachment
                    ? attachmentViewer.attachment.__state
                    : undefined,
                attachments: attachmentViewer
                    ? attachmentViewer.attachments.map(attachment => attachment.__state)
                    : [],
                attachmentViewer: attachmentViewer ? attachmentViewer.__state : undefined,
            };
        });
        /**
         * Used to ensure that the ref is always up to date, which seems to be needed if the element
         * has a t-key, which was added to force the rendering of a new element when the src of the image changes.
         * This was made to remove the display of the previous image as soon as the src changes.
         */
        this._getRefs = useRefs();
        /**
         * Determine whether the user is currently dragging the image.
         * This is useful to determine whether a click outside of the image
         * should close the attachment viewer or not.
         */
        this._isDragging = false;
        /**
         * Reference of the zoomer node. Useful to apply translate
         * transformation on image visualisation.
         */
        this._zoomerRef = useRef('zoomer');
        /**
         * Tracked translate transformations on image visualisation. This is
         * not observed with `useStore` because they are used to compute zoomer
         * style, and this is changed directly on zoomer for performance
         * reasons (overhead of making vdom is too significant for each mouse
         * position changes while dragging)
         */
        this._translate = { x: 0, y: 0, dx: 0, dy: 0 };
        this._onClickGlobal = this._onClickGlobal.bind(this);
    }

    mounted() {
        this.el.focus();
        this._handleImageLoad();
        document.addEventListener('click', this._onClickGlobal);
    }

    /**
     * When a new image is displayed, show a spinner until it is loaded.
     */
    patched() {
        this._handleImageLoad();
    }

    willUnmount() {
        document.removeEventListener('click', this._onClickGlobal);
    }

    //--------------------------------------------------------------------------
    // Public
    //--------------------------------------------------------------------------

    /**
     * @returns {mail.attachment_viewer}
     */
    get attachmentViewer() {
        return this.env.models['mail.attachment_viewer'].get(this.props.localId);
    }

    /**
     * Compute the style of the image (scale + rotation).
     *
     * @returns {string}
     */
    get imageStyle() {
        const attachmentViewer = this.attachmentViewer;
        let style = `transform: ` +
            `scale3d(${attachmentViewer.scale}, ${attachmentViewer.scale}, 1) ` +
            `rotate(${attachmentViewer.angle}deg);`;

        if (attachmentViewer.angle % 180 !== 0) {
            style += `` +
                `max-height: ${window.innerWidth}px; ` +
                `max-width: ${window.innerHeight}px;`;
        } else {
            style += `` +
                `max-height: 100%; ` +
                `max-width: 100%;`;
        }
        return style;
    }

    /**
     * Mandatory method for dialog components.
     * Prevent closing the dialog when clicking on the mask when the user is
     * currently dragging the image.
     *
     * @returns {boolean}
     */
    isCloseable() {
        return !this._isDragging;
    }

    //--------------------------------------------------------------------------
    // Private
    //--------------------------------------------------------------------------

    /**
     * Close the dialog with this attachment viewer.
     *
     * @private
     */
    _close() {
        this.attachmentViewer.close();
    }

    /**
     * Download the attachment.
     *
     * @private
     */
    _download() {
        const id = this.attachmentViewer.attachment.id;
        this.env.services.navigate(`/web/content/ir.attachment/${id}/datas`, { download: true });
    }

    /**
     * Determine whether the current image is rendered for the 1st time, and if
     * that's the case, display a spinner until loaded.
     *
     * @private
     */
    _handleImageLoad() {
        if (!this.attachmentViewer || !this.attachmentViewer.attachment) {
            return;
        }
        const refs = this._getRefs();
        const image = refs[`image_${this.attachmentViewer.attachment.id}`];
        if (
            this.attachmentViewer.attachment.fileType === 'image' &&
            (!image || !image.complete)
        ) {
            this.attachmentViewer.update({ isImageLoading: true });
        }
    }

    /**
     * Display the previous attachment in the list of attachments.
     *
     * @private
     */
    _next() {
        const attachmentViewer = this.attachmentViewer;
        const index = attachmentViewer.attachments.findIndex(attachment =>
            attachment === attachmentViewer.attachment
        );
        const nextIndex = (index + 1) % attachmentViewer.attachments.length;
        attachmentViewer.update({
            attachment: [['link', attachmentViewer.attachments[nextIndex]]],
        });
    }

    /**
     * Display the previous attachment in the list of attachments.
     *
     * @private
     */
    _previous() {
        const attachmentViewer = this.attachmentViewer;
        const index = attachmentViewer.attachments.findIndex(attachment =>
            attachment === attachmentViewer.attachment
        );
        const nextIndex = index === 0
            ? attachmentViewer.attachments.length - 1
            : index - 1;
        attachmentViewer.update({
            attachment: [['link', attachmentViewer.attachments[nextIndex]]],
        });
    }

    /**
     * Prompt the browser print of this attachment.
     *
     * @private
     */
    _print() {
        const printWindow = window.open('about:blank', '_new');
        printWindow.document.open();
        printWindow.document.write(`
            <html>
                <head>
                    <script>
                        function onloadImage() {
                            setTimeout('printImage()', 10);
                        }
                        function printImage() {
                            window.print();
                            window.close();
                        }
                    </script>
                </head>
                <body onload='onloadImage()'>
                    <img src="${this.attachmentViewer.attachment.defaultSource}" alt=""/>
                </body>
            </html>`);
        printWindow.document.close();
    }

    /**
     * Rotate the image by 90 degrees to the right.
     *
     * @private
     */
    _rotate() {
        this.attachmentViewer.update({ angle: this.attachmentViewer.angle + 90 });
    }

    /**
     * Stop dragging interaction of the user.
     *
     * @private
     */
    _stopDragging() {
        this._isDragging = false;
        this._translate.x += this._translate.dx;
        this._translate.y += this._translate.dy;
        this._translate.dx = 0;
        this._translate.dy = 0;
        this._updateZoomerStyle();
    }

    /**
     * Update the style of the zoomer based on translate transformation. Changes
     * are directly applied on zoomer, instead of triggering re-render and
     * defining them in the template, for performance reasons.
     *
     * @private
     * @returns {string}
     */
    _updateZoomerStyle() {
        const attachmentViewer = this.attachmentViewer;
        const refs = this._getRefs();
        const image = refs[`image_${this.attachmentViewer.attachment.id}`];
        const tx = image.offsetWidth * attachmentViewer.scale > this._zoomerRef.el.offsetWidth
            ? this._translate.x + this._translate.dx
            : 0;
        const ty = image.offsetHeight * attachmentViewer.scale > this._zoomerRef.el.offsetHeight
            ? this._translate.y + this._translate.dy
            : 0;
        if (tx === 0) {
            this._translate.x = 0;
        }
        if (ty === 0) {
            this._translate.y = 0;
        }
        this._zoomerRef.el.style = `transform: ` +
            `translate(${tx}px, ${ty}px)`;
    }

    /**
     * Zoom in the image.
     *
     * @private
     * @param {Object} [param0={}]
     * @param {boolean} [param0.scroll=false]
     */
    _zoomIn({ scroll = false } = {}) {
        this.attachmentViewer.update({
            scale: this.attachmentViewer.scale + (scroll ? SCROLL_ZOOM_STEP : ZOOM_STEP),
        });
        this._updateZoomerStyle();
    }

    /**
     * Zoom out the image.
     *
     * @private
     * @param {Object} [param0={}]
     * @param {boolean} [param0.scroll=false]
     */
    _zoomOut({ scroll = false } = {}) {
        if (this.attachmentViewer.scale === MIN_SCALE) {
            return;
        }
        const unflooredAdaptedScale = (
            this.attachmentViewer.scale -
            (scroll ? SCROLL_ZOOM_STEP : ZOOM_STEP)
        );
        this.attachmentViewer.update({
            scale: Math.max(MIN_SCALE, unflooredAdaptedScale),
        });
        this._updateZoomerStyle();
    }

    /**
     * Reset the zoom scale of the image.
     *
     * @private
     */
    _zoomReset() {
        this.attachmentViewer.update({ scale: 1 });
        this._updateZoomerStyle();
    }

    //--------------------------------------------------------------------------
    // Handlers
    //--------------------------------------------------------------------------

    /**
     * Called when clicking on mask of attachment viewer.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClick(ev) {
        if (this._isDragging) {
            return;
        }
        // TODO: clicking on the background should probably be handled by the dialog?
        // task-2092965
        this._close();
    }

    /**
     * Called when clicking on cross icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickClose(ev) {
        this._close();
    }

    /**
     * Called when clicking on download icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickDownload(ev) {
        ev.stopPropagation();
        this._download();
    }

    /**
     * @private
     * @param {MouseEvent} ev
     */
    _onClickGlobal(ev) {
        if (!this._isDragging) {
            return;
        }
        ev.stopPropagation();
        this._stopDragging();
    }

    /**
     * Called when clicking on the header. Stop propagation of event to prevent
     * closing the dialog.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickHeader(ev) {
        ev.stopPropagation();
    }

    /**
     * Called when clicking on image. Stop propagation of event to prevent
     * closing the dialog.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickImage(ev) {
        if (this._isDragging) {
            return;
        }
        ev.stopPropagation();
    }

    /**
     * Called when clicking on next icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickNext(ev) {
        ev.stopPropagation();
        this._next();
    }

    /**
     * Called when clicking on previous icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickPrevious(ev) {
        ev.stopPropagation();
        this._previous();
    }

    /**
     * Called when clicking on print icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickPrint(ev) {
        ev.stopPropagation();
        this._print();
    }

    /**
     * Called when clicking on rotate icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickRotate(ev) {
        ev.stopPropagation();
        this._rotate();
    }

    /**
     * Called when clicking on embed video player. Stop propagation to prevent
     * closing the dialog.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickVideo(ev) {
        ev.stopPropagation();
    }

    /**
     * Called when clicking on zoom in icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickZoomIn(ev) {
        ev.stopPropagation();
        this._zoomIn();
    }

    /**
     * Called when clicking on zoom out icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickZoomOut(ev) {
        ev.stopPropagation();
        this._zoomOut();
    }

    /**
     * Called when clicking on reset zoom icon.
     *
     * @private
     * @param {MouseEvent} ev
     */
    _onClickZoomReset(ev) {
        ev.stopPropagation();
        this._zoomReset();
    }

    /**
     * @private
     * @param {KeyboardEvent} ev
     */
    _onKeydown(ev) {
        switch (ev.key) {
            case 'ArrowRight':
                this._next();
                break;
            case 'ArrowLeft':
                this._previous();
                break;
            case 'Escape':
                this._close();
                break;
            case 'q':
                this._close();
                break;
            case 'r':
                this._rotate();
                break;
            case '+':
                this._zoomIn();
                break;
            case '-':
                this._zoomOut();
                break;
            case '0':
                this._zoomReset();
                break;
            default:
                return;
        }
        ev.stopPropagation();
    }

    /**
     * Called when new image has been loaded
     *
     * @private
     * @param {Event} ev
     */
    _onLoadImage(ev) {
        ev.stopPropagation();
        this.attachmentViewer.update({ isImageLoading: false });
    }

    /**
     * @private
     * @param {DragEvent} ev
     */
    _onMousedownImage(ev) {
        if (this._isDragging) {
            return;
        }
        if (ev.button !== 0) {
            return;
        }
        ev.stopPropagation();
        this._isDragging = true;
        this._dragstartX = ev.clientX;
        this._dragstartY = ev.clientY;
    }

    /**
     * @private
     * @param {DragEvent}
     */
    _onMousemoveView(ev) {
        if (!this._isDragging) {
            return;
        }
        this._translate.dx = ev.clientX - this._dragstartX;
        this._translate.dy = ev.clientY - this._dragstartY;
        this._updateZoomerStyle();
    }

    /**
     * @private
     * @param {Event} ev
     */
    _onWheelImage(ev) {
        ev.stopPropagation();
        if (!this.el) {
            return;
        }
        if (ev.deltaY > 0) {
            this._zoomOut({ scroll: true });
        } else {
            this._zoomIn({ scroll: true });
        }
    }

}

Object.assign(AttachmentViewer, {
    props: {
        localId: String,
    },
    template: 'mail.AttachmentViewer',
});

QWeb.registerComponent('AttachmentViewer', AttachmentViewer);

return AttachmentViewer;

});