FileManager.vue 35.2 KB
Newer Older
1
<template lang='pug'>
2
q-layout.fileman(view='hHh lpR lFr', container)
3 4 5
  q-header.card-header
    q-toolbar(dark)
      q-icon(name='img:/_assets/icons/fluent-folder.svg', left, size='md')
6
      span {{ t(`fileman.title`) }}
7
    q-toolbar(dark)
8 9 10
      q-btn.q-mr-sm.acrylic-btn(
        flat
        color='white'
11 12
        :label='commonStore.locale'
        :aria-label='commonStore.locale'
13 14
        style='height: 40px;'
        )
15
        locale-selector-menu
16 17 18 19 20 21 22
      q-input(
        dark
        v-model='state.search'
        standout='bg-white text-dark'
        dense
        ref='searchField'
        style='width: 100%;'
23
        :label='t(`fileman.searchFolder`)'
24
        :debounce='500'
25
        )
26
        template(#prepend)
27
          q-icon(name='las la-search')
28
        template(#append)
29 30 31 32 33 34 35 36 37 38 39
          q-icon.cursor-pointer(
            name='las la-times'
            @click='state.search=``'
            v-if='state.search.length > 0'
            :color='$q.dark.isActive ? `blue` : `grey-4`'
            )
    q-toolbar(dark)
      q-space
      q-btn(
        flat
        dense
40 41
        no-caps
        color='red-3'
42 43 44 45 46
        :aria-label='t(`common.actions.close`)'
        icon='las la-times'
        @click='close'
        )
        q-tooltip(anchor='bottom middle', self='top middle') {{t(`common.actions.close`)}}
47
  q-drawer.fileman-left(:model-value='true', :width='350')
48 49 50 51
    q-scroll-area(
      :thumb-style='thumbStyle'
      :bar-style='barStyle'
      style='height: 100%;'
52
      )
53 54 55 56 57 58 59 60 61 62
      .q-px-md.q-pb-sm
        tree(
          ref='treeComp'
          :nodes='state.treeNodes'
          :roots='state.treeRoots'
          v-model:selected='state.currentFolderId'
          @lazy-load='treeLazyLoad'
          :use-lazy-load='true'
          @context-action='treeContextAction'
          :display-mode='state.displayMode'
63
        )
64 65 66 67 68 69 70 71 72
  q-drawer.fileman-right(:model-value='$q.screen.gt.md', :width='350', side='right')
    q-scroll-area(
      :thumb-style='thumbStyle'
      :bar-style='barStyle'
      style='height: 100%;'
      )
      .q-pa-md
        template(v-if='currentFileDetails')
          q-img.rounded-borders.q-mb-md(
73
            :src='currentFileDetails.thumbnail'
74 75 76 77
            width='100%'
            fit='cover'
            :ratio='16/10'
            no-spinner
78
          )
79 80
          .fileman-details-row(
            v-for='item of currentFileDetails.items'
81
            :key='item.id'
82
            )
83 84
            label {{ item.label }}
            span {{ item.value }}
85 86 87 88 89 90 91 92 93 94
          template(v-if='insertMode')
            q-separator.q-my-md
            q-btn.full-width(
              @click='insertItem()'
              :label='t(`common.actions.insert`)'
              color='primary'
              icon='las la-plus-circle'
              push
              padding='sm'
              )
95
  q-page-container
96
    q-page.fileman-center.column
97 98 99 100
      //- TOOLBAR -----------------------------------------------------
      q-toolbar.fileman-toolbar
        template(v-if='state.isUploading')
          .fileman-progressbar
101
            div(:style='`width: ` + state.uploadPercentage + `%`') {{ state.uploadPercentage }}%
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
          q-btn.acrylic-btn.q-ml-sm(
            flat
            dense
            no-caps
            color='negative'
            :aria-label='t(`common.actions.cancel`)'
            icon='las la-square'
            @click='uploadCancel'
            v-if='state.uploadPercentage < 100'
            )
        template(v-else)
          q-space
          q-btn.q-mr-sm(
            flat
            dense
            no-caps
            color='grey'
            :aria-label='t(`fileman.viewOptions`)'
            icon='las la-th-list'
            )
122
            q-tooltip(anchor='bottom middle', self='top middle') {{ t(`fileman.viewOptions`) }}
123 124 125 126 127 128 129 130
            q-menu(
              transition-show='jump-down'
              transition-hide='jump-up'
              anchor='bottom right'
              self='top right'
              )
              q-card.q-pa-sm
                .text-center
131
                  small.text-grey {{ t(`fileman.viewOptions`) }}
132 133 134 135
                q-list(dense)
                  q-separator.q-my-sm
                  q-item(clickable)
                    q-item-section(side)
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
                      q-icon(name='las la-list', color='grey', size='xs')
                    q-item-section.q-pr-sm Browse using...
                    q-item-section(side)
                      q-icon(name='las la-angle-right', color='grey', size='xs')
                    q-menu(
                      anchor='top end'
                      self='top start'
                      )
                      q-list.q-pa-sm(dense)
                        q-item(clickable, @click='state.displayMode = `path`')
                          q-item-section(side)
                            q-icon(
                              :name='state.displayMode === `path` ? `las la-check-circle` : `las la-circle`'
                              :color='state.displayMode === `path` ? `positive` : `grey`'
                              size='xs'
                              )
                          q-item-section.q-pr-sm Browse Using Paths
                        q-item(clickable, @click='state.displayMode = `title`')
                          q-item-section(side)
                            q-icon(
                              :name='state.displayMode === `title` ? `las la-check-circle` : `las la-circle`'
                              :color='state.displayMode === `title` ? `positive` : `grey`'
                              size='xs'
                              )
                          q-item-section.q-pr-sm Browse Using Titles
161
                  q-item(clickable, @click='state.isCompact = !state.isCompact')
162
                    q-item-section(side)
163 164 165 166 167
                      q-icon(
                        :name='state.isCompact ? `las la-check-square` : `las la-stop`'
                        :color='state.isCompact ? `positive` : `grey`'
                        size='xs'
                      )
168
                    q-item-section.q-pr-sm Compact List
169
                  q-item(clickable, @click='state.shouldShowFolders = !state.shouldShowFolders')
170
                    q-item-section(side)
171 172 173 174 175
                      q-icon(
                        :name='state.shouldShowFolders ? `las la-check-square` : `las la-stop`'
                        :color='state.shouldShowFolders ? `positive` : `grey`'
                        size='xs'
                      )
176 177 178 179 180 181 182 183
                    q-item-section.q-pr-sm Show Folders
          q-btn.q-mr-sm(
            flat
            dense
            no-caps
            color='grey'
            :aria-label='t(`common.actions.refresh`)'
            icon='las la-redo-alt'
184
            @click='reloadFolder(state.currentFolderId)'
185
            )
186
            q-tooltip(anchor='bottom middle', self='top middle') {{ t(`common.actions.refresh`) }}
187 188 189 190 191 192 193 194 195 196 197 198 199 200
          q-separator.q-mr-sm(inset, vertical)
          q-btn.q-mr-sm(
            flat
            dense
            no-caps
            color='blue'
            :label='t(`common.actions.new`)'
            :aria-label='t(`common.actions.new`)'
            icon='las la-plus-circle'
            )
            new-menu(
              :hide-asset-btn='true'
              :show-new-folder='true'
              @new-folder='() => newFolder(state.currentFolderId)'
201 202
              @new-page='() => close()'
              :base-path='folderPath'
203 204 205 206 207 208 209 210 211 212 213
              )
          q-btn(
            flat
            dense
            no-caps
            color='positive'
            :label='t(`common.actions.upload`)'
            :aria-label='t(`common.actions.upload`)'
            icon='las la-cloud-upload-alt'
            @click='uploadFile'
            )
214 215 216 217 218 219 220

      .row(style='flex: 1 1 100%;')
        .col
          q-scroll-area(
            :thumb-style='thumbStyle'
            :bar-style='barStyle'
            style='height: 100%;'
221
            )
222 223 224 225 226 227
            .fileman-loadinglist(v-if='state.fileListLoading')
              q-spinner.q-mr-sm(color='primary', size='64px', :thickness='1')
              span.text-primary Fetching folder contents...
            .fileman-emptylist(v-else-if='files.length < 1')
              img(src='/_assets/icons/carbon-copy-empty-box.svg')
              span This folder is empty.
228 229 230 231 232 233 234 235 236 237
            q-list.fileman-filelist(
              v-else
              :class='state.isCompact && `is-compact`'
              )
              q-item(
                v-for='item of files'
                :key='item.id'
                clickable
                active-class='active'
                :active='item.id === state.currentFileId'
238 239
                @click='selectItem(item)'
                @dblclick='doubleClickItem(item)'
240 241 242 243
                )
                q-item-section.fileman-filelist-icon(avatar)
                  q-icon(:name='item.icon', :size='state.isCompact ? `md` : `xl`')
                q-item-section.fileman-filelist-label
244 245
                  q-item-label {{ usePathTitle ? item.fileName : item.title }}
                  q-item-label(caption, v-if='!state.isCompact') {{ item.caption }}
246
                q-item-section.fileman-filelist-side(side, v-if='item.side')
247
                  .text-caption {{ item.side }}
248
                //- RIGHT-CLICK MENU
NGPixel's avatar
NGPixel committed
249
                q-menu.translucent-menu(
250 251 252 253 254 255 256 257
                  touch-position
                  context-menu
                  auto-close
                  transition-show='jump-down'
                  transition-hide='jump-up'
                  )
                  q-card.q-pa-sm
                    q-list(dense, style='min-width: 150px;')
258
                      q-item(clickable, v-if='insertMode && item.type !== `folder`', @click='insertItem(item)')
259 260 261
                        q-item-section(side)
                          q-icon(name='las la-plus-circle', color='primary')
                        q-item-section {{ t(`common.actions.insert`) }}
262
                      q-item(clickable, v-if='item.type === `page`', @click='editItem(item)')
263 264
                        q-item-section(side)
                          q-icon(name='las la-edit', color='orange')
265
                        q-item-section {{ t(`common.actions.edit`) }}
NGPixel's avatar
NGPixel committed
266 267 268 269
                      q-item(clickable, v-if='item.type === `page`', @click='rerenderPage(item)')
                        q-item-section(side)
                          q-icon(name='las la-magic', color='orange')
                        q-item-section {{ t(`common.actions.rerender`) }}
270 271 272
                      q-item(clickable, v-if='item.type !== `folder`', @click='openItem(item)')
                        q-item-section(side)
                          q-icon(name='las la-eye', color='primary')
273
                        q-item-section {{ t(`common.actions.view`) }}
274 275 276 277 278 279 280 281 282
                      template(v-if='item.type === `asset` && item.imageEdit')
                        q-item(clickable)
                          q-item-section(side)
                            q-icon(name='las la-edit', color='orange')
                          q-item-section Edit Image...
                        q-item(clickable)
                          q-item-section(side)
                            q-icon(name='las la-crop', color='orange')
                          q-item-section Resize Image...
283 284 285
                      q-item(clickable, v-if='item.type !== `folder`', @click='copyItemURL(item)')
                        q-item-section(side)
                          q-icon(name='las la-clipboard', color='primary')
286
                        q-item-section {{ t(`common.actions.copyURL`) }}
287
                      q-item(clickable, v-if='item.type !== `folder`', @click='downloadItem(item)')
288 289
                        q-item-section(side)
                          q-icon(name='las la-download', color='primary')
290
                        q-item-section {{ t(`common.actions.download`) }}
291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
                      q-item(clickable)
                        q-item-section(side)
                          q-icon(name='las la-copy', color='teal')
                        q-item-section Duplicate...
                      q-item(clickable, @click='renameItem(item)')
                        q-item-section(side)
                          q-icon(name='las la-redo', color='teal')
                        q-item-section Rename...
                      q-item(clickable)
                        q-item-section(side)
                          q-icon(name='las la-arrow-right', color='teal')
                        q-item-section Move to...
                      q-item(clickable, @click='delItem(item)')
                        q-item-section(side)
                          q-icon(name='las la-trash-alt', color='negative')
306
                        q-item-section.text-negative {{ t(`common.actions.delete`) }}
307
  q-footer
308
    q-bar.fileman-path
309
      small.text-caption.text-grey-7 {{folderPath}}
310 311 312 313 314 315 316 317

  input(
    type='file'
    ref='fileIpt'
    multiple
    @change='uploadNewFiles'
    style='display: none'
    )
318 319 320 321
</template>

<script setup>
import { useI18n } from 'vue-i18n'
322
import { computed, defineAsyncComponent, nextTick, onMounted, reactive, ref, toRaw, watch } from 'vue'
323 324 325
import { filesize } from 'filesize'
import { useQuasar } from 'quasar'
import { DateTime } from 'luxon'
326
import { cloneDeep, dropRight, find, findKey, initial, last, nth } from 'lodash-es'
327
import { useRoute, useRouter } from 'vue-router'
328
import gql from 'graphql-tag'
329
import Fuse from 'fuse.js/basic'
330

331 332 333
import NewMenu from './PageNewMenu.vue'
import Tree from './TreeNav.vue'

334
import fileTypes from '@/helpers/fileTypes'
335

336 337 338
import { useCommonStore } from '@/stores/common'
import { usePageStore } from '@/stores/page'
import { useSiteStore } from '@/stores/site'
339

340 341 342 343 344
import FolderCreateDialog from '@/components/FolderCreateDialog.vue'
import FolderDeleteDialog from '@/components/FolderDeleteDialog.vue'
import FolderRenameDialog from '@/components/FolderRenameDialog.vue'
import AssetRenameDialog from '@/components/AssetRenameDialog.vue'
import LocaleSelectorMenu from '@/components/LocaleSelectorMenu.vue'
345 346 347 348 349

// QUASAR

const $q = useQuasar()

350 351
// STORES

352
const commonStore = useCommonStore()
353
const pageStore = usePageStore()
354 355
const siteStore = useSiteStore()

356 357 358 359 360
// ROUTER

const router = useRouter()
const route = useRoute()

361 362 363 364 365 366 367 368
// I18N

const { t } = useI18n()

// DATA

const state = reactive({
  loading: 0,
369
  isFetching: false,
370
  search: '',
371 372
  currentFolderId: null,
  currentFileId: null,
373 374
  treeNodes: {},
  treeRoots: [],
375
  displayMode: 'title',
376 377
  isCompact: false,
  shouldShowFolders: true,
378 379 380
  isUploading: false,
  shouldCancelUpload: false,
  uploadPercentage: 0,
381 382
  fileList: [],
  fileListLoading: false
383 384
})

385 386 387 388 389 390 391 392 393 394 395 396 397
const thumbStyle = {
  right: '2px',
  borderRadius: '5px',
  backgroundColor: '#000',
  width: '5px',
  opacity: 0.15
}
const barStyle = {
  backgroundColor: '#FAFAFA',
  width: '9px',
  opacity: 1
}

398 399 400
// REFS

const fileIpt = ref(null)
401
const treeComp = ref(null)
402 403 404

// COMPUTED

405 406
const insertMode = computed(() => siteStore.overlayOpts?.insertMode ?? false)

407 408 409 410 411 412 413 414 415
const folderPath = computed(() => {
  if (!state.currentFolderId) {
    return '/'
  } else {
    const folderNode = state.treeNodes[state.currentFolderId] ?? {}
    return folderNode.folderPath ? `/${folderNode.folderPath}/${folderNode.fileName}/` : `/${folderNode.fileName}/`
  }
})

416 417
const usePathTitle = computed(() => state.displayMode === 'path')

418 419 420 421 422 423 424 425 426 427 428 429 430 431
const filteredFiles = computed(() => {
  if (state.search) {
    const fuse = new Fuse(state.fileList, {
      keys: [
        'title',
        'fileName'
      ]
    })
    return fuse.search(state.search).map(n => n.item)
  } else {
    return state.fileList
  }
})

432
const files = computed(() => {
433 434 435 436 437 438 439
  return filteredFiles.value.filter(f => {
    // -> Show Folders Filter
    if (f.type === 'folder' && !state.shouldShowFolders) {
      return false
    }
    return true
  }).map(f => {
440 441 442
    switch (f.type) {
      case 'folder': {
        f.icon = fileTypes.folder.icon
443
        f.caption = t('fileman.folderChildrenCount', { count: f.children }, f.children)
444 445 446 447 448 449 450
        break
      }
      case 'page': {
        f.icon = fileTypes.page.icon
        f.caption = t(`fileman.${f.pageType}PageType`)
        break
      }
451
      case 'asset': {
452 453
        f.icon = fileTypes[f.fileExt]?.icon ?? ''
        f.side = filesize(f.fileSize, { round: 0 })
454
        f.imageEdit = fileTypes[f.fileExt]?.imageEdit
455
        if (fileTypes[f.fileExt]) {
456
          f.caption = t(`fileman.${f.fileExt}FileType`)
457
        } else {
458
          f.caption = t('fileman.unknownFileType', { type: f.fileExt.toUpperCase() })
459 460 461
        }
        break
      }
462
    }
463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
    return f
  })
})

const currentFileDetails = computed(() => {
  if (state.currentFileId) {
    const item = find(state.fileList, ['id', state.currentFileId])
    if (item.type === 'folder') {
      return null
    }

    const items = [
      {
        label: t('fileman.detailsTitle'),
        value: item.title
      }
    ]
480
    let thumbnail = ''
481 482
    switch (item.type) {
      case 'page': {
483
        thumbnail = '/_assets/illustrations/fileman-page.svg'
484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
        items.push({
          label: t('fileman.detailsPageType'),
          value: t(`fileman.${item.pageType}PageType`)
        })
        items.push({
          label: t('fileman.detailsPageEditor'),
          value: item.pageType
        })
        items.push({
          label: t('fileman.detailsPageUpdated'),
          value: DateTime.fromISO(item.updatedAt).toFormat('yyyy-MM-dd \'at\' h:mm ZZZZ')
        })
        items.push({
          label: t('fileman.detailsPageCreated'),
          value: DateTime.fromISO(item.updatedAt).toFormat('yyyy-MM-dd \'at\' h:mm ZZZZ')
        })
        break
      }
502
      case 'asset': {
503
        thumbnail = `/_thumb/${item.id}.webp`
504 505
        items.push({
          label: t('fileman.detailsAssetType'),
506
          value: fileTypes[item.fileExt] ? t(`fileman.${item.fileExt}FileType`) : t('fileman.unknownFileType', { type: item.fileExt.toUpperCase() })
507 508 509 510 511 512 513 514 515
        })
        items.push({
          label: t('fileman.detailsAssetSize'),
          value: filesize(item.fileSize)
        })
        break
      }
    }
    return {
516
      thumbnail,
517 518 519 520 521 522 523 524 525
      items
    }
  } else {
    return null
  }
})

// WATCHERS

526
watch(() => state.currentFolderId, async (newValue) => {
527
  await loadTree({ parentId: newValue })
528 529 530 531 532 533 534 535
})

// METHODS

function close () {
  siteStore.overlay = null
}

536 537 538 539 540 541 542 543
function insertItem (item) {
  if (!item) {
    item = find(state.fileList, ['id', state.currentFileId])
  }
  EVENT_BUS.emit('insertAsset', toRaw(item))
  close()
}

544 545
async function treeLazyLoad (nodeId, isCurrent, { done, fail }) {
  await loadTree({ parentId: nodeId, types: isCurrent ? null : ['folder'] })
546 547 548
  done()
}

549
async function loadTree ({ parentId = null, parentPath = null, types, initLoad = false }) {
550 551
  if (state.isFetching) { return }
  state.isFetching = true
552 553 554 555 556 557 558 559
  if (!parentId) {
    parentId = null
  }
  if (parentId === state.currentFolderId) {
    state.fileListLoading = true
    state.currentFileId = null
    state.fileList = []
  }
560 561 562 563 564 565
  try {
    const resp = await APOLLO_CLIENT.query({
      query: gql`
        query loadTree (
          $siteId: UUID!
          $parentId: UUID
566
          $parentPath: String
567
          $types: [TreeItemType]
568 569
          $includeAncestors: Boolean
          $includeRootFolders: Boolean
570 571 572 573
        ) {
          tree (
            siteId: $siteId
            parentId: $parentId
574
            parentPath: $parentPath
575
            types: $types
576 577
            includeAncestors: $includeAncestors
            includeRootFolders: $includeRootFolders
578 579
          ) {
            __typename
580 581 582 583
            id
            folderPath
            fileName
            title
584 585
            ... on TreeItemFolder {
              childrenCount
586
              isAncestor
587 588 589 590
            }
            ... on TreeItemPage {
              createdAt
              updatedAt
591
              editor
592 593 594 595 596
            }
            ... on TreeItemAsset {
              createdAt
              updatedAt
              fileSize
597 598
              fileExt
              mimeType
599 600 601 602 603 604 605
            }
          }
        }
      `,
      variables: {
        siteId: siteStore.id,
        parentId,
606 607 608 609
        parentPath,
        types,
        includeAncestors: initLoad,
        includeRootFolders: initLoad
610 611 612 613 614 615 616 617 618
      },
      fetchPolicy: 'network-only'
    })
    const items = cloneDeep(resp?.data?.tree)
    if (items?.length > 0) {
      const newTreeRoots = []
      for (const item of items) {
        switch (item.__typename) {
          case 'TreeItemFolder': {
619
            // -> Tree Nodes
620 621 622 623 624
            state.treeNodes[item.id] = {
              folderPath: item.folderPath,
              fileName: item.fileName,
              title: item.title,
              children: state.treeNodes[item.id]?.children ?? []
625
            }
626

627 628
            // -> Set Ancestors / Tree Roots
            if (item.folderPath) {
629 630 631 632 633 634 635 636
              let folderParentId = parentId
              if (!folderParentId) {
                const parentFolderParts = item.folderPath.split('/')
                const parentFolder = find(items, { folderPath: parentFolderParts.length > 1 ? initial(parentFolderParts).join('/') : '', fileName: last(parentFolderParts) })
                folderParentId = parentFolder.id
              }
              if (item.id !== folderParentId && !state.treeNodes[folderParentId]?.children?.includes(item.id)) {
                state.treeNodes[folderParentId]?.children?.push(item.id)
637 638
              }
            } else {
639
              newTreeRoots.push(item.id)
640 641 642
            }

            // -> File List
643
            if (parentId === state.currentFolderId && !item.isAncestor) {
644 645 646 647
              state.fileList.push({
                id: item.id,
                type: 'folder',
                title: item.title,
648
                fileName: item.fileName,
649
                children: item.childrenCount || 0
650 651 652 653 654 655 656 657 658 659
              })
            }
            break
          }
          case 'TreeItemAsset': {
            if (parentId === state.currentFolderId) {
              state.fileList.push({
                id: item.id,
                type: 'asset',
                title: item.title,
660 661 662
                fileExt: item.fileExt,
                fileSize: item.fileSize,
                mimeType: item.mimeType,
663 664
                folderPath: item.folderPath,
                fileName: item.fileName
665 666 667 668 669 670 671 672 673 674 675
              })
            }
            break
          }
          case 'TreeItemPage': {
            if (parentId === state.currentFolderId) {
              state.fileList.push({
                id: item.id,
                type: 'page',
                title: item.title,
                pageType: 'markdown',
676 677 678
                updatedAt: '2022-11-24T18:27:00Z',
                folderPath: item.folderPath,
                fileName: item.fileName
679
              })
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
            }
            break
          }
        }
      }
      if (newTreeRoots.length > 0) {
        state.treeRoots = newTreeRoots
      }
    }
  } catch (err) {
    $q.notify({
      type: 'negative',
      message: 'Failed to load folder tree.',
      caption: err.message
    })
  }
696 697 698 699 700
  if (parentId === state.currentFolderId) {
    nextTick(() => {
      state.fileListLoading = false
    })
  }
701 702 703
  if (parentId) {
    treeComp.value.setLoaded(parentId)
  }
704
  state.isFetching = false
705 706
}

707 708 709 710 711 712
function treeContextAction (nodeId, action) {
  switch (action) {
    case 'newFolder': {
      newFolder(nodeId)
      break
    }
713 714 715 716
    case 'rename': {
      renameFolder(nodeId)
      break
    }
717 718 719 720
    case 'del': {
      delFolder(nodeId)
      break
    }
721 722 723
  }
}

724 725 726 727
// --------------------------------------
// FOLDER METHODS
// --------------------------------------

728 729 730 731 732 733 734
function newFolder (parentId) {
  $q.dialog({
    component: FolderCreateDialog,
    componentProps: {
      parentId
    }
  }).onOk(() => {
735
    loadTree({ parentId })
736 737 738
  })
}

739 740 741 742 743 744
function renameFolder (folderId) {
  $q.dialog({
    component: FolderRenameDialog,
    componentProps: {
      folderId
    }
745
  }).onOk(async () => {
746
    treeComp.value.resetLoaded()
747 748 749 750 751 752 753 754 755 756 757 758
    // // -> Delete current folder and children from cache
    // const fPath = [state.treeNodes[folderId].folderPath, state.treeNodes[folderId].fileName].filter(p => !!p).join('/')
    // delete state.treeNodes[folderId]
    // for (const [nodeId, node] of Object.entries(state.treeNodes)) {
    //   if (node.folderPath.startsWith(fPath)) {
    //     delete state.treeNodes[nodeId]
    //   }
    // }
    // -> Reload tree
    await loadTree({ parentId: folderId, types: ['folder'], initLoad: true }) // Update tree
    // -> Reload current view (in case current folder is included)
    await loadTree({ parentId: state.currentFolderId })
759 760 761
  })
}

762
function delFolder (folderId, mustReload = false) {
763 764 765 766 767 768 769 770 771 772 773 774 775
  $q.dialog({
    component: FolderDeleteDialog,
    componentProps: {
      folderId,
      folderName: state.treeNodes[folderId].title
    }
  }).onOk(() => {
    for (const nodeId in state.treeNodes) {
      if (state.treeNodes[nodeId].children.includes(folderId)) {
        state.treeNodes[nodeId].children = state.treeNodes[nodeId].children.filter(c => c !== folderId)
      }
    }
    delete state.treeNodes[folderId]
776 777 778 779
    if (state.treeRoots.includes(folderId)) {
      state.treeRoots = state.treeRoots.filter(n => n !== folderId)
    }
    if (mustReload) {
780
      loadTree({ parentId: state.currentFolderId })
781
    }
782 783 784 785
  })
}

function reloadFolder (folderId) {
786
  loadTree({ parentId: folderId })
787 788 789
  treeComp.value.resetLoaded()
}

790
// --------------------------------------
791 792 793
// PAGE METHODS
// --------------------------------------

NGPixel's avatar
NGPixel committed
794 795
function rerenderPage (item) {
  $q.dialog({
796
    component: defineAsyncComponent(() => import('@/components/RerenderPageDialog.vue')),
NGPixel's avatar
NGPixel committed
797 798 799 800 801 802
    componentProps: {
      id: item.id
    }
  })
}

803 804
function delPage (pageId, pageName) {
  $q.dialog({
805
    component: defineAsyncComponent(() => import('@/components/PageDeleteDialog.vue')),
806 807 808 809 810
    componentProps: {
      pageId,
      pageName
    }
  }).onOk(() => {
811 812
    // -> Reload current view
    loadTree({ parentId: state.currentFolderId })
813 814 815
  })
}

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833
// --------------------------------------
// ASSET METHODS
// --------------------------------------

function renameAsset (assetId) {
  $q.dialog({
    component: AssetRenameDialog,
    componentProps: {
      assetId
    }
  }).onOk(async () => {
    // -> Reload current view
    await loadTree({ parentId: state.currentFolderId })
  })
}

function delAsset (assetId, assetName) {
  $q.dialog({
834
    component: defineAsyncComponent(() => import('@/components/AssetDeleteDialog.vue')),
835 836 837 838
    componentProps: {
      assetId,
      assetName
    }
839 840 841
  }).onOk(async () => {
    // -> Reload current view
    await loadTree({ parentId: state.currentFolderId })
842 843 844
  })
}

845 846 847
// --------------------------------------
// UPLOAD METHODS
// --------------------------------------
848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871

function uploadFile () {
  fileIpt.value.click()
}

async function uploadNewFiles () {
  if (!fileIpt.value.files?.length) {
    return
  }

  state.isUploading = true
  state.uploadPercentage = 0

  state.loading++

  nextTick(() => {
    setTimeout(async () => {
      try {
        const totalFiles = fileIpt.value.files.length
        let idx = 0
        for (const fileToUpload of fileIpt.value.files) {
          idx++
          state.uploadPercentage = totalFiles > 1 ? Math.round(idx / totalFiles * 100) : 90
          const resp = await APOLLO_CLIENT.mutate({
872 873 874
            context: {
              uploadMode: true
            },
875 876
            mutation: gql`
              mutation uploadAssets (
877 878 879
                $folderId: UUID
                $locale: String
                $siteId: UUID
880 881 882
                $files: [Upload!]!
              ) {
                uploadAssets (
883 884
                  folderId: $folderId
                  locale: $locale
885 886 887 888 889 890 891 892 893 894 895
                  siteId: $siteId
                  files: $files
                ) {
                  operation {
                    succeeded
                    message
                  }
                }
              }
            `,
            variables: {
896
              folderId: state.currentFolderId,
897
              siteId: siteStore.id,
898
              locale: 'en', // TODO: use current locale
899 900 901 902 903 904 905 906
              files: [fileToUpload]
            }
          })
          if (!resp?.data?.uploadAssets?.operation?.succeeded) {
            throw new Error(resp?.data?.uploadAssets?.operation?.message || 'An unexpected error occured.')
          }
        }
        state.uploadPercentage = 100
907
        loadTree({ parentId: state.currentFolderId })
908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933
        $q.notify({
          type: 'positive',
          message: t('fileman.uploadSuccess')
        })
      } catch (err) {
        $q.notify({
          type: 'negative',
          message: 'Failed to upload file.',
          caption: err.message
        })
      }
      state.loading--
      fileIpt.value.value = null
      setTimeout(() => {
        state.isUploading = false
        state.uploadPercentage = 0
      }, 1500)
    }, 400)
  })
}

function uploadCancel () {
  state.isUploading = false
  state.uploadPercentage = 0
}

934 935 936 937
// --------------------------------------
// ITEM LIST ACTIONS
// --------------------------------------

938 939 940 941 942 943 944 945 946
function selectItem (item) {
  if (item.type === 'folder') {
    state.currentFolderId = item.id
    treeComp.value.setOpened(item.id)
  } else {
    state.currentFileId = item.id
  }
}

947 948 949 950 951 952 953 954
function doubleClickItem (item) {
  if (insertMode.value) {
    insertItem(item)
  } else {
    openItem(item)
  }
}

955
function openItem (item) {
956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982
  switch (item.type) {
    case 'folder': {
      return
    }
    case 'page': {
      const pagePath = item.folderPath ? `${item.folderPath}/${item.fileName}` : item.fileName
      router.push(`/${pagePath}`)
      close()
      break
    }
    case 'asset': {
      // TODO: Open asset
      close()
      break
    }
  }
}

async function copyItemURL (item) {
  try {
    switch (item.type) {
      case 'page': {
        const pagePath = item.folderPath ? `${item.folderPath}/${item.fileName}` : item.fileName
        await navigator.clipboard.writeText(`${window.location.origin}/${pagePath}`)
        break
      }
      case 'asset': {
983 984
        const assetPath = item.folderPath ? `${item.folderPath}/${item.fileName}` : item.fileName
        await navigator.clipboard.writeText(`${window.location.origin}/${assetPath}`)
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003
        break
      }
      default: {
        throw new Error('Invalid Item Type')
      }
    }
    $q.notify({
      type: 'positive',
      message: t('fileman.copyURLSuccess')
    })
  } catch (err) {
    $q.notify({
      type: 'negative',
      message: 'Failed to copy URL to clipboard.',
      caption: err.message
    })
  }
}

1004 1005 1006 1007 1008 1009 1010 1011 1012
async function editItem (item) {
  router.push(item.folderPath ? `/_edit/${item.folderPath}/${item.fileName}` : `/_edit/${item.fileName}`)
  close()
}

function downloadItem (item) {

}

1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024
function renameItem (item) {
  console.info(item)
  switch (item.type) {
    case 'folder': {
      renameFolder(item.id)
      break
    }
    case 'page': {
      // TODO: Rename page
      break
    }
    case 'asset': {
1025
      renameAsset(item.id)
1026 1027 1028 1029 1030
      break
    }
  }
}

1031 1032
function delItem (item) {
  switch (item.type) {
1033 1034 1035 1036
    case 'asset': {
      delAsset(item.id, item.title)
      break
    }
1037 1038 1039 1040
    case 'folder': {
      delFolder(item.id, true)
      break
    }
1041 1042 1043 1044
    case 'page': {
      delPage(item.id, item.title)
      break
    }
1045
  }
1046 1047 1048 1049
}

// MOUNTED

1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
onMounted(async () => {
  const pathParts = pageStore.path.split('/')
  const parentPath = initial(pathParts).join('/')

  await loadTree({
    parentPath,
    initLoad: true
  })

  // -> Open tree up to current folder
  const folderFolderPath = dropRight(pathParts, 2).join('/')
  const folderFileName = nth(pathParts, -2)

  for (const [id, node] of Object.entries(state.treeNodes)) {
    if (parentPath.startsWith(node.folderPath ? `${node.folderPath}/${node.fileName}` : node.fileName)) {
      treeComp.value.setOpened(id)
    }
  }

  // -> Switch to current folder (from page path)
  const currentNodeId = findKey(state.treeNodes, n => n.folderPath === folderFolderPath && n.fileName === folderFileName)
  if (currentNodeId) {
    state.currentFolderId = currentNodeId
  }
1074 1075
})

1076 1077 1078 1079
</script>

<style lang="scss">
.fileman {
1080 1081 1082 1083 1084 1085 1086 1087 1088 1089
  &-left {
    @at-root .body--light & {
      background-color: $blue-grey-1;
    }
    @at-root .body--dark & {
      background-color: $dark-4;
    }
  }

  &-center {
1090

1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125
    @at-root .body--light & {
      background-color: #FFF;
    }
    @at-root .body--dark & {
      background-color: $dark-6;
    }
  }

  &-right {
    @at-root .body--light & {
      background-color: $grey-1;
    }
    @at-root .body--dark & {
      background-color: $dark-5;
    }
  }

  &-toolbar {
    @at-root .body--light & {
      background-color: $grey-1;
    }
    @at-root .body--dark & {
      background-color: $dark-5;
    }
  }

  &-path {
    @at-root .body--light & {
      background-color: $blue-grey-1 !important;
    }
    @at-root .body--dark & {
      background-color: $dark-4 !important;
    }
  }

1126 1127 1128 1129
  &-main {
    height: 100%;
  }

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142
  &-loadinglist {
    padding: 16px;
    font-style: italic;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;

    > span {
      margin-top: 16px;
    }
  }

1143 1144 1145
  &-emptylist {
    padding: 16px;
    font-style: italic;
1146 1147
    font-size: 1.5em;
    font-weight: 300;
1148
    display: flex;
1149 1150
    flex-direction: column;
    justify-content: center;
1151 1152
    align-items: center;

1153 1154 1155 1156 1157
    > img {
      opacity: .25;
      width: 200px;
    }

1158 1159 1160 1161
    @at-root .body--light & {
      color: $grey-6;
    }
    @at-root .body--dark & {
1162 1163 1164 1165 1166
      color: $grey-7;

      > img {
        filter: invert(1);
      }
1167 1168 1169
    }
  }

1170 1171 1172 1173
  &-filelist {
    padding: 8px 12px;

    > .q-item {
1174
      padding: 4px 6px;
1175
      border-radius: 8px;
1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

      &.active {
        background-color: var(--q-primary);
        color: #FFF;

        .fileman-filelist-label .q-item__label--caption {
          color: rgba(255,255,255,.7);
        }

        .fileman-filelist-side .text-caption {
          color: rgba(255,255,255,.7);
        }
      }
    }
1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201

    &.is-compact {
      > .q-item {
        padding: 0 6px;
        min-height: 36px;
      }

      .fileman-filelist-icon {
        padding-right: 6px;
        min-width: 0;
      }
    }
1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227
  }
  &-details-row {
    display: flex;
    flex-direction: column;
    padding: 5px 0;

    label {
      font-size: .7rem;
      font-weight: 500;

      @at-root .body--light & {
        color: $grey-6;
      }
      @at-root .body--dark & {
        color: $blue-grey-4;
      }
    }
    span {
      font-size: .85rem;

      @at-root .body--light & {
        color: $grey-8;
      }
      @at-root .body--dark & {
        color: $blue-grey-2;
      }
1228
    }
1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284

    & + .fileman-details-row {
      margin-top: 5px;
    }
  }

  &-progressbar {
    width: 100%;
    flex: 1;
    height: 12px;
    border-radius: 3px;

    @at-root .body--light & {
      background-color: $blue-grey-2;
    }
    @at-root .body--dark & {
      background-color: $dark-4 !important;
    }

    > div {
      height: 12px;
      background-color: $positive;
      border-radius: 3px 0 0 3px;
      background-image: linear-gradient(
        -45deg,
        rgba(255, 255, 255, 0.3) 25%,
        transparent 25%,
        transparent 50%,
        rgba(255, 255, 255, 0.3) 50%,
        rgba(255, 255, 255, 0.3) 75%,
        transparent 75%,
        transparent
      );
      background-size: 50px 50px;
      background-position: 0 0;
      animation: fileman-progress 2s linear infinite;
      box-shadow: 0 0 5px 0 $positive;
      font-size: 9px;
      letter-spacing: 2px;
      font-weight: 700;
      color: #FFF;
      display: flex;
      justify-content: center;
      align-items: center;
      overflow: hidden;
      transition: all 1s ease;
    }
  }
}

@keyframes fileman-progress {
  0% {
    background-position: 0 0;
  }
  100% {
    background-position: -50px -50px;
1285 1286 1287
  }
}
</style>