-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathFilePicker.vue
More file actions
387 lines (342 loc) · 10.1 KB
/
FilePicker.vue
File metadata and controls
387 lines (342 loc) · 10.1 KB
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
<!--
- SPDX-FileCopyrightText: 2023-2024 Nextcloud GmbH and Nextcloud contributors
- SPDX-License-Identifier: AGPL-3.0-or-later
-->
<template>
<NcDialog
v-model:open="isOpen"
:buttons="dialogButtons"
:name="name"
size="large"
contentClasses="file-picker__content"
dialogClasses="file-picker"
navigationClasses="file-picker__navigation"
@update:open="handleClose">
<template #navigation="{ isCollapsed }">
<FilePickerNavigation
v-model:currentView="currentView"
v-model:filterString="filterString"
:isCollapsed
:disabledNavigation />
</template>
<div class="file-picker__main">
<!-- Header title / file list breadcrumbs -->
<FilePickerBreadcrumbs
v-if="currentView === 'files'"
v-model:path="currentPath"
:showMenu="!noMenu"
@createNode="onCreateFolder" />
<div v-else class="file-picker__view">
<h3>{{ viewHeadline }}</h3>
</div>
<!-- File list -->
<!-- If loading or files found show file list, otherwise show empty content-->
<FileList
v-if="isLoading || filteredFiles.length > 0"
v-model:path="currentPath"
v-model:selectedFiles="selectedFiles"
:allowPickDirectory="allowPickDirectory"
:currentView="currentView"
:files="filteredFiles"
:multiselect="multiselect"
:loading="isLoading"
:name="viewHeadline"
:canPick="canPickFn"
@update:path="currentView = 'files'" />
<NcEmptyContent
v-else-if="filterString"
:name="t('No matching files')"
:description="t('No files matching your filter were found.')">
<template #icon>
<IconFile />
</template>
</NcEmptyContent>
<NcEmptyContent
v-else
:name="t('No files in here')"
:description="noFilesDescription">
<template #icon>
<IconFile />
</template>
</NcEmptyContent>
</div>
</NcDialog>
</template>
<script setup lang="ts">
import type { INode } from '@nextcloud/files'
import type { IFilesViewId } from '../../composables/views.ts'
import type { IDialogButton, IFilePickerButton, IFilePickerButtonFactory, IFilePickerCanPick, IFilePickerFilter } from '../types.ts'
import { emit as emitOnEventBus } from '@nextcloud/event-bus'
import { computed, onMounted, ref, shallowRef, toRef, watch } from 'vue'
import NcDialog from '@nextcloud/vue/components/NcDialog'
import NcEmptyContent from '@nextcloud/vue/components/NcEmptyContent'
import IconFile from 'vue-material-design-icons/File.vue'
import FileList from './FileList.vue'
import FilePickerBreadcrumbs from './FilePickerBreadcrumbs.vue'
import FilePickerNavigation from './FilePickerNavigation.vue'
import { useDAVFiles } from '../../composables/dav.ts'
import { useFilesSettings } from '../../composables/filesSettings.ts'
import { useMimeFilter } from '../../composables/mime.ts'
import { showError } from '../../toast.ts'
import { t } from '../../utils/l10n.ts'
import { logger } from '../../utils/logger.ts'
const props = withDefaults(defineProps<{
/** Buttons to be displayed */
buttons: IFilePickerButton[] | IFilePickerButtonFactory
/** The name of file picker dialog (heading) */
name: string
/**
* Can directories be picked
*
* @default false
*/
allowPickDirectory?: boolean
/**
* Can new Files/folders be created
*
* @default false
*/
noMenu?: boolean
/**
* Is the navigation disabled
*/
disabledNavigation?: boolean
/**
* Custom filter function used to filter pickable files
*/
filterFn?: IFilePickerFilter
/**
* Custom function to decide if a node can be picked
*/
canPickFn?: IFilePickerCanPick
/**
* List of allowed mime types
* You can use placeholders for e.g. allowing all subtypes of images `['image/*']`.
* Note that if unset all files are allowed, which is the same as passing `['*∕*']`
*
* @default []
*/
mimetypeFilter?: string[]
/**
* Is it allowed to pick multiple files
*/
multiselect?: boolean
/**
* The initial path of the file picker
*
* @default '/'
*/
path?: string
}>(), {
allowPickDirectory: false,
noMenu: false,
disabledNavigation: false,
filterFn: undefined,
canPickFn: undefined,
mimetypeFilter: () => [],
multiselect: false,
path: undefined,
})
const emit = defineEmits<{
(e: 'close', v?: INode[]): void
}>()
const isOpen = ref(true)
/**
* Name of the currently active view
*/
const currentView = ref<IFilesViewId>('files')
/**
* Last path navigated to using the file picker
* (required as sessionStorage is not reactive)
*/
const savedPath = ref(window?.sessionStorage.getItem('NC.FilePicker.LastPath') || '/')
/**
* The path the user manually navigated to using this filepicker instance
*/
const navigatedPath = ref('')
/**
* The current path that should be picked from
*/
const currentPath = computed({
get: () => {
// Only use the path for the files view as favorites and recent only works on the root
return currentView.value === 'files' ? navigatedPath.value || props.path || savedPath.value : '/'
},
set: (path: string) => {
// forward setting the current path to the navigated path
navigatedPath.value = path
},
})
/**
* All currently selected files
*/
const selectedFiles = shallowRef<INode[]>([])
const {
files,
folder: currentFolder,
isLoading,
loadFiles,
createDirectory,
} = useDAVFiles(currentView, currentPath)
// Save the navigated path to the session storage on change
watch([navigatedPath], () => {
if (props.path === undefined && navigatedPath.value) {
window.sessionStorage.setItem('NC.FilePicker.LastPath', navigatedPath.value)
}
// Reset selected files
selectedFiles.value = []
})
/**
* Flag that is set when a button was clicked to prevent the default close event to be emitted
* This is needed as `handleButtonClick` is async and thus might execute after NcDialog already closed
*/
let isHandlingCallback = false
/**
* Map buttons to Dialog buttons by wrapping the callback function to pass the selected files
*/
const dialogButtons = computed(() => {
const nodes = selectedFiles.value.length === 0
&& props.allowPickDirectory
&& currentFolder.value
? [currentFolder.value]
: selectedFiles.value
const buttons = typeof props.buttons === 'function'
? props.buttons(nodes, currentPath.value, currentView.value)
: props.buttons
return buttons.map((button) => ({
...button,
disabled: button.disabled || isLoading.value,
callback: () => {
// lock default close handling
isHandlingCallback = true
handleButtonClick(button.callback, nodes)
},
} satisfies IDialogButton))
})
/**
* @param callback - Callback of the button
* @param nodes - Currently selected nodes
*/
async function handleButtonClick(callback: IFilePickerButton['callback'], nodes: INode[]) {
await callback(nodes)
emit('close', nodes)
// Unlock close
isHandlingCallback = false
}
/**
* Headline to be used on the current view
*/
const viewHeadline = computed(() => currentView.value === 'favorites' ? t('Favorites') : (currentView.value === 'recent' ? t('Recent') : ''))
/**
* A string used to filter files in current view
*/
const filterString = ref('')
const { isSupportedMimeType } = useMimeFilter(toRef(props, 'mimetypeFilter')) // vue 3.3 will allow cleaner syntax of toRef(() => props.mimetypeFilter)
onMounted(() => loadFiles())
const { showHiddenFiles } = useFilesSettings()
/**
* The files list filtered by the current value of the filter input
*/
const filteredFiles = computed(() => {
let filtered = files.value
if (!showHiddenFiles.value) {
// Hide hidden files if not configured otherwise
filtered = filtered.filter((file) => !file.basename.startsWith('.'))
}
if (props.mimetypeFilter.length > 0) {
// filter by mime type but always include folders to navigate
filtered = filtered.filter((file) => file.type === 'folder' || (file.mime && isSupportedMimeType(file.mime)))
}
if (filterString.value) {
filtered = filtered.filter((file) => file.basename.toLowerCase().includes(filterString.value.toLowerCase()))
}
if (props.filterFn) {
filtered = filtered.filter((f) => props.filterFn!(f as INode))
}
return filtered
})
/**
* If no files are found in the current view this message will be shown in the EmptyContent
*/
const noFilesDescription = computed(() => {
if (currentView.value === 'files') {
return t('Upload some content or sync with your devices!')
} else if (currentView.value === 'recent') {
return t('Files and folders you recently modified will show up here.')
} else {
return t('Files and folders you mark as favorite will show up here.')
}
})
/**
* Handle creating new folder (breadcrumb menu)
* This will create the folder using WebDAV, reload the directory content and signal the directory creation to fhe files app
*
* @param name The new folder name
*/
async function onCreateFolder(name: string) {
try {
const folder = await createDirectory(name)
navigatedPath.value = folder.path
// emit event bus to force files app to reload that file if needed
emitOnEventBus('files:node:created', files.value.filter((file) => file.basename === name)[0])
} catch (error) {
logger.warn('Could not create new folder', { name, error })
// show error to user
showError(t('Could not create the new folder'))
}
}
/**
* Handle closing the file picker
*
* @param open If the dialog is open
*/
function handleClose(open: boolean) {
if (!open && !isHandlingCallback) {
emit('close')
}
}
</script>
<style scoped lang="scss">
.file-picker {
&__view {
height: 50px; // align with breadcrumbs
display: flex;
justify-content: start;
align-items: center;
h3 {
font-weight: bold;
height: fit-content;
margin: 0;
}
}
&__main {
box-sizing: border-box;
width: 100%;
display: flex;
flex-direction: column;
// Auto fit height
min-height: 0;
flex: 1;
// align with navigation on smaller screens
padding-inline: 2px;
* {
box-sizing: border-box;
}
}
}
:deep(.file-picker) {
// Dialog is max. 900px wide so the best looking height seems to be 800px
height: min(80vh, 800px)!important;
}
@media (max-width: 512px) {
:deep(.file-picker) {
// below 512px the modal is fullscreen so we use 100% height - margin of heading (4px + 12px) - height of heading (default-clickable-area)
height: calc(100% - 16px - var(--default-clickable-area))!important;
}
}
:deep(.file-picker__content) {
display: flex;
flex-direction: column;
overflow: hidden;
}
</style>