refactor: standardize design

Signed-off-by: Sebastian Krupinski <krupinski01@gmail.com>
This commit is contained in:
2026-03-03 21:55:48 -05:00
parent 31a33d8758
commit a59dbff9f1
25 changed files with 994 additions and 306 deletions

View File

@@ -1,11 +1,11 @@
{
"name": "ktrix/files",
"description": "File browser interface module",
"name": "ktrix/documents",
"description": "Documents interface module",
"type": "ktrix-module",
"license": "AGPL-3.0-or-later",
"autoload": {
"psr-4": {
"KTXM\\Files\\": "lib/"
"KTXM\\Documents\\": "lib/"
}
},
"require": {}

View File

@@ -1,12 +1,12 @@
<?php
namespace KTXM\Files;
namespace KTXM\Documents;
use KTXF\Module\ModuleBrowserInterface;
use KTXF\Module\ModuleInstanceAbstract;
/**
* Files Module - File Browser UI
* Documents Module - Document Browser UI
*/
class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
{
@@ -16,12 +16,12 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
public function handle(): string
{
return 'files';
return 'documents';
}
public function label(): string
{
return 'Files';
return 'Documents';
}
public function author(): string
@@ -31,7 +31,7 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
public function description(): string
{
return 'File browser interface - provides file and folder management, navigation, uploads, and organization capabilities';
return 'Documents interface - provides file and folder management, navigation, uploads, and organization capabilities';
}
public function version(): string
@@ -42,10 +42,10 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
public function permissions(): array
{
return [
'files' => [
'label' => 'Access Files',
'description' => 'View and access the file browser module',
'group' => 'File Management'
'documents' => [
'label' => 'Access Documents',
'description' => 'View and access the documents module',
'group' => 'Document Management'
],
];
}
@@ -54,7 +54,7 @@ class Module extends ModuleInstanceAbstract implements ModuleBrowserInterface
{
return [
'handle' => $this->handle(),
'namespace' => 'Files',
'namespace' => 'Documents',
'version' => $this->version(),
'label' => $this->label(),
'author' => $this->author(),

View File

@@ -1,5 +1,5 @@
{
"name": "files",
"name": "documents",
"version": "0.0.1",
"private": true,
"license": "AGPL-3.0-or-later",

View File

@@ -1,29 +1,32 @@
<script setup lang="ts">
import { ref } from 'vue'
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
defineProps<{
item: FileCollectionObject | FileEntityObject
item: CollectionObject | EntityObject
size?: 'x-small' | 'small' | 'default'
variant?: 'text' | 'flat' | 'elevated' | 'tonal' | 'outlined' | 'plain'
buttonClass?: string
}>()
const emit = defineEmits<{
'rename': [item: FileCollectionObject | FileEntityObject]
'delete': [item: FileCollectionObject | FileEntityObject]
'download': [item: FileCollectionObject | FileEntityObject]
'show-details': [item: FileCollectionObject | FileEntityObject]
'open': [item: CollectionObject | EntityObject]
'rename': [item: CollectionObject | EntityObject]
'delete': [item: CollectionObject | EntityObject]
'download': [item: CollectionObject | EntityObject]
'show-details': [item: CollectionObject | EntityObject]
}>()
const menuOpen = ref(false)
function handleAction(action: string, item: FileCollectionObject | FileEntityObject, event: Event) {
function handleAction(action: string, item: CollectionObject | EntityObject, event: Event) {
event.stopPropagation()
menuOpen.value = false
if (action === 'rename') {
if (action === 'open') {
emit('open', item)
} else if (action === 'rename') {
emit('rename', item)
} else if (action === 'delete') {
emit('delete', item)
@@ -34,8 +37,8 @@ function handleAction(action: string, item: FileCollectionObject | FileEntityObj
}
}
function isEntity(item: FileCollectionObject | FileEntityObject): item is FileEntityObject {
return item['@type'] === 'files.entity'
function isEntity(item: CollectionObject | EntityObject): item is EntityObject {
return item instanceof EntityObject
}
</script>
@@ -52,6 +55,10 @@ function isEntity(item: FileCollectionObject | FileEntityObject): item is FileEn
/>
</template>
<v-list density="compact">
<v-list-item v-if="isEntity(item)" @click="(e: Event) => handleAction('open', item, e)">
<template #prepend><v-icon size="small">mdi-open-in-app</v-icon></template>
<v-list-item-title>Open</v-list-item-title>
</v-list-item>
<v-list-item @click="(e: Event) => handleAction('details', item, e)">
<template #prepend><v-icon size="small">mdi-information-outline</v-icon></template>
<v-list-item-title>Details</v-list-item-title>

View File

@@ -1,11 +1,11 @@
<script setup lang="ts">
import { computed } from 'vue'
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
import { getFileIcon, formatSize, formatDate } from '@/utils/fileHelpers'
const props = defineProps<{
selectedItems: (FileCollectionObject | FileEntityObject)[]
selectedItems: (CollectionObject | EntityObject)[]
}>()
const emit = defineEmits<{
@@ -17,15 +17,15 @@ const singleSelection = computed(() => props.selectedItems.length === 1)
const selectedItem = computed(() => props.selectedItems[0] ?? null)
const isCollection = computed(() =>
selectedItem.value?.['@type'] === 'files.collection'
selectedItem.value instanceof CollectionObject
)
const isEntity = computed(() =>
selectedItem.value?.['@type'] === 'files.entity'
selectedItem.value instanceof EntityObject
)
const entity = computed(() =>
isEntity.value ? selectedItem.value as FileEntityObject : null
isEntity.value ? selectedItem.value as EntityObject : null
)
// Computed display values
@@ -43,8 +43,8 @@ const itemIconColor = computed(() => {
const totalSize = computed(() => {
if (props.selectedItems.length === 0) return 0
return props.selectedItems.reduce((sum, item) => {
if (item['@type'] === 'files.entity') {
return sum + ((item as FileEntityObject).size || 0)
if (item instanceof EntityObject) {
return sum + (item.properties.size || 0)
}
return sum
}, 0)
@@ -54,7 +54,7 @@ const totalSize = computed(() => {
<template>
<v-navigation-drawer
:model-value="hasSelection"
:key="selectedItems.map(i => i.id).join(',')"
:key="selectedItems.map(i => String(i.identifier)).join(',')"
location="right"
width="320"
temporary
@@ -78,9 +78,9 @@ const totalSize = computed(() => {
<!-- Icon and name -->
<div class="text-center mb-4">
<v-icon :color="itemIconColor" size="64">{{ itemIcon }}</v-icon>
<div class="text-h6 mt-2 text-truncate">{{ selectedItem.label }}</div>
<div class="text-h6 mt-2 text-truncate">{{ selectedItem.properties.label || String(selectedItem.identifier ?? '') }}</div>
<div class="text-caption text-grey">
{{ isCollection ? 'Folder' : entity?.mime || 'File' }}
{{ isCollection ? 'Folder' : entity?.properties.mime || 'File' }}
</div>
</div>
@@ -95,7 +95,7 @@ const totalSize = computed(() => {
</template>
<v-list-item-title class="text-caption text-grey">Type</v-list-item-title>
<v-list-item-subtitle>
{{ isCollection ? 'Folder' : (entity?.mime || 'Unknown') }}
{{ isCollection ? 'Folder' : (entity?.properties.mime || 'Unknown') }}
</v-list-item-subtitle>
</v-list-item>
@@ -105,25 +105,25 @@ const totalSize = computed(() => {
<v-icon size="small" class="mr-3">mdi-harddisk</v-icon>
</template>
<v-list-item-title class="text-caption text-grey">Size</v-list-item-title>
<v-list-item-subtitle>{{ formatSize(entity.size) }}</v-list-item-subtitle>
<v-list-item-subtitle>{{ formatSize(entity.properties.size) }}</v-list-item-subtitle>
</v-list-item>
<!-- Created -->
<v-list-item v-if="selectedItem.createdOn">
<v-list-item v-if="selectedItem.created">
<template #prepend>
<v-icon size="small" class="mr-3">mdi-calendar-plus</v-icon>
</template>
<v-list-item-title class="text-caption text-grey">Created</v-list-item-title>
<v-list-item-subtitle>{{ formatDate(selectedItem.createdOn) }}</v-list-item-subtitle>
<v-list-item-subtitle>{{ formatDate(selectedItem.created) }}</v-list-item-subtitle>
</v-list-item>
<!-- Modified -->
<v-list-item v-if="selectedItem.modifiedOn">
<v-list-item v-if="selectedItem.modified">
<template #prepend>
<v-icon size="small" class="mr-3">mdi-calendar-edit</v-icon>
</template>
<v-list-item-title class="text-caption text-grey">Modified</v-list-item-title>
<v-list-item-subtitle>{{ formatDate(selectedItem.modifiedOn) }}</v-list-item-subtitle>
<v-list-item-subtitle>{{ formatDate(selectedItem.modified) }}</v-list-item-subtitle>
</v-list-item>
<!-- ID -->
@@ -133,7 +133,7 @@ const totalSize = computed(() => {
</template>
<v-list-item-title class="text-caption text-grey">ID</v-list-item-title>
<v-list-item-subtitle class="text-truncate" style="font-family: monospace; font-size: 11px;">
{{ selectedItem.id }}
{{ selectedItem.identifier }}
</v-list-item-subtitle>
</v-list-item>
</v-list>
@@ -165,8 +165,8 @@ const totalSize = computed(() => {
</template>
<v-list-item-title class="text-caption text-grey">Contents</v-list-item-title>
<v-list-item-subtitle>
{{ selectedItems.filter(i => i['@type'] === 'files.collection').length }} folders,
{{ selectedItems.filter(i => i['@type'] === 'files.entity').length }} files
{{ selectedItems.filter(i => i instanceof CollectionObject).length }} folders,
{{ selectedItems.filter(i => i instanceof EntityObject).length }} files
</v-list-item-subtitle>
</v-list-item>
</v-list>

View File

@@ -12,3 +12,6 @@ export * from './views'
// Dialog components
export * from './dialogs'
// Viewer
export * from './viewer'

View File

@@ -0,0 +1,293 @@
<script setup lang="ts">
import { ref, computed, watch, onMounted, onUnmounted, defineAsyncComponent } from 'vue'
import { EntityObject } from '@DocumentsManager/models/entity'
import { useFileViewer } from '@/composables'
const props = defineProps<{
modelValue: boolean
entity: EntityObject | null
/** All files in the current folder, used for prev/next navigation */
allEntities: EntityObject[]
/** Converts an entity into a URL usable as an img/video src */
getUrl: (entityId: string, collectionId: string | null) => string
/** Called to trigger a browser download of an entity */
downloadEntity: (entityId: string, collectionId: string | null) => void
}>()
const emit = defineEmits<{
'update:modelValue': [value: boolean]
/** Request the parent to switch to a different entity */
'navigate': [entity: EntityObject]
}>()
const fileViewer = useFileViewer()
// ── Derived state ──────────────────────────────────────────────────────────
const url = computed(() => {
if (!props.entity) return ''
return props.getUrl(
String(props.entity.identifier ?? ''),
props.entity.collection ? String(props.entity.collection) : null,
)
})
const mime = computed(() => props.entity?.properties.mime ?? '')
const viewer = computed(() => {
if (!mime.value) return null
return fileViewer.findViewer(mime.value)
})
// Wrap the raw () => import() factory in defineAsyncComponent so Vue
// actually resolves it instead of rendering the Promise as text.
const viewerComponent = computed(() => {
if (!viewer.value?.component) return null
return defineAsyncComponent(viewer.value.component as () => Promise<unknown>)
})
const filename = computed(
() => props.entity?.properties.label ?? String(props.entity?.identifier ?? ''),
)
const currentIndex = computed(() => {
if (!props.entity) return -1
return props.allEntities.findIndex(e => e.identifier === props.entity!.identifier)
})
const hasPrev = computed(() => currentIndex.value > 0)
const hasNext = computed(() => currentIndex.value < props.allEntities.length - 1)
// Viewer component may take a moment to load; track async state
const viewerLoading = ref(false)
watch(() => props.entity, () => {
viewerLoading.value = false
})
// ── Navigation ──────────────────────────────────────────────────────────────
function navigatePrev() {
if (!hasPrev.value) return
emit('navigate', props.allEntities[currentIndex.value - 1])
}
function navigateNext() {
if (!hasNext.value) return
emit('navigate', props.allEntities[currentIndex.value + 1])
}
function close() {
emit('update:modelValue', false)
}
function handleDownload() {
if (!props.entity) return
props.downloadEntity(
String(props.entity.identifier ?? ''),
props.entity.collection ? String(props.entity.collection) : null,
)
}
// ── Keyboard shortcuts ──────────────────────────────────────────────────────
function handleKeydown(e: KeyboardEvent) {
if (!props.modelValue) return
if (e.key === 'ArrowLeft') { e.preventDefault(); navigatePrev() }
else if (e.key === 'ArrowRight') { e.preventDefault(); navigateNext() }
else if (e.key === 'Escape') { e.preventDefault(); close() }
}
onMounted(() => window.addEventListener('keydown', handleKeydown))
onUnmounted(() => window.removeEventListener('keydown', handleKeydown))
</script>
<template>
<v-dialog
:model-value="modelValue"
fullscreen
transition="dialog-bottom-transition"
@update:model-value="emit('update:modelValue', $event)"
>
<div class="viewer-shell">
<!-- Toolbar -->
<div class="viewer-toolbar">
<v-btn icon="mdi-close" variant="text" @click="close" />
<span class="viewer-filename text-truncate">{{ filename }}</span>
<div class="viewer-toolbar-actions">
<span v-if="allEntities.length > 1" class="viewer-counter text-caption text-medium-emphasis mr-2">
{{ currentIndex + 1 }} / {{ allEntities.length }}
</span>
<v-btn
icon="mdi-download"
variant="text"
size="small"
title="Download"
@click="handleDownload"
/>
</div>
</div>
<!-- Content area -->
<div class="viewer-content">
<!-- Prev arrow -->
<div class="viewer-nav viewer-nav--prev">
<v-btn
v-if="hasPrev"
icon="mdi-chevron-left"
variant="elevated"
size="large"
@click="navigatePrev"
/>
</div>
<!-- Viewer / fallback -->
<div class="viewer-stage">
<template v-if="entity">
<!-- Registered viewer component -->
<Suspense v-if="viewer">
<template #default>
<component
:is="viewerComponent"
:url="url"
:entity="entity"
:mime="mime"
class="viewer-component"
/>
</template>
<template #fallback>
<div class="viewer-loading">
<v-progress-circular indeterminate color="primary" />
</div>
</template>
</Suspense>
<!-- No viewer registered for this type -->
<div v-else class="viewer-no-preview">
<v-icon size="64" color="grey-lighten-1">mdi-file-question-outline</v-icon>
<p class="text-h6 mt-4">No preview available</p>
<p class="text-body-2 text-medium-emphasis mb-6">
{{ mime || 'Unknown file type' }}
</p>
<v-btn
prepend-icon="mdi-download"
variant="tonal"
@click="handleDownload"
>
Download file
</v-btn>
</div>
</template>
</div>
<!-- Next arrow -->
<div class="viewer-nav viewer-nav--next">
<v-btn
v-if="hasNext"
icon="mdi-chevron-right"
variant="elevated"
size="large"
@click="navigateNext"
/>
</div>
</div>
</div>
</v-dialog>
</template>
<style scoped>
.viewer-shell {
display: flex;
flex-direction: column;
height: 100%;
background: rgb(var(--v-theme-surface));
}
/* Toolbar */
.viewer-toolbar {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 8px;
border-bottom: 1px solid rgba(var(--v-border-color), var(--v-border-opacity));
min-height: 56px;
flex-shrink: 0;
}
.viewer-filename {
flex: 1;
font-size: 0.9375rem;
font-weight: 500;
}
.viewer-toolbar-actions {
display: flex;
align-items: center;
flex-shrink: 0;
}
/* Content */
.viewer-content {
flex: 1;
display: flex;
align-items: stretch;
overflow: hidden;
}
/* Prev/Next nav columns */
.viewer-nav {
display: flex;
align-items: center;
justify-content: center;
width: 64px;
flex-shrink: 0;
padding: 8px;
}
/* Main stage */
.viewer-stage {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
overflow: auto;
position: relative;
}
.viewer-component {
max-width: 100%;
max-height: 100%;
}
/* Loading */
.viewer-loading {
display: flex;
align-items: center;
justify-content: center;
width: 100%;
height: 100%;
min-height: 200px;
}
/* No-preview fallback */
.viewer-no-preview {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
padding: 32px;
}
@media (max-width: 600px) {
.viewer-nav {
width: 40px;
padding: 4px;
}
}
</style>

View File

@@ -0,0 +1 @@
export { default as FileViewerDialog } from './FileViewerDialog.vue'

View File

@@ -1,27 +1,28 @@
<script setup lang="ts">
import { computed } from 'vue'
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
import { getFileIcon, formatSize, formatDate } from '@/utils/fileHelpers'
import { FileActionsMenu } from '@/components'
type ItemWithType = {
item: FileCollectionObject | FileEntityObject
item: CollectionObject | EntityObject
type: 'collection' | 'entity'
}
const props = defineProps<{
collections: FileCollectionObject[]
entities: FileEntityObject[]
collections: CollectionObject[]
entities: EntityObject[]
selectedIds: Set<string>
}>()
const emit = defineEmits<{
'item-click': [item: FileCollectionObject | FileEntityObject, event: MouseEvent | KeyboardEvent]
'rename': [item: FileCollectionObject | FileEntityObject]
'delete': [item: FileCollectionObject | FileEntityObject]
'download': [item: FileCollectionObject | FileEntityObject]
'show-details': [item: FileCollectionObject | FileEntityObject]
'item-click': [item: CollectionObject | EntityObject, event: MouseEvent | KeyboardEvent]
'open': [item: CollectionObject | EntityObject]
'rename': [item: CollectionObject | EntityObject]
'delete': [item: CollectionObject | EntityObject]
'download': [item: CollectionObject | EntityObject]
'show-details': [item: CollectionObject | EntityObject]
}>()
// Combine collections and entities into a single list for virtual scrolling
@@ -30,7 +31,7 @@ const allItems = computed<ItemWithType[]>(() => [
...props.entities.map(e => ({ item: e, type: 'entity' as const }))
])
function isCollection(wrapped: ItemWithType): wrapped is { item: FileCollectionObject; type: 'collection' } {
function isCollection(wrapped: ItemWithType): wrapped is { item: CollectionObject; type: 'collection' } {
return wrapped.type === 'collection'
}
</script>
@@ -56,18 +57,19 @@ function isCollection(wrapped: ItemWithType): wrapped is { item: FileCollectionO
<div
v-if="isCollection(wrapped)"
class="files-details-row"
:class="{ 'files-details-row--selected': selectedIds.has(wrapped.item.id) }"
:class="{ 'files-details-row--selected': selectedIds.has(String(wrapped.item.identifier)) }"
@click="emit('item-click', wrapped.item, $event)"
>
<div class="files-details-cell files-details-name">
<v-icon color="amber-darken-2" size="small" class="mr-2">mdi-folder</v-icon>
{{ wrapped.item.label }}
{{ wrapped.item.properties.label || String(wrapped.item.identifier ?? '') }}
</div>
<div class="files-details-cell files-details-size"></div>
<div class="files-details-cell files-details-modified">{{ formatDate(wrapped.item.modifiedOn) }}</div>
<div class="files-details-cell files-details-modified">{{ formatDate(wrapped.item.modified) }}</div>
<div class="files-details-cell files-details-actions">
<FileActionsMenu
:item="wrapped.item"
@open="emit('open', $event)"
@rename="emit('rename', $event)"
@delete="emit('delete', $event)"
@download="emit('download', $event)"
@@ -80,18 +82,20 @@ function isCollection(wrapped: ItemWithType): wrapped is { item: FileCollectionO
<div
v-else
class="files-details-row"
:class="{ 'files-details-row--selected': selectedIds.has(wrapped.item.id) }"
:class="{ 'files-details-row--selected': selectedIds.has(String(wrapped.item.identifier)) }"
@click="emit('item-click', wrapped.item, $event)"
@dblclick.stop="emit('open', wrapped.item)"
>
<div class="files-details-cell files-details-name">
<v-icon color="grey" size="small" class="mr-2">{{ getFileIcon(wrapped.item as FileEntityObject) }}</v-icon>
{{ wrapped.item.label }}
<v-icon color="grey" size="small" class="mr-2">{{ getFileIcon(wrapped.item as EntityObject) }}</v-icon>
{{ wrapped.item.properties.label || String(wrapped.item.identifier ?? '') }}
</div>
<div class="files-details-cell files-details-size">{{ formatSize((wrapped.item as FileEntityObject).size) }}</div>
<div class="files-details-cell files-details-modified">{{ formatDate(wrapped.item.modifiedOn) }}</div>
<div class="files-details-cell files-details-size">{{ formatSize(wrapped.item.properties.size) }}</div>
<div class="files-details-cell files-details-modified">{{ formatDate(wrapped.item.modified) }}</div>
<div class="files-details-cell files-details-actions">
<FileActionsMenu
:item="wrapped.item"
@open="emit('open', $event)"
@rename="emit('rename', $event)"
@delete="emit('delete', $event)"
@download="emit('download', $event)"

View File

@@ -1,21 +1,22 @@
<script setup lang="ts">
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
import { getFileIcon, formatSize } from '@/utils/fileHelpers'
import { FileActionsMenu } from '@/components'
defineProps<{
collections: FileCollectionObject[]
entities: FileEntityObject[]
collections: CollectionObject[]
entities: EntityObject[]
selectedIds: Set<string>
}>()
const emit = defineEmits<{
'item-click': [item: FileCollectionObject | FileEntityObject, event: MouseEvent | KeyboardEvent]
'rename': [item: FileCollectionObject | FileEntityObject]
'delete': [item: FileCollectionObject | FileEntityObject]
'download': [item: FileCollectionObject | FileEntityObject]
'show-details': [item: FileCollectionObject | FileEntityObject]
'item-click': [item: CollectionObject | EntityObject, event: MouseEvent | KeyboardEvent]
'open': [item: CollectionObject | EntityObject]
'rename': [item: CollectionObject | EntityObject]
'delete': [item: CollectionObject | EntityObject]
'download': [item: CollectionObject | EntityObject]
'show-details': [item: CollectionObject | EntityObject]
}>()
</script>
@@ -24,9 +25,9 @@ const emit = defineEmits<{
<!-- Folders -->
<div
v-for="folder in collections"
:key="folder.id"
:key="String(folder.identifier)"
class="files-grid-item"
:class="{ selected: selectedIds.has(folder.id) }"
:class="{ selected: selectedIds.has(String(folder.identifier)) }"
@click="emit('item-click', folder, $event)"
>
<div class="files-grid-item-actions">
@@ -34,6 +35,7 @@ const emit = defineEmits<{
:item="folder"
size="x-small"
button-class="action-btn"
@open="emit('open', $event)"
@rename="emit('rename', $event)"
@delete="emit('delete', $event)"
@download="emit('download', $event)"
@@ -41,22 +43,24 @@ const emit = defineEmits<{
/>
</div>
<v-icon size="48" color="amber-darken-2">mdi-folder</v-icon>
<div class="files-grid-label">{{ folder.label }}</div>
<div class="files-grid-label">{{ folder.properties.label || String(folder.identifier ?? '') }}</div>
</div>
<!-- Files -->
<div
v-for="entity in entities"
:key="entity.id"
:key="String(entity.identifier)"
class="files-grid-item"
:class="{ selected: selectedIds.has(entity.id) }"
:class="{ selected: selectedIds.has(String(entity.identifier)) }"
@click="emit('item-click', entity, $event)"
@dblclick.stop="emit('open', entity)"
>
<div class="files-grid-item-actions">
<FileActionsMenu
:item="entity"
size="x-small"
button-class="action-btn"
@open="emit('open', $event)"
@rename="emit('rename', $event)"
@delete="emit('delete', $event)"
@download="emit('download', $event)"
@@ -64,8 +68,8 @@ const emit = defineEmits<{
/>
</div>
<v-icon size="48" color="grey">{{ getFileIcon(entity) }}</v-icon>
<div class="files-grid-label">{{ entity.label }}</div>
<div class="files-grid-size">{{ formatSize(entity.size) }}</div>
<div class="files-grid-label">{{ entity.properties.label || String(entity.identifier ?? '') }}</div>
<div class="files-grid-size">{{ formatSize(entity.properties.size) }}</div>
</div>
</div>
</template>

View File

@@ -1,27 +1,28 @@
<script setup lang="ts">
import { computed } from 'vue'
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
import { getFileIcon, formatSize } from '@/utils/fileHelpers'
import { FileActionsMenu } from '@/components'
type ItemWithType = {
item: FileCollectionObject | FileEntityObject
item: CollectionObject | EntityObject
type: 'collection' | 'entity'
}
const props = defineProps<{
collections: FileCollectionObject[]
entities: FileEntityObject[]
collections: CollectionObject[]
entities: EntityObject[]
selectedIds: Set<string>
}>()
const emit = defineEmits<{
'item-click': [item: FileCollectionObject | FileEntityObject, event: MouseEvent | KeyboardEvent]
'rename': [item: FileCollectionObject | FileEntityObject]
'delete': [item: FileCollectionObject | FileEntityObject]
'download': [item: FileCollectionObject | FileEntityObject]
'show-details': [item: FileCollectionObject | FileEntityObject]
'item-click': [item: CollectionObject | EntityObject, event: MouseEvent | KeyboardEvent]
'open': [item: CollectionObject | EntityObject]
'rename': [item: CollectionObject | EntityObject]
'delete': [item: CollectionObject | EntityObject]
'download': [item: CollectionObject | EntityObject]
'show-details': [item: CollectionObject | EntityObject]
}>()
// Combine collections and entities into a single list for virtual scrolling
@@ -30,7 +31,7 @@ const allItems = computed<ItemWithType[]>(() => [
...props.entities.map(e => ({ item: e, type: 'entity' as const }))
])
function isCollection(wrapped: ItemWithType): wrapped is { item: FileCollectionObject; type: 'collection' } {
function isCollection(wrapped: ItemWithType): wrapped is { item: CollectionObject; type: 'collection' } {
return wrapped.type === 'collection'
}
</script>
@@ -45,16 +46,17 @@ function isCollection(wrapped: ItemWithType): wrapped is { item: FileCollectionO
<!-- Folder -->
<v-list-item
v-if="isCollection(wrapped)"
:active="selectedIds.has(wrapped.item.id)"
:active="selectedIds.has(String(wrapped.item.identifier))"
@click="($event: MouseEvent | KeyboardEvent) => emit('item-click', wrapped.item, $event)"
>
<template #prepend>
<v-icon color="amber-darken-2">mdi-folder</v-icon>
</template>
<v-list-item-title>{{ wrapped.item.label }}</v-list-item-title>
<v-list-item-title>{{ wrapped.item.properties.label || String(wrapped.item.identifier ?? '') }}</v-list-item-title>
<template #append>
<FileActionsMenu
:item="wrapped.item"
@open="emit('open', $event)"
@rename="emit('rename', $event)"
@delete="emit('delete', $event)"
@download="emit('download', $event)"
@@ -66,17 +68,19 @@ function isCollection(wrapped: ItemWithType): wrapped is { item: FileCollectionO
<!-- File -->
<v-list-item
v-else
:active="selectedIds.has(wrapped.item.id)"
:active="selectedIds.has(String(wrapped.item.identifier))"
@click="($event: MouseEvent | KeyboardEvent) => emit('item-click', wrapped.item, $event)"
@dblclick.stop="emit('open', wrapped.item)"
>
<template #prepend>
<v-icon color="grey">{{ getFileIcon(wrapped.item as FileEntityObject) }}</v-icon>
<v-icon color="grey">{{ getFileIcon(wrapped.item as EntityObject) }}</v-icon>
</template>
<v-list-item-title>{{ wrapped.item.label }}</v-list-item-title>
<v-list-item-subtitle>{{ formatSize((wrapped.item as FileEntityObject).size) }}</v-list-item-subtitle>
<v-list-item-title>{{ wrapped.item.properties.label || String(wrapped.item.identifier ?? '') }}</v-list-item-title>
<v-list-item-subtitle>{{ formatSize(wrapped.item.properties.size) }}</v-list-item-subtitle>
<template #append>
<FileActionsMenu
:item="wrapped.item"
@open="emit('open', $event)"
@rename="emit('rename', $event)"
@delete="emit('delete', $event)"
@download="emit('download', $event)"

View File

@@ -5,7 +5,9 @@
export { useFileManager } from './useFileManager'
export { useFileSelection } from './useFileSelection'
export { useFileUpload } from './useFileUpload'
export { useFileViewer } from './useFileViewer'
export type { UseFileManagerOptions } from './useFileManager'
export type { UseFileSelectionOptions } from './useFileSelection'
export type { UseFileUploadOptions, FileUploadProgress } from './useFileUpload'
export type { UseFileViewerReturn } from './useFileViewer'

View File

@@ -5,15 +5,16 @@
import { computed, ref } from 'vue'
import type { Ref, ComputedRef } from 'vue'
import { useProvidersStore } from '@FilesManager/stores/providersStore'
import { useServicesStore } from '@FilesManager/stores/servicesStore'
import { useNodesStore, ROOT_ID } from '@FilesManager/stores/nodesStore'
import type { FilterCondition, SortCondition, RangeCondition } from '@FilesManager/types/common'
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { useProvidersStore } from '@DocumentsManager/stores/providersStore'
import { useServicesStore } from '@DocumentsManager/stores/servicesStore'
import { useNodesStore, ROOT_ID } from '@DocumentsManager/stores/nodesStore'
import type { ListFilter, ListSort, ListRange } from '@DocumentsManager/types/common'
import type { DocumentInterface } from '@DocumentsManager/types/document'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
// Base URL for file manager transfer endpoints
const TRANSFER_BASE_URL = '/m/file_manager'
const TRANSFER_BASE_URL = '/m/documents_manager'
export interface UseFileManagerOptions {
providerId: string
@@ -32,24 +33,24 @@ export function useFileManager(options: UseFileManagerOptions) {
const currentLocation: Ref<string> = ref(ROOT_ID)
// Loading/error state
const isLoading = computed(() => nodesStore.loading)
const isLoading = computed(() => nodesStore.transceiving)
const error = computed(() => nodesStore.error)
// Provider and service
const provider = computed(() => providersStore.getProvider(providerId))
const service = computed(() => servicesStore.getService(providerId, serviceId))
const rootId = computed(() => servicesStore.getRootId(providerId, serviceId) || ROOT_ID)
const provider = computed(() => providersStore.provider(providerId))
const service = computed(() => servicesStore.service(providerId, serviceId))
const rootId = computed(() => ROOT_ID)
// Current children
const currentChildren = computed(() =>
nodesStore.getChildren(providerId, serviceId, currentLocation.value)
)
const currentCollections: ComputedRef<FileCollectionObject[]> = computed(() =>
const currentCollections: ComputedRef<CollectionObject[]> = computed(() =>
nodesStore.getChildCollections(providerId, serviceId, currentLocation.value)
)
const currentEntities: ComputedRef<FileEntityObject[]> = computed(() =>
const currentEntities: ComputedRef<EntityObject[]> = computed(() =>
nodesStore.getChildEntities(providerId, serviceId, currentLocation.value)
)
@@ -77,7 +78,7 @@ export function useFileManager(options: UseFileManagerOptions) {
}
const currentNode = nodesStore.getNode(providerId, serviceId, currentLocation.value)
if (currentNode) {
await navigateTo(currentNode.in || ROOT_ID)
await navigateTo(currentNode.collection ? String(currentNode.collection) : ROOT_ID)
}
}
@@ -88,15 +89,14 @@ export function useFileManager(options: UseFileManagerOptions) {
// Refresh current location
const refresh = async (
filter?: FilterCondition[] | null,
sort?: SortCondition[] | null,
range?: RangeCondition | null
filter?: ListFilter,
sort?: ListSort,
range?: ListRange
) => {
await nodesStore.fetchNodes(
providerId,
serviceId,
currentLocation.value === ROOT_ID ? null : currentLocation.value,
false,
currentLocation.value === ROOT_ID ? ROOT_ID : currentLocation.value,
filter,
sort,
range
@@ -104,12 +104,12 @@ export function useFileManager(options: UseFileManagerOptions) {
}
// Create a new folder
const createFolder = async (label: string): Promise<FileCollectionObject> => {
const createFolder = async (label: string): Promise<CollectionObject> => {
return await nodesStore.createCollection(
providerId,
serviceId,
currentLocation.value === ROOT_ID ? ROOT_ID : currentLocation.value,
{ label }
{ label, owner: '' }
)
}
@@ -117,12 +117,22 @@ export function useFileManager(options: UseFileManagerOptions) {
const createFile = async (
label: string,
mime: string = 'application/octet-stream'
): Promise<FileEntityObject> => {
): Promise<EntityObject> => {
const properties: DocumentInterface = {
'@type': 'documents.properties',
urid: null,
size: 0,
label,
mime,
format: null,
encoding: null,
}
return await nodesStore.createEntity(
providerId,
serviceId,
currentLocation.value === ROOT_ID ? ROOT_ID : currentLocation.value,
{ label, mime }
properties
)
}
@@ -133,10 +143,22 @@ export function useFileManager(options: UseFileManagerOptions) {
throw new Error('Node not found')
}
if (node['@type'] === 'files.collection') {
return await nodesStore.modifyCollection(providerId, serviceId, nodeId, { label: newLabel })
if (node instanceof CollectionObject) {
return await nodesStore.updateCollection(providerId, serviceId, nodeId, {
label: newLabel,
owner: node.properties.owner,
})
} else {
return await nodesStore.modifyEntity(providerId, serviceId, node.in, nodeId, { label: newLabel })
const properties: DocumentInterface = {
'@type': 'documents.properties',
urid: node.properties.urid,
size: node.properties.size,
label: newLabel,
mime: node.properties.mime,
format: node.properties.format,
encoding: node.properties.encoding,
}
return await nodesStore.updateEntity(providerId, serviceId, node.collection, nodeId, properties)
}
}
@@ -147,61 +169,35 @@ export function useFileManager(options: UseFileManagerOptions) {
throw new Error('Node not found')
}
if (node['@type'] === 'files.collection') {
return await nodesStore.destroyCollection(providerId, serviceId, nodeId)
if (node instanceof CollectionObject) {
return await nodesStore.deleteCollection(providerId, serviceId, nodeId)
} else {
return await nodesStore.destroyEntity(providerId, serviceId, node.in, nodeId)
}
}
// Copy a node
const copyNode = async (nodeId: string, destinationId?: string | null) => {
const node = nodesStore.getNode(providerId, serviceId, nodeId)
if (!node) {
throw new Error('Node not found')
}
const destination = destinationId ?? currentLocation.value
if (node['@type'] === 'files.collection') {
return await nodesStore.copyCollection(providerId, serviceId, nodeId, destination)
} else {
return await nodesStore.copyEntity(providerId, serviceId, node.in, nodeId, destination)
}
}
// Move a node
const moveNode = async (nodeId: string, destinationId?: string | null) => {
const node = nodesStore.getNode(providerId, serviceId, nodeId)
if (!node) {
throw new Error('Node not found')
}
const destination = destinationId ?? currentLocation.value
if (node['@type'] === 'files.collection') {
return await nodesStore.moveCollection(providerId, serviceId, nodeId, destination)
} else {
return await nodesStore.moveEntity(providerId, serviceId, node.in, nodeId, destination)
return await nodesStore.deleteEntity(providerId, serviceId, node.collection, nodeId)
}
}
// Read file content
const readFile = async (entityId: string): Promise<string | null> => {
const node = nodesStore.getNode(providerId, serviceId, entityId)
if (!node || node['@type'] !== 'files.entity') {
if (!node || !(node instanceof EntityObject)) {
throw new Error('Entity not found')
}
return await nodesStore.readEntity(providerId, serviceId, node.in || ROOT_ID, entityId)
return await nodesStore.readEntity(providerId, serviceId, node.collection || ROOT_ID, entityId)
}
// Write file content
const writeFile = async (entityId: string, content: string): Promise<number> => {
const node = nodesStore.getNode(providerId, serviceId, entityId)
if (!node || node['@type'] !== 'files.entity') {
if (!node || !(node instanceof EntityObject)) {
throw new Error('Entity not found')
}
return await nodesStore.writeEntity(providerId, serviceId, node.in, entityId, content)
return await nodesStore.writeEntity(providerId, serviceId, node.collection, entityId, content)
}
// Get a URL suitable for inline viewing (img src / video src)
const getEntityUrl = (entityId: string, collectionId?: string | null): string => {
const collection = collectionId ?? currentLocation.value
return `${TRANSFER_BASE_URL}/download/entity/${encodeURIComponent(providerId)}/${encodeURIComponent(serviceId)}/${encodeURIComponent(collection)}/${encodeURIComponent(entityId)}`
}
// Download a single file
@@ -214,7 +210,6 @@ export function useFileManager(options: UseFileManagerOptions) {
window.open(url, '_blank')
}
// Download a collection (folder) as ZIP
const downloadCollection = (collectionId: string): void => {
// Use path parameters: /download/collection/{provider}/{service}/{identifier}
const url = `${TRANSFER_BASE_URL}/download/collection/${encodeURIComponent(providerId)}/${encodeURIComponent(serviceId)}/${encodeURIComponent(collectionId)}`
@@ -222,7 +217,6 @@ export function useFileManager(options: UseFileManagerOptions) {
window.open(url, '_blank')
}
// Download multiple items as ZIP archive
const downloadArchive = (ids: string[], name: string = 'download', collectionId?: string | null): void => {
const collection = collectionId ?? currentLocation.value
const params = new URLSearchParams({
@@ -244,12 +238,8 @@ export function useFileManager(options: UseFileManagerOptions) {
// Initialize - fetch providers, services, and initial nodes if autoFetch
const initialize = async () => {
if (!providersStore.initialized) {
await providersStore.fetchProviders()
}
if (!servicesStore.initialized) {
await servicesStore.fetchServices()
}
await providersStore.list()
await servicesStore.list({ [providerId]: true })
if (autoFetch) {
await refresh()
}
@@ -284,10 +274,9 @@ export function useFileManager(options: UseFileManagerOptions) {
createFile,
renameNode,
deleteNode,
copyNode,
moveNode,
readFile,
writeFile,
getEntityUrl,
downloadEntity,
downloadCollection,
downloadArchive,

View File

@@ -5,10 +5,10 @@
import { ref, computed } from 'vue'
import type { Ref, ComputedRef } from 'vue'
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
type NodeRecord = FileCollectionObject | FileEntityObject
type NodeRecord = CollectionObject | EntityObject
export interface UseFileSelectionOptions {
multiple?: boolean
@@ -20,145 +20,107 @@ export function useFileSelection(options: UseFileSelectionOptions = {}) {
const {
multiple = true,
allowFolders = true,
allowFiles = true
allowFiles = true,
} = options
const selectedIds: Ref<Set<string>> = ref(new Set())
const selectedNodes: Ref<Map<string, NodeRecord>> = ref(new Map())
// Get selected count
const count: ComputedRef<number> = computed(() => selectedIds.value.size)
// Check if any selected
const hasSelection: ComputedRef<boolean> = computed(() => selectedIds.value.size > 0)
// Get selected IDs as array
const selectedIdArray: ComputedRef<string[]> = computed(() =>
Array.from(selectedIds.value)
const selectedIdArray: ComputedRef<string[]> = computed(() => Array.from(selectedIds.value))
const selectedNodeArray: ComputedRef<NodeRecord[]> = computed(() => Array.from(selectedNodes.value.values()))
const selectedCollections: ComputedRef<CollectionObject[]> = computed(() =>
selectedNodeArray.value.filter((node): node is CollectionObject => node instanceof CollectionObject),
)
// Get selected nodes as array
const selectedNodeArray: ComputedRef<NodeRecord[]> = computed(() =>
Array.from(selectedNodes.value.values())
const selectedEntities: ComputedRef<EntityObject[]> = computed(() =>
selectedNodeArray.value.filter((node): node is EntityObject => node instanceof EntityObject),
)
// Get selected collections only
const selectedCollections: ComputedRef<FileCollectionObject[]> = computed(() =>
selectedNodeArray.value.filter(
(node): node is FileCollectionObject => node['@type'] === 'files.collection'
)
)
const isSelected = (nodeId: string): boolean => selectedIds.value.has(nodeId)
// Get selected entities only
const selectedEntities: ComputedRef<FileEntityObject[]> = computed(() =>
selectedNodeArray.value.filter(
(node): node is FileEntityObject => node['@type'] === 'files.entity'
)
)
// Check if a node is selected
const isSelected = (nodeId: string): boolean => {
return selectedIds.value.has(nodeId)
}
// Check if node type is allowed
const isTypeAllowed = (node: NodeRecord): boolean => {
if (node['@type'] === 'files.collection' && !allowFolders) {
return false
}
if (node['@type'] === 'files.entity' && !allowFiles) {
return false
}
if (node instanceof CollectionObject && !allowFolders) return false
if (node instanceof EntityObject && !allowFiles) return false
return true
}
// Select a node
const select = (node: NodeRecord) => {
if (!isTypeAllowed(node)) {
return
}
if (!isTypeAllowed(node)) return
if (!multiple) {
// Clear previous selection for single select
selectedIds.value.clear()
selectedNodes.value.clear()
}
selectedIds.value.add(node.id)
selectedNodes.value.set(node.id, node)
const nodeId = String(node.identifier)
selectedIds.value.add(nodeId)
selectedNodes.value.set(nodeId, node)
}
// Deselect a node
const deselect = (nodeId: string) => {
selectedIds.value.delete(nodeId)
selectedNodes.value.delete(nodeId)
}
// Toggle selection
const toggle = (node: NodeRecord) => {
if (isSelected(node.id)) {
deselect(node.id)
} else {
const nodeId = String(node.identifier)
if (isSelected(nodeId)) {
deselect(nodeId)
return
}
select(node)
}
}
// Select multiple nodes
const selectMultiple = (nodes: NodeRecord[]) => {
if (!multiple) {
// For single select, only select the last one
const lastNode = nodes[nodes.length - 1]
if (lastNode && isTypeAllowed(lastNode)) {
selectedIds.value.clear()
selectedNodes.value.clear()
selectedIds.value.add(lastNode.id)
selectedNodes.value.set(lastNode.id, lastNode)
const nodeId = String(lastNode.identifier)
selectedIds.value.add(nodeId)
selectedNodes.value.set(nodeId, lastNode)
}
return
}
for (const node of nodes) {
if (isTypeAllowed(node)) {
selectedIds.value.add(node.id)
selectedNodes.value.set(node.id, node)
const nodeId = String(node.identifier)
selectedIds.value.add(nodeId)
selectedNodes.value.set(nodeId, node)
}
}
}
// Select all from a list
const selectAll = (nodes: NodeRecord[]) => {
if (!multiple) {
return
}
if (!multiple) return
selectMultiple(nodes)
}
// Clear selection
const clear = () => {
selectedIds.value.clear()
selectedNodes.value.clear()
}
// Set selection (replace current)
const setSelection = (nodes: NodeRecord[]) => {
clear()
selectMultiple(nodes)
}
return {
// State
selectedIds,
selectedNodes,
// Computed
count,
hasSelection,
selectedIdArray,
selectedNodeArray,
selectedCollections,
selectedEntities,
// Methods
isSelected,
select,
deselect,

View File

@@ -6,15 +6,16 @@
import { ref, computed } from 'vue'
import type { Ref, ComputedRef } from 'vue'
import { useNodesStore, ROOT_ID } from '@FilesManager/stores/nodesStore'
import { FileEntityObject } from '@FilesManager/models/entity'
import { useNodesStore, ROOT_ID } from '@DocumentsManager/stores/nodesStore'
import { EntityObject } from '@DocumentsManager/models/entity'
import type { DocumentInterface } from '@DocumentsManager/types/document'
export interface FileUploadProgress {
file: File
progress: number
status: 'pending' | 'uploading' | 'completed' | 'error'
error?: string
entity?: FileEntityObject
entity?: EntityObject
/** Relative path within folder upload (e.g., "folder/subfolder/file.txt") */
relativePath?: string
}
@@ -230,9 +231,9 @@ export function useFileUpload(options: UseFileUploadOptions) {
providerId,
serviceId,
parentId,
{ label: folderName }
{ label: folderName, owner: '' }
)
folderIdMap.set(folderPath, collection.id)
folderIdMap.set(folderPath, String(collection.identifier))
} catch (e) {
console.error(`Failed to create folder: ${folderPath}`, e)
// Try to continue with other folders
@@ -246,7 +247,7 @@ export function useFileUpload(options: UseFileUploadOptions) {
const uploadFile = async (
uploadId: string,
folderIdMap?: Map<string, string>
): Promise<FileEntityObject | null> => {
): Promise<EntityObject | null> => {
const upload = uploads.value.get(uploadId)
if (!upload || upload.status !== 'pending') {
return null
@@ -278,12 +279,16 @@ export function useFileUpload(options: UseFileUploadOptions) {
const entity = await nodesStore.createEntity(
providerId,
serviceId,
targetCollection,
targetCollection || ROOT_ID,
{
'@type': 'documents.properties',
urid: null,
format: null,
encoding: null,
label: upload.file.name,
mime: upload.file.type || 'application/octet-stream',
size: upload.file.size,
}
} as DocumentInterface
)
upload.progress = 75
@@ -292,8 +297,8 @@ export function useFileUpload(options: UseFileUploadOptions) {
await nodesStore.writeEntity(
providerId,
serviceId,
targetCollection,
entity.id,
targetCollection || ROOT_ID,
String(entity.identifier),
content
)
@@ -325,9 +330,9 @@ export function useFileUpload(options: UseFileUploadOptions) {
}
// Upload all pending files
const uploadAll = async (): Promise<FileEntityObject[]> => {
const uploadAll = async (): Promise<EntityObject[]> => {
isUploading.value = true
const entities: FileEntityObject[] = []
const entities: EntityObject[] = []
try {
// Check if any uploads have relative paths (folder upload)
@@ -377,7 +382,7 @@ export function useFileUpload(options: UseFileUploadOptions) {
}
// Retry a failed upload
const retryUpload = async (uploadId: string): Promise<FileEntityObject | null> => {
const retryUpload = async (uploadId: string): Promise<EntityObject | null> => {
const upload = uploads.value.get(uploadId)
if (!upload || upload.status !== 'error') {
return null

View File

@@ -0,0 +1,81 @@
/**
* useFileViewer — resolves which registered viewer can handle a given MIME type.
*
* Other modules register viewers at the `documents_file_viewer` integration
* point by including an entry in their `integrations.ts`:
*
* ```ts
* documents_file_viewer: [{
* id: 'my_viewer',
* meta: { mimeTypes: ['application/pdf'] },
* component: () => import('./components/MyViewer.vue'),
* }]
* ```
*
* Viewer components receive the props: `url: string`, `entity: EntityObject`, `mime: string`.
*/
import { useIntegrationStore } from '@KTXC'
import type { EntityObject } from '@DocumentsManager/models/entity'
const INTEGRATION_POINT = 'documents_file_viewer'
function mimeMatchesPattern(mime: string, pattern: string): boolean {
if (pattern.endsWith('/*')) {
// e.g. 'image/*' matches 'image/png', 'image/jpeg', …
return mime.startsWith(pattern.slice(0, -1))
}
return mime === pattern
}
function viewerMatchesMime(
mime: string,
mimeTypes?: string[],
mimePatterns?: string[],
): boolean {
if (mimeTypes?.includes(mime)) return true
if (mimePatterns) {
for (const pattern of mimePatterns) {
if (mimeMatchesPattern(mime, pattern)) return true
}
}
return false
}
export function useFileViewer() {
const integrationStore = useIntegrationStore()
/**
* Returns the highest-priority registered viewer that can handle `mime`,
* or `null` if none is found.
*/
function findViewer(mime: string) {
// getItems() already returns items sorted by priority (ascending)
const viewers = integrationStore.getItems(INTEGRATION_POINT)
for (const viewer of viewers) {
if (
viewerMatchesMime(
mime,
viewer.meta?.mimeTypes as string[] | undefined,
viewer.meta?.mimePatterns as string[] | undefined,
)
) {
return viewer
}
}
return null
}
/**
* Convenience: returns true if any registered viewer can open this entity.
*/
function canOpen(entity: EntityObject): boolean {
const mime = entity.properties.mime
if (!mime) return false
return findViewer(mime) !== null
}
return { findViewer, canOpen }
}
export type UseFileViewerReturn = ReturnType<typeof useFileViewer>

View File

@@ -3,9 +3,9 @@ import type { ModuleIntegrations } from "@KTXC/types/moduleTypes";
const integrations: ModuleIntegrations = {
app_menu: [
{
id: 'files',
label: 'Files',
path: '/files',
id: 'documents',
label: 'Documents',
path: '/',
icon: 'mdi-folder-outline',
priority: 30,
},

View File

@@ -3,8 +3,8 @@ import { ref, computed, onMounted, watch } from 'vue'
import { useModuleStore } from '@KTXC'
import { useFileManager, useFileSelection, useFileUpload } from '@/composables'
import type { ViewMode, SortField, SortOrder, BreadcrumbItem } from '@/types'
import { FileCollectionObject } from '@FilesManager/models/collection'
import { FileEntityObject } from '@FilesManager/models/entity'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
// Components
import {
@@ -17,6 +17,7 @@ import {
FilesGridView,
FilesListView,
FilesDetailsView,
FileViewerDialog,
NewFolderDialog,
RenameDialog,
DeleteConfirmDialog,
@@ -26,7 +27,7 @@ import {
// Check if file manager is available
const moduleStore = useModuleStore()
const isFileManagerAvailable = computed(() => {
return moduleStore.has('file_manager') || moduleStore.has('FileManager')
return moduleStore.has('documents_manager') || moduleStore.has('DocumentsManager')
})
// Active provider/service (will be selectable later)
@@ -65,16 +66,54 @@ const showNewFolderDialog = ref(false)
const showRenameDialog = ref(false)
const showDeleteDialog = ref(false)
const showUploadDialog = ref(false)
const nodeToRename = ref<FileCollectionObject | FileEntityObject | null>(null)
const nodesToDelete = ref<(FileCollectionObject | FileEntityObject)[]>([])
const nodeToRename = ref<CollectionObject | EntityObject | null>(null)
const nodesToDelete = ref<(CollectionObject | EntityObject)[]>([])
// Drag and drop state
const isDragOver = ref(false)
// Viewer state
const viewerEntity = ref<EntityObject | null>(null)
const showViewer = ref(false)
function handleOpenItem(item: CollectionObject | EntityObject) {
if (item instanceof EntityObject) {
viewerEntity.value = item
showViewer.value = true
} else {
// Folders: navigate into them when opened via double-click / action
selection.clear()
handleFolderOpen(item as CollectionObject)
}
}
function handleViewerNavigate(entity: EntityObject) {
viewerEntity.value = entity
}
// Hidden file inputs
const fileInputRef = ref<HTMLInputElement | null>(null)
const folderInputRef = ref<HTMLInputElement | null>(null)
function nodeId(node: CollectionObject | EntityObject): string {
return String(node.identifier ?? '')
}
function nodeLabel(node: CollectionObject | EntityObject): string {
if (node instanceof EntityObject) {
return node.properties.label || nodeId(node)
}
return node.properties.label || nodeId(node)
}
function renameCurrentName(node: CollectionObject | EntityObject | null): string {
if (!node) return ''
if (node instanceof EntityObject) {
return node.properties.label || nodeId(node)
}
return node.properties.label || nodeId(node)
}
// Computed
const breadcrumbs = computed<BreadcrumbItem[]>(() => {
const items: BreadcrumbItem[] = [
@@ -83,8 +122,8 @@ const breadcrumbs = computed<BreadcrumbItem[]>(() => {
for (const node of fileManager.breadcrumbs.value) {
items.push({
id: node.id,
label: node.label,
id: nodeId(node),
label: nodeLabel(node),
isRoot: false,
})
}
@@ -98,24 +137,59 @@ const sortedItems = computed(() => {
// Sort collections
collections.sort((a, b) => {
const aVal = a[sortField.value as keyof FileCollectionObject] ?? ''
const bVal = b[sortField.value as keyof FileCollectionObject] ?? ''
const aVal = sortField.value === 'label'
? (a.properties.label || nodeId(a))
: sortField.value === 'modifiedOn'
? (a.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (a.created?.getTime() ?? 0)
: ''
const bVal = sortField.value === 'label'
? (b.properties.label || nodeId(b))
: sortField.value === 'modifiedOn'
? (b.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (b.created?.getTime() ?? 0)
: ''
const cmp = String(aVal).localeCompare(String(bVal))
return sortOrder.value === 'asc' ? cmp : -cmp
})
// Sort entities
entities.sort((a, b) => {
const aVal = a[sortField.value as keyof FileEntityObject] ?? ''
const bVal = b[sortField.value as keyof FileEntityObject] ?? ''
const aVal = sortField.value === 'label'
? (a.properties.label || nodeId(a))
: sortField.value === 'mime'
? (a.properties.mime || '')
: sortField.value === 'size'
? a.properties.size
: sortField.value === 'modifiedOn'
? (a.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (a.created?.getTime() ?? 0)
: ''
const bVal = sortField.value === 'label'
? (b.properties.label || nodeId(b))
: sortField.value === 'mime'
? (b.properties.mime || '')
: sortField.value === 'size'
? b.properties.size
: sortField.value === 'modifiedOn'
? (b.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (b.created?.getTime() ?? 0)
: ''
const cmp = String(aVal).localeCompare(String(bVal))
return sortOrder.value === 'asc' ? cmp : -cmp
})
// Filter by search
const filterFn = (item: FileCollectionObject | FileEntityObject) => {
const filterFn = (item: CollectionObject | EntityObject) => {
if (!searchQuery.value) return true
return item.label.toLowerCase().includes(searchQuery.value.toLowerCase())
const label = item instanceof EntityObject
? (item.properties.label || nodeId(item))
: (item.properties.label || nodeId(item))
return label.toLowerCase().includes(searchQuery.value.toLowerCase())
}
return {
@@ -136,13 +210,13 @@ async function handleBreadcrumbNavigate(item: BreadcrumbItem) {
await fileManager.navigateTo(item.isRoot ? null : item.id)
}
async function handleFolderOpen(folder: FileCollectionObject) {
async function handleFolderOpen(folder: CollectionObject) {
selection.clear()
await fileManager.navigateTo(folder.id)
await fileManager.navigateTo(nodeId(folder))
}
// Item interaction methods
function handleItemClick(item: FileCollectionObject | FileEntityObject, event: MouseEvent | KeyboardEvent) {
function handleItemClick(item: CollectionObject | EntityObject, event: MouseEvent | KeyboardEvent) {
const hasCtrl = event.ctrlKey || event.metaKey
const hasShift = event.shiftKey
@@ -154,10 +228,10 @@ function handleItemClick(item: FileCollectionObject | FileEntityObject, event: M
selection.select(item)
} else {
// Single click behavior depends on item type
if (item['@type'] === 'files.collection') {
if (item instanceof CollectionObject) {
// Folders: navigate into them
selection.clear()
handleFolderOpen(item as FileCollectionObject)
handleFolderOpen(item as CollectionObject)
} else {
// Files: show info panel
selection.clear()
@@ -167,7 +241,7 @@ function handleItemClick(item: FileCollectionObject | FileEntityObject, event: M
}
// Show details panel for an item
function handleShowDetails(item: FileCollectionObject | FileEntityObject) {
function handleShowDetails(item: CollectionObject | EntityObject) {
selection.clear()
selection.select(item)
}
@@ -183,7 +257,7 @@ async function handleCreateFolder(name: string) {
}
// Rename operations - for specific item
function handleRenameItem(item: FileCollectionObject | FileEntityObject) {
function handleRenameItem(item: CollectionObject | EntityObject) {
nodeToRename.value = item
showRenameDialog.value = true
}
@@ -192,7 +266,7 @@ async function handleRename(newName: string) {
if (!nodeToRename.value) return
try {
await fileManager.renameNode(nodeToRename.value.id, newName)
await fileManager.renameNode(nodeId(nodeToRename.value), newName)
showRenameDialog.value = false
nodeToRename.value = null
} catch (error) {
@@ -201,7 +275,7 @@ async function handleRename(newName: string) {
}
// Delete operations - for specific item
function handleDeleteItem(item: FileCollectionObject | FileEntityObject) {
function handleDeleteItem(item: CollectionObject | EntityObject) {
nodesToDelete.value = [item]
showDeleteDialog.value = true
}
@@ -209,7 +283,7 @@ function handleDeleteItem(item: FileCollectionObject | FileEntityObject) {
async function handleDelete() {
try {
for (const node of nodesToDelete.value) {
await fileManager.deleteNode(node.id)
await fileManager.deleteNode(nodeId(node))
}
selection.clear()
showDeleteDialog.value = false
@@ -220,13 +294,13 @@ async function handleDelete() {
}
// Download operation
function handleDownloadItem(item: FileCollectionObject | FileEntityObject) {
if (item['@type'] === 'files.entity') {
function handleDownloadItem(item: CollectionObject | EntityObject) {
if (item instanceof EntityObject) {
// Download single file
fileManager.downloadEntity(item.id, item.in)
} else if (item['@type'] === 'files.collection') {
fileManager.downloadEntity(nodeId(item), String(item.collection ?? fileManager.ROOT_ID))
} else if (item instanceof CollectionObject) {
// Download folder as ZIP
fileManager.downloadCollection(item.id)
fileManager.downloadCollection(nodeId(item))
}
}
@@ -448,6 +522,7 @@ onMounted(async () => {
:entities="sortedItems.entities"
:selected-ids="selectedIds"
@item-click="handleItemClick"
@open="handleOpenItem"
@rename="handleRenameItem"
@delete="handleDeleteItem"
@download="handleDownloadItem"
@@ -461,6 +536,7 @@ onMounted(async () => {
:entities="sortedItems.entities"
:selected-ids="selectedIds"
@item-click="handleItemClick"
@open="handleOpenItem"
@rename="handleRenameItem"
@delete="handleDeleteItem"
@download="handleDownloadItem"
@@ -474,6 +550,7 @@ onMounted(async () => {
:entities="sortedItems.entities"
:selected-ids="selectedIds"
@item-click="handleItemClick"
@open="handleOpenItem"
@rename="handleRenameItem"
@delete="handleDeleteItem"
@download="handleDownloadItem"
@@ -506,7 +583,7 @@ onMounted(async () => {
<RenameDialog
v-model="showRenameDialog"
:current-name="nodeToRename?.label ?? ''"
:current-name="renameCurrentName(nodeToRename)"
@rename="handleRename"
/>
@@ -535,6 +612,16 @@ onMounted(async () => {
:selected-items="selection.selectedNodeArray.value"
@close="selection.clear()"
/>
<!-- File Viewer -->
<FileViewerDialog
v-model="showViewer"
:entity="viewerEntity"
:all-entities="sortedItems.entities"
:get-url="fileManager.getEntityUrl"
:download-entity="fileManager.downloadEntity"
@navigate="handleViewerNavigate"
/>
</div>
</template>

View File

@@ -2,8 +2,8 @@ import type { RouteRecordRaw } from 'vue-router'
const routes: RouteRecordRaw[] = [
{
name: 'files',
path: '/files',
name: 'documents',
path: '/',
component: () => import('@/pages/FilesPage.vue')
},
]

View File

@@ -0,0 +1,222 @@
import { computed, ref } from 'vue'
import { defineStore } from 'pinia'
import { useProvidersStore, useServicesStore, useNodesStore, ROOT_ID } from '@DocumentsManager/stores'
import { CollectionObject } from '@DocumentsManager/models/collection'
import { EntityObject } from '@DocumentsManager/models/entity'
import type { SortField, SortOrder, ViewMode, BreadcrumbItem } from '@/types'
type NodeRecord = CollectionObject | EntityObject
export const useDocumentsStore = defineStore('documentsStore', () => {
const providersStore = useProvidersStore()
const servicesStore = useServicesStore()
const nodesStore = useNodesStore()
const activeProviderId = ref('default')
const activeServiceId = ref<string | number>('personal')
const currentLocation = ref<string>(ROOT_ID)
const viewMode = ref<ViewMode>('grid')
const sortField = ref<SortField>('label')
const sortOrder = ref<SortOrder>('asc')
const searchQuery = ref('')
const sidebarVisible = ref(true)
const transceiving = computed(() =>
providersStore.transceiving || servicesStore.transceiving || nodesStore.transceiving,
)
const provider = computed(() => providersStore.provider(activeProviderId.value))
const service = computed(() => servicesStore.service(activeProviderId.value, activeServiceId.value))
const currentCollections = computed(() =>
nodesStore.getChildCollections(activeProviderId.value, activeServiceId.value, currentLocation.value),
)
const currentEntities = computed(() =>
nodesStore.getChildEntities(activeProviderId.value, activeServiceId.value, currentLocation.value),
)
const breadcrumbs = computed<BreadcrumbItem[]>(() => {
const nodes = nodesStore.getPath(activeProviderId.value, activeServiceId.value, currentLocation.value)
return [
{ id: ROOT_ID, label: 'Home', isRoot: true },
...nodes.map((node) => ({
id: String(node.identifier),
label: node.properties.label,
isRoot: false,
})),
]
})
function sortCollections(items: CollectionObject[]): CollectionObject[] {
return [...items].sort((a, b) => {
const aVal = sortField.value === 'label'
? a.properties.label
: sortField.value === 'modifiedOn'
? (a.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (a.created?.getTime() ?? 0)
: ''
const bVal = sortField.value === 'label'
? b.properties.label
: sortField.value === 'modifiedOn'
? (b.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (b.created?.getTime() ?? 0)
: ''
const cmp = String(aVal).localeCompare(String(bVal))
return sortOrder.value === 'asc' ? cmp : -cmp
})
}
function sortEntities(items: EntityObject[]): EntityObject[] {
return [...items].sort((a, b) => {
const aVal = sortField.value === 'label'
? a.properties.label
: sortField.value === 'mime'
? (a.properties.mime ?? '')
: sortField.value === 'size'
? a.properties.size
: sortField.value === 'modifiedOn'
? (a.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (a.created?.getTime() ?? 0)
: ''
const bVal = sortField.value === 'label'
? b.properties.label
: sortField.value === 'mime'
? (b.properties.mime ?? '')
: sortField.value === 'size'
? b.properties.size
: sortField.value === 'modifiedOn'
? (b.modified?.getTime() ?? 0)
: sortField.value === 'createdOn'
? (b.created?.getTime() ?? 0)
: ''
const cmp = String(aVal).localeCompare(String(bVal))
return sortOrder.value === 'asc' ? cmp : -cmp
})
}
function filterNode(node: NodeRecord): boolean {
if (!searchQuery.value) return true
return node.properties.label.toLowerCase().includes(searchQuery.value.toLowerCase())
}
const sortedItems = computed(() => ({
collections: sortCollections(currentCollections.value).filter(filterNode),
entities: sortEntities(currentEntities.value).filter(filterNode),
}))
const hasItems = computed(() =>
sortedItems.value.collections.length > 0 || sortedItems.value.entities.length > 0,
)
const isAtRoot = computed(() => currentLocation.value === ROOT_ID)
async function initialize() {
await providersStore.list()
await servicesStore.list({ [activeProviderId.value]: true })
await refresh()
}
async function refresh() {
await nodesStore.fetchNodes(activeProviderId.value, activeServiceId.value, currentLocation.value)
}
async function navigateTo(collectionId: string | null) {
currentLocation.value = collectionId || ROOT_ID
await refresh()
}
async function navigateToRoot() {
await navigateTo(ROOT_ID)
}
async function navigateUp() {
if (currentLocation.value === ROOT_ID) return
const currentNode = nodesStore.getNode(activeProviderId.value, activeServiceId.value, currentLocation.value)
if (!currentNode) return
const parentId = currentNode.collection ? String(currentNode.collection) : ROOT_ID
await navigateTo(parentId)
}
async function createFolder(label: string) {
await nodesStore.createCollection(
activeProviderId.value,
activeServiceId.value,
currentLocation.value,
{ label, owner: '' },
)
await refresh()
}
async function renameNode(node: NodeRecord, label: string) {
if (node instanceof CollectionObject) {
await nodesStore.updateCollection(
activeProviderId.value,
activeServiceId.value,
node.identifier,
{ label, owner: node.properties.owner },
)
} else {
await nodesStore.updateEntity(
activeProviderId.value,
activeServiceId.value,
node.collection,
node.identifier,
{
'@type': 'documents.properties',
urid: node.properties.urid,
size: node.properties.size,
label,
mime: node.properties.mime,
format: node.properties.format,
encoding: node.properties.encoding,
},
)
}
await refresh()
}
async function deleteNode(node: NodeRecord) {
if (node instanceof CollectionObject) {
await nodesStore.deleteCollection(activeProviderId.value, activeServiceId.value, node.identifier)
} else {
await nodesStore.deleteEntity(activeProviderId.value, activeServiceId.value, node.collection, node.identifier)
}
await refresh()
}
return {
activeProviderId,
activeServiceId,
currentLocation,
viewMode,
sortField,
sortOrder,
searchQuery,
sidebarVisible,
transceiving,
provider,
service,
currentCollections,
currentEntities,
sortedItems,
hasItems,
breadcrumbs,
isAtRoot,
initialize,
refresh,
navigateTo,
navigateToRoot,
navigateUp,
createFolder,
renameNode,
deleteNode,
ROOT_ID,
}
})

1
src/stores/index.ts Normal file
View File

@@ -0,0 +1 @@
export { useDocumentsStore } from './documentsStore'

View File

@@ -28,3 +28,23 @@ export interface ContextMenuAction {
disabled?: boolean
divider?: boolean
}
/**
* Shape of an item registered at the `documents_file_viewer` integration point.
* Stored under `meta` so it fits inside a standard `ModuleIntegrationItem`.
*/
export interface DocumentViewerMeta {
/** Exact MIME type matches, e.g. ['application/pdf'] */
mimeTypes?: string[]
/** Glob-style patterns, e.g. ['image/*', 'video/*'] */
mimePatterns?: string[]
}
export interface DocumentViewerItem {
id: string
label?: string
priority?: number
meta: DocumentViewerMeta
/** Async factory returning the Vue viewer component */
component: () => Promise<unknown>
}

View File

@@ -1,10 +1,10 @@
import { FileEntityObject } from '@FilesManager/models/entity'
import { EntityObject } from '@DocumentsManager/models/entity'
/**
* Get the appropriate icon for a file based on its MIME type
*/
export function getFileIcon(entity: FileEntityObject): string {
const mime = entity.mime || ''
export function getFileIcon(entity: EntityObject): string {
const mime = entity.properties.mime || ''
if (!mime) return 'mdi-file'
if (mime.startsWith('image/')) return 'mdi-file-image'
if (mime.startsWith('video/')) return 'mdi-file-video'
@@ -22,19 +22,22 @@ export function getFileIcon(entity: FileEntityObject): string {
* Format file size in human readable format
*/
export function formatSize(bytes: number): string {
if (bytes === 0) return '0 B'
const safeBytes = Number.isFinite(bytes) ? bytes : 0
if (safeBytes === 0) return '0 B'
const k = 1024
const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
const i = Math.floor(Math.log(safeBytes) / Math.log(k))
return parseFloat((safeBytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}
/**
* Format date string to localized format
*/
export function formatDate(dateStr: string): string {
if (!dateStr) return '—'
return new Date(dateStr).toLocaleDateString('en-US', {
export function formatDate(value: Date | string | null | undefined): string {
if (!value) return '—'
const date = value instanceof Date ? value : new Date(value)
if (Number.isNaN(date.getTime())) return '—'
return date.toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',

View File

@@ -7,14 +7,14 @@
"paths": {
"@/*": ["./src/*"],
"@KTXC/*": ["../../core/src/*"],
"@FilesManager/*": ["../file_manager/src/*"]
"@DocumentsManager/*": ["../documents_manager/src/*"]
}
},
"include": [
"src/**/*.ts",
"src/**/*.tsx",
"src/**/*.vue",
"../file_manager/src/**/*.ts",
"../documents_manager/src/**/*.ts",
"../../core/src/**/*.ts"
]
}

View File

@@ -27,7 +27,7 @@ export default defineConfig({
alias: {
'@': path.resolve(__dirname, './src'),
'@KTXC': path.resolve(__dirname, '../../core/src'),
'@filesManager': path.resolve(__dirname, '../files_manager/src'),
'@DocumentsManager': path.resolve(__dirname, '../documents_manager/src'),
},
},
build: {
@@ -45,19 +45,19 @@ export default defineConfig({
'vue-router',
'pinia',
'@KTXC',
/^@FilesManager\//,
/^@DocumentsManager\//,
],
output: {
paths: (id) => {
if (id === '@KTXC') return '/js/ktxc.mjs'
if (id.startsWith('@FilesManager/')) {
return '/modules/file_manager/static/module.mjs'
if (id.startsWith('@DocumentsManager/')) {
return '/modules/documents_manager/static/module.mjs'
}
return id
},
assetFileNames: (assetInfo) => {
if (assetInfo.name?.endsWith('.css')) {
return 'files-[hash].css'
return 'documents-[hash].css'
}
return '[name]-[hash][extname]'
}