/
Viewer.vue
657 lines (564 loc) · 16.9 KB
/
Viewer.vue
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
<!--
- @copyright Copyright (c) 2019 John Molakvoæ <skjnldsv@protonmail.com>
-
- @author John Molakvoæ <skjnldsv@protonmail.com>
-
- @license GNU AGPL version 3 or any later version
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as
- published by the Free Software Foundation, either version 3 of the
- License, or (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see <http://www.gnu.org/licenses/>.
-
-->
<template>
<Modal
v-if="initiated || currentFile.modal"
id="viewer-content"
:class="{'icon-loading': !currentFile.loaded && !currentFile.failed}"
:view="currentFile.modal"
:enable-slideshow="hasPrevious || hasNext"
:spread-navigation="true"
:has-previous="hasPrevious"
:has-next="hasNext"
:title="currentFile.name"
:enable-swipe="canSwipe"
:size="isMobile || isFullscreen ? 'full' : 'large'"
:style="{width: shownSidebar ? `calc(100% - ${sidebarWidth}px)` : null}"
@close="close"
@previous="previous"
@next="next">
<!-- ACTIONS -->
<template #actions>
<ActionButton
v-if="OCA.Files && OCA.Files.Sidebar"
icon="icon-menu-sidebar-white-forced"
@click="showSidebar">
{{ t('viewer', 'Open sidebar') }}
</ActionButton>
</template>
<!-- PREVIOUS -->
<component
:is="previousFile.modal"
v-if="previousFile && !previousFile.failed"
:key="getPreviewIfAny(previousFile)"
ref="previous-content"
:dav-path="previousFile.path"
:file-id="previousFile.id"
:file-list="fileList"
:file-name="previousFile.name"
:mime="previousFile.mime"
:path="getPreviewIfAny(previousFile)"
class="hidden-visually file-view"
@error="previousFailed" />
<Error
v-else-if="previousFile"
class="hidden-visually"
:name="previousFile.name" />
<!-- CURRENT -->
<component
:is="currentFile.modal"
v-if="!currentFile.failed"
:key="getPreviewIfAny(currentFile)"
ref="content"
:active="true"
:can-swipe.sync="canSwipe"
:dav-path="currentFile.path"
:file-id="currentFile.id"
:file-list="fileList"
:file-name="currentFile.name"
:is-full-screen="isFullscreen"
:loaded.sync="currentFile.loaded"
:mime="currentFile.mime"
:path="getPreviewIfAny(currentFile)"
:sidebar-shown="shownSidebar"
class="file-view active"
@error="currentFailed" />
<Error
v-else
:name="currentFile.name" />
<!-- NEXT -->
<component
:is="nextFile.modal"
v-if="nextFile && !nextFile.failed"
:key="getPreviewIfAny(nextFile)"
ref="next-content"
:dav-path="nextFile.path"
:file-id="nextFile.id"
:file-list="fileList"
:file-name="nextFile.name"
:mime="nextFile.mime"
:path="getPreviewIfAny(nextFile)"
class="hidden-visually file-view"
@error="nextFailed" />
<Error
v-else-if="nextFile"
class="hidden-visually"
:name="nextFile.name" />
</Modal>
</template>
<script>
import { generateRemoteUrl } from '@nextcloud/router'
import ActionButton from 'nextcloud-vue/dist/Components/ActionButton'
import isFullscreen from 'nextcloud-vue/dist/Mixins/isFullscreen'
import isMobile from 'nextcloud-vue/dist/Mixins/isMobile'
import Modal from 'nextcloud-vue/dist/Components/Modal'
import Vue from 'vue'
import { extractFilePaths, sortCompare } from '../utils/fileUtils'
import Error from '../components/Error'
import File from '../models/file'
import getFileList from '../services/FileList'
import getFileInfo from '../services/FileInfo'
import PreviewUrl from '../mixins/PreviewUrl'
import cancelableRequest from '../utils/CancelableRequest'
export default {
name: 'Viewer',
components: {
ActionButton,
Modal,
Error,
},
mixins: [isMobile, isFullscreen, PreviewUrl],
data: () => ({
Viewer: OCA.Viewer.state,
handlers: OCA.Viewer.availableHandlers,
components: {},
mimeGroups: {},
registeredHandlers: [],
currentIndex: 0,
previousFile: {},
currentFile: {},
nextFile: {},
fileList: [],
isLoaded: false,
initiated: false,
// cancellable requests
cancelRequestFile: () => {},
cancelRequestFolder: () => {},
shownSidebar: false,
sidebarWidth: 0,
canSwipe: true,
standalone: !(OCA && OCA.Files && 'fileActions' in OCA.Files),
root: generateRemoteUrl(`dav/files/${OC.getCurrentUser().uid}`),
}),
computed: {
hasPrevious() {
return this.fileList.length > 1
},
hasNext() {
return this.fileList.length > 1
},
file() {
return this.Viewer.file
},
},
watch: {
// make sure any late external app can register handlers
// should not happens if external apps do not wait for
// the DOMContentLoaded event!
handlers: function() {
// make sure the viewer is done registering handlers
// so we only register handlers added AFTER the init
// of the viewer
if (this.isLoaded) {
console.error('Please do NOT wait for the DOMContentLoaded before registering your viewer handler')
const handler = this.handlers[this.handlers.length - 1]
// register all primary components mimes
this.registerHandler(handler)
// then register aliases. We need to have the components
// first so we can bind the alias to them.
this.registerHandlerAlias(handler)
}
},
file: function(path) {
// we got a valid path! Load file...
if (path.trim() !== '') {
console.info('Opening viewer for file ', path)
this.openFile(path)
} else {
// path is empty, closing!
this.close()
}
},
},
beforeMount() {
// register on load
document.addEventListener('DOMContentLoaded', event => {
// register all primary components mimes
this.handlers.forEach(handler => {
this.registerHandler(handler)
})
// then register aliases. We need to have the components
// first so we can bind the alias to them.
this.handlers.forEach(handler => {
this.registerHandlerAlias(handler)
})
this.isLoaded = true
})
window.addEventListener('resize', this.onResize)
if (this.standalone) {
console.debug('No OCA.Files found, viewer is now in standalone mode')
}
},
beforeDestroy() {
window.removeEventListener('resize', this.onResize)
},
methods: {
/**
* Open the view and display the clicked file
*
* @param {string} path the file path to open
*/
async openFile(path) {
// cancel any previous requests
this.cancelRequestFile()
this.cancelRequestFolder()
// do not open the same file again
if (path === this.currentFile.path) {
return
}
// initial loading start
this.initiated = true
const { request: fileRequest, cancel: cancelRequestFile } = cancelableRequest(getFileInfo)
const { request: folderRequest, cancel: cancelRequestFolder } = cancelableRequest(getFileList)
this.cancelRequestFile = cancelRequestFile
this.cancelRequestFolder = cancelRequestFolder
// extcrat needed info from path
const [dirPath, fileName] = extractFilePaths(path)
// prevent scrolling while opened
document.body.style.overflow = 'hidden'
// swap title with original one
const title = document.getElementsByTagName('head')[0].getElementsByTagName('title')[0]
if (title && !title.dataset.old) {
title.dataset.old = document.title
document.title = `${fileName} - ${OC.theme.title}`
}
try {
// retrieve, sort and store file List
let fileInfo = await fileRequest(path)
// get original mime
let mime = fileInfo.mime
// check if part of a group, if so retrieve full files list
const group = this.mimeGroups[mime]
if (group) {
const mimes = this.mimeGroups[group]
? this.mimeGroups[group]
: [mime]
// retrieve folder list
const fileList = await folderRequest(dirPath)
// filter out the unwanted mimes
const filteredFiles = fileList.filter(file => file.mime && mimes.indexOf(file.mime) !== -1)
// sort like the files list
// TODO: implement global sorting API
// https://github.com/nextcloud/server/blob/a83b79c5f8ab20ed9b4d751167417a65fa3c42b8/apps/files/lib/Controller/ApiController.php#L247
this.fileList = filteredFiles.sort((a, b) => sortCompare(a, b, 'basename'))
// store current position
this.currentIndex = this.fileList.findIndex(file => file.basename === fileName)
} else {
this.currentIndex = 0
this.fileList = [fileInfo]
}
// get saved fileInfo
fileInfo = this.fileList[this.currentIndex]
// override mimetype if existing alias
if (!this.components[mime]) {
mime = mime.split('/')[0]
}
// if we have a valid mime, show it!
if (this.components[mime]) {
this.currentFile = new File(fileInfo, mime, this.components[mime])
this.updatePreviousNext()
} else {
console.error(`The following file could not be displayed`, fileName, fileInfo)
this.close()
}
} catch (error) {
console.error(error)
}
},
/**
* Open the view and display the file from the file list
*
* @param {Object} fileInfo the opened file info
*/
openFileFromList(fileInfo) {
// override mimetype if existing alias
const mime = fileInfo.mime
this.currentFile = new File(fileInfo, mime, this.components[mime])
this.updatePreviousNext()
},
/**
* Update the previous and next file components
*/
updatePreviousNext() {
const prev = this.fileList[this.currentIndex - 1]
const next = this.fileList[this.currentIndex + 1]
if (prev) {
const mime = prev.mime
if (this.components[mime]) {
this.previousFile = new File(prev, mime, this.components[mime])
}
} else {
// RESET
this.previousFile = null
}
if (next) {
const mime = next.mime
if (this.components[mime]) {
this.nextFile = new File(next, mime, this.components[mime])
}
} else {
// RESET
this.nextFile = null
}
},
/**
* Registering possible new handers
*
* @param {Object} handler the handler to register
* @param {String} handler.id unique handler identifier
* @param {Array} handler.mimes list of valid mimes compatible with the handler
* @param {Object} handler.component a vuejs component to render when a file matching the mime list is opened
* @param {String} [handler.group] a group name to be associated with for the slideshow
*/
registerHandler(handler) {
// checking if handler is not already registered
if (handler.id && this.registeredHandlers.indexOf(handler.id) > -1) {
console.error(`The following handler is already registered`, handler)
return
}
// checking valid handler id
if (!handler.id || handler.id.trim() === '' || typeof handler.id !== 'string') {
console.error(`The following handler doesn't have a valid id`, handler)
return
}
// checking if no valid mimes data but alias. If so, skipping...
if (!(handler.mimes && Array.isArray(handler.mimes)) && handler.mimesAliases) {
return
}
// Nothing available to process! Failure
if (!(handler.mimes && Array.isArray(handler.mimes)) && !handler.mimesAliases) {
console.error(`The following handler doesn't have a valid mime array`, handler)
return
}
// checking valid handler component data
if ((!handler.component || typeof handler.component !== 'object')) {
console.error(`The following handler doesn't have a valid component`, handler)
return
}
// parsing mimes registration
if (handler.mimes) {
handler.mimes.forEach(mime => {
// checking valid mime
if (this.components[mime]) {
console.error(`The following mime is already registered`, mime, handler)
return
}
// register file action and groups
this.registerAction({ mime, group: handler.group })
// register mime's component
this.components[mime] = handler.component
Vue.component(handler.component.name, handler.component)
// set the handler as registered
this.registeredHandlers.push(handler.id)
})
}
},
registerHandlerAlias(handler) {
// parsing aliases registration
if (handler.mimesAliases) {
Object.keys(handler.mimesAliases).forEach(mime => {
if (handler.mimesAliases && typeof handler.mimesAliases !== 'object') {
console.error(`The following handler doesn't have a valid mimesAliases object`, handler)
return
}
// this is the targeted alias
const alias = handler.mimesAliases[mime]
// checking valid mime
if (this.components[mime]) {
console.error(`The following mime is already registered`, mime, handler)
return
}
if (!this.components[alias]) {
console.error(`The requested alias does not exists`, alias, mime, handler)
return
}
// register file action and groups if the request alias had a group
this.registerAction({ mime, group: this.mimeGroups[alias] })
// register mime's component
this.components[mime] = this.components[alias]
// set the handler as registered
this.registeredHandlers.push(handler.id)
})
}
},
registerAction({ mime, group }) {
if (!this.standalone) {
// unregistered handler, let's go!
OCA.Files.fileActions.registerAction({
name: 'view',
displayName: t('viewer', 'View'),
mime: mime,
permissions: OC.PERMISSION_READ,
actionHandler: (name, { dir }) => {
// replace potential leading double slashes
OCA.Viewer.open(`${dir}/${name}`.replace(/^\/\//, '/'))
},
})
OCA.Files.fileActions.setDefault(mime, 'view')
}
// register groups
if (group) {
this.mimeGroups[mime] = group
// init if undefined
if (!this.mimeGroups[group]) {
this.mimeGroups[group] = []
}
this.mimeGroups[group].push(mime)
}
},
/**
* Close the viewer
*/
close() {
// reset all properties
OCA.Viewer.close()
this.currentFile = {}
this.currentModal = null
this.fileList = []
this.initiated = false
this.hideAppsSidebar()
// cancel requests
this.cancelRequestFile()
this.cancelRequestFolder()
// restore default
document.body.style.overflow = null
// swap back original title
const title = document.getElementsByTagName('head')[0].getElementsByTagName('title')[0]
if (title && title.dataset.old) {
document.title = title.dataset.old
delete title.dataset.old
}
},
/**
* Open previous available file
*/
previous() {
this.currentIndex--
if (this.currentIndex < 0) {
this.currentIndex = this.fileList.length - 1
}
this.openFileFromList(this.fileList[this.currentIndex])
},
/**
* Open next available file
*/
next() {
this.currentIndex++
if (this.currentIndex > this.fileList.length - 1) {
this.currentIndex = 0
}
this.openFileFromList(this.fileList[this.currentIndex])
},
/**
* Failures handlers
*/
previousFailed() {
this.previousFile.failed = true
},
currentFailed() {
this.currentFile.failed = true
},
nextFailed() {
this.nextFile.failed = true
},
/**
* Show the sharing sidebar
*/
showSidebar() {
// Open the sidebar sharing tab
OCA.Files.App.fileList.showDetailsView(this.currentFile.basename)
this.showAppsSidebar()
},
showAppsSidebar() {
this.shownSidebar = true
const sidebar = document.getElementById('app-sidebar')
if (sidebar) {
sidebar.classList.add('app-sidebar--full')
}
// overriding closing function
const origHideAppsSidebar = OC.Apps.hideAppSidebar
OC.Apps.hideAppSidebar = ($el) => {
this.hideAppsSidebar()
origHideAppsSidebar($el)
}
this.sidebarWidth = sidebar.offsetWidth
},
hideAppsSidebar() {
this.shownSidebar = false
const sidebar = document.getElementById('app-sidebar')
if (sidebar) {
sidebar.classList.remove('app-sidebar--full')
}
},
onResize(event) {
// update sidebar width
const sidebar = document.getElementById('app-sidebar')
if (sidebar) {
this.sidebarWidth = sidebar.offsetWidth
}
},
},
}
</script>
<style lang="scss">
#viewer-content.modal-mask {
transition: width ease 100ms;
.modal-container {
display: flex !important;
width: auto !important;
border-radius: 0 !important;
// let the mime components manage their own background-color
background-color: transparent;
justify-content: center;
align-items: center;
}
}
.component-fade-enter-active, .component-fade-leave-active {
transition: opacity .3s ease;
}
.component-fade-enter, .component-fade-leave-to {
opacity: 0;
}
// force white icon
.icon-menu-sidebar-white-forced {
background-image: url('~Assets/menu-sidebar-white.svg');
}
.file-view {
transition: height 100ms ease,
width 100ms ease;
}
#app-sidebar.app-sidebar--full {
position: fixed;
top: 0;
height: 100%;
z-index: 2025;
.thumbnailContainer {
display: none;
}
}
// put autocomplete over full sidebar
// TODO: remove when new sharing sidebar (18)
// is the min-version of viewer
.ui-autocomplete {
z-index: 2050 !important;
}
</style>