feat(#211): E3 — Document library (/docs), filters, bulk actions, multi-file import, StatusBadge

- StatusBadge component with 6 lifecycle states, compact/full variants, tooltip (#215)
- DocsLibraryPage: table (Name/Status/Stores/Updated), empty state (#211)
- Filter bar: status pills, store chips, debounced search, URL sync (#212)
- Multi-select with sticky bulk bar: Re-chunk, Push to store modal, Delete (#213)
- DocsNewPage: multi-file drop zone with per-file progress, sequential upload (#214)
- Document.stores?: string[] field, formatRelativeTime(iso, locale) helper
- rechunkDocument / pushDocumentToStore API + store actions (rechunk / pushToStore)
- i18n keys status.*, docs.*, docsNew.* in FR + EN

Closes #211, Closes #212, Closes #213, Closes #214, Closes #215
This commit is contained in:
Pier-Jean Malandrino 2026-04-30 09:30:29 +02:00 committed by GitHub
parent d121874fb0
commit 59af8acdc6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 1620 additions and 21 deletions

View file

@ -1,5 +1,13 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { fetchDocuments, fetchDocument, uploadDocument, deleteDocument, getPreviewUrl } from './api'
import {
fetchDocuments,
fetchDocument,
uploadDocument,
deleteDocument,
getPreviewUrl,
rechunkDocument,
pushDocumentToStore,
} from './api'
vi.mock('../../shared/api/http', () => ({
apiFetch: vi.fn(),
@ -62,4 +70,25 @@ describe('document API', () => {
it('getPreviewUrl accepts custom page and dpi', () => {
expect(getPreviewUrl('abc', 3, 300)).toBe('/api/documents/abc/preview?page=3&dpi=300')
})
it('rechunkDocument calls POST /api/documents/:id/rechunk', async () => {
apiFetch.mockResolvedValue({ jobId: 'job-1' })
const result = await rechunkDocument('42')
expect(apiFetch).toHaveBeenCalledWith('/api/documents/42/rechunk', { method: 'POST' })
expect(result).toEqual({ jobId: 'job-1' })
})
it('pushDocumentToStore calls POST /api/documents/:id/push with store', async () => {
apiFetch.mockResolvedValue({ jobId: 'job-2' })
const result = await pushDocumentToStore('42', 'my-store')
expect(apiFetch).toHaveBeenCalledWith('/api/documents/42/push', {
method: 'POST',
body: JSON.stringify({ store: 'my-store' }),
})
expect(result).toEqual({ jobId: 'job-2' })
})
})

View file

@ -26,3 +26,14 @@ export function deleteDocument(id: string): Promise<unknown> {
export function getPreviewUrl(id: string, page = 1, dpi = 150): string {
return `/api/documents/${id}/preview?page=${page}&dpi=${dpi}`
}
export function rechunkDocument(id: string): Promise<{ jobId: string }> {
return apiFetch<{ jobId: string }>(`/api/documents/${id}/rechunk`, { method: 'POST' })
}
export function pushDocumentToStore(id: string, store: string): Promise<{ jobId: string }> {
return apiFetch<{ jobId: string }>(`/api/documents/${id}/push`, {
method: 'POST',
body: JSON.stringify({ store }),
})
}

View file

@ -6,6 +6,8 @@ vi.mock('./api', () => ({
fetchDocuments: vi.fn(),
uploadDocument: vi.fn(),
deleteDocument: vi.fn(),
rechunkDocument: vi.fn(),
pushDocumentToStore: vi.fn(),
}))
import * as api from './api'
@ -120,4 +122,51 @@ describe('useDocumentStore', () => {
store.select('42')
expect(store.selectedId).toBe('42')
})
it('load() sets loading to false after success', async () => {
api.fetchDocuments.mockResolvedValue([])
const store = useDocumentStore()
await store.load()
expect(store.loading).toBe(false)
})
it('load() sets loading to false after error', async () => {
api.fetchDocuments.mockRejectedValue(new Error('fail'))
vi.spyOn(console, 'error').mockImplementation(() => {})
const store = useDocumentStore()
await store.load()
expect(store.loading).toBe(false)
})
it('rechunk() returns jobId on success', async () => {
api.rechunkDocument.mockResolvedValue({ jobId: 'j1' })
const store = useDocumentStore()
const result = await store.rechunk('42')
expect(api.rechunkDocument).toHaveBeenCalledWith('42')
expect(result).toBe('j1')
})
it('rechunk() returns null on error', async () => {
api.rechunkDocument.mockRejectedValue(new Error('fail'))
vi.spyOn(console, 'error').mockImplementation(() => {})
const store = useDocumentStore()
const result = await store.rechunk('42')
expect(result).toBeNull()
})
it('pushToStore() returns jobId on success', async () => {
api.pushDocumentToStore.mockResolvedValue({ jobId: 'j2' })
const store = useDocumentStore()
const result = await store.pushToStore('42', 'my-store')
expect(api.pushDocumentToStore).toHaveBeenCalledWith('42', 'my-store')
expect(result).toBe('j2')
})
it('pushToStore() returns null on error', async () => {
api.pushDocumentToStore.mockRejectedValue(new Error('fail'))
vi.spyOn(console, 'error').mockImplementation(() => {})
const store = useDocumentStore()
const result = await store.pushToStore('42', 'my-store')
expect(result).toBeNull()
})
})

View file

@ -7,6 +7,7 @@ import * as api from './api'
export const useDocumentStore = defineStore('document', () => {
const documents = ref<Document[]>([])
const selectedId = ref<string | null>(null)
const loading = ref(false)
const uploading = ref(false)
const error = ref<string | null>(null)
@ -15,12 +16,15 @@ export const useDocumentStore = defineStore('document', () => {
}
async function load(): Promise<void> {
loading.value = true
try {
error.value = null
documents.value = await api.fetchDocuments()
} catch (e) {
error.value = (e as Error).message || 'Failed to load documents'
console.error('Failed to load documents', e)
} finally {
loading.value = false
}
}
@ -61,5 +65,40 @@ export const useDocumentStore = defineStore('document', () => {
selectedId.value = id
}
return { documents, selectedId, uploading, error, clearError, load, upload, remove, select }
async function rechunk(id: string): Promise<string | null> {
try {
const res = await api.rechunkDocument(id)
return res.jobId
} catch (e) {
error.value = (e as Error).message || 'Failed to rechunk'
console.error('Rechunk failed', e)
return null
}
}
async function pushToStore(id: string, store: string): Promise<string | null> {
try {
const res = await api.pushDocumentToStore(id, store)
return res.jobId
} catch (e) {
error.value = (e as Error).message || 'Failed to push to store'
console.error('Push to store failed', e)
return null
}
}
return {
documents,
selectedId,
loading,
uploading,
error,
clearError,
load,
upload,
remove,
select,
rechunk,
pushToStore,
}
})

View file

@ -0,0 +1,91 @@
<template>
<span
class="status-badge"
:class="[`status-badge--${state}`, { 'status-badge--compact': compact }]"
:title="tooltip"
:aria-label="label"
>
<span aria-hidden="true" class="status-symbol">{{ symbol }}</span>
<span v-if="!compact" class="status-text">{{ label }}</span>
</span>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useI18n } from '../../../shared/i18n'
import type { DocumentLifecycleState } from '../../../shared/types'
const props = withDefaults(
defineProps<{
state: DocumentLifecycleState
compact?: boolean
}>(),
{ compact: false },
)
const { t } = useI18n()
const SYMBOLS: Record<DocumentLifecycleState, string> = {
Uploaded: '○',
Parsed: '◐',
Chunked: '◑',
Ingested: '●',
Stale: '⚠',
Failed: '✗',
}
const symbol = computed(() => SYMBOLS[props.state] ?? '?')
const label = computed(() => t(`status.${props.state}`))
const tooltip = computed(() => t(`status.tooltip.${props.state}`))
</script>
<style scoped>
.status-badge {
display: inline-flex;
align-items: center;
gap: 5px;
font-size: 12px;
font-weight: 500;
padding: 2px 8px;
border-radius: 999px;
white-space: nowrap;
cursor: default;
}
.status-badge--Uploaded {
background: rgba(99, 102, 241, 0.12);
color: #818cf8;
}
.status-badge--Parsed {
background: rgba(59, 130, 246, 0.12);
color: var(--info);
}
.status-badge--Chunked {
background: rgba(249, 115, 22, 0.12);
color: var(--accent);
}
.status-badge--Ingested {
background: rgba(34, 197, 94, 0.12);
color: var(--success);
}
.status-badge--Stale {
background: rgba(234, 179, 8, 0.12);
color: var(--warning);
}
.status-badge--Failed {
background: rgba(239, 68, 68, 0.12);
color: var(--error);
}
.status-badge--compact {
padding: 0;
background: transparent;
gap: 0;
}
.status-symbol {
font-size: 1em;
line-height: 1;
}
</style>

View file

@ -1,39 +1,851 @@
<template>
<div>
<div class="library-page">
<!-- Flash: redirected here because all workspace modes are disabled (#210) -->
<div v-if="showFlashAllModesDisabled" class="flash flash--warning" role="alert">
{{ t('flags.allModesDisabled') }}
</div>
<ComingSoonShell
:title="t('comingSoon.title')"
:subtitle="t('comingSoon.subtitle.docsLibrary')"
/>
<!-- Page header -->
<div class="library-header">
<h1 class="library-title">{{ t('docs.title') }}</h1>
<RouterLink :to="{ name: ROUTES.DOCS_NEW }" class="btn-primary">
{{ t('docs.import') }}
</RouterLink>
</div>
<!-- Filter bar (#212) -->
<div v-if="docStore.documents.length" class="filter-bar">
<!-- Status pills -->
<div class="filter-group">
<button
v-for="state in ALL_STATES"
:key="state"
class="filter-pill"
:class="{ active: statusFilter.has(state) }"
@click="toggleStatus(state)"
>
<StatusBadge :state="state" compact />
{{ t(`status.${state}`) }}
</button>
</div>
<!-- Store pills (shown only when at least one doc has stores) -->
<div v-if="allStores.length" class="filter-group">
<button
v-for="store in allStores"
:key="store"
class="filter-pill filter-pill--store"
:class="{ active: storeFilter.has(store) }"
@click="toggleStore(store)"
>
{{ store }}
</button>
</div>
<!-- Search -->
<input
v-model="searchInput"
type="search"
class="filter-search"
:placeholder="t('docs.filterSearch')"
/>
<!-- Clear -->
<button v-if="hasActiveFilters" class="filter-clear" @click="clearFilters">
{{ t('docs.filterClear') }}
</button>
</div>
<!-- Loading skeleton -->
<div v-if="docStore.loading" class="loading-state">
<div class="spinner" />
</div>
<!-- Table (#211) -->
<div v-else-if="docStore.documents.length" class="table-wrapper">
<table class="doc-table" data-e2e="docs-table">
<thead>
<tr>
<th class="col-check">
<input
type="checkbox"
:checked="allSelected"
:indeterminate="someSelected"
:aria-label="t('docs.selected', { n: filteredDocs.length })"
@change="toggleAll"
/>
</th>
<th>{{ t('docs.colName') }}</th>
<th>{{ t('docs.colStatus') }}</th>
<th>{{ t('docs.colStores') }}</th>
<th class="col-updated">{{ t('docs.colUpdated') }}</th>
</tr>
</thead>
<tbody>
<tr
v-for="doc in filteredDocs"
:key="doc.id"
class="doc-row"
data-e2e="doc-row"
@click="openDoc(doc.id)"
>
<td class="col-check" @click.stop>
<input
type="checkbox"
:checked="selectedIds.has(doc.id)"
@change="toggleDoc(doc.id)"
/>
</td>
<td class="col-name">
<svg class="doc-icon" viewBox="0 0 20 20" fill="currentColor">
<path
fill-rule="evenodd"
d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"
clip-rule="evenodd"
/>
</svg>
<span class="doc-filename" :title="doc.filename">{{ doc.filename }}</span>
</td>
<td class="col-status">
<StatusBadge :state="doc.lifecycleState" />
</td>
<td class="col-stores">
<span v-if="doc.stores?.length" class="store-chips">
<span v-for="s in doc.stores" :key="s" class="store-chip">{{ s }}</span>
</span>
<span v-else class="no-value"></span>
</td>
<td class="col-updated">
<span class="updated-time">{{ formatUpdated(doc) }}</span>
</td>
</tr>
</tbody>
</table>
<!-- Filtered empty state -->
<div v-if="!filteredDocs.length" class="empty-state empty-state--filtered">
<p class="empty-title">{{ t('docs.emptyFiltered') }}</p>
<button class="btn-secondary" @click="clearFilters">{{ t('docs.filterClear') }}</button>
</div>
</div>
<!-- Empty corpus state -->
<div v-else-if="!docStore.loading" class="empty-state" data-e2e="docs-empty">
<svg
class="empty-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1"
>
<path
d="M7 21h10a2 2 0 002-2V9.414a1 1 0 00-.293-.707l-5.414-5.414A1 1 0 0012.586 3H7a2 2 0 00-2 2v14a2 2 0 002 2z"
/>
</svg>
<p class="empty-title">{{ t('docs.emptyTitle') }}</p>
<p class="empty-subtitle">{{ t('docs.emptySubtitle') }}</p>
<RouterLink :to="{ name: ROUTES.DOCS_NEW }" class="btn-primary">
{{ t('docs.emptyAction') }}
</RouterLink>
</div>
<!-- Sticky bulk action bar (#213) -->
<div v-if="selectedIds.size > 0" class="bulk-bar" data-e2e="bulk-bar">
<span class="bulk-count">{{ t('docs.selected', { n: selectedIds.size }) }}</span>
<div class="bulk-actions">
<button class="btn-sm" @click="bulkRechunk">{{ t('docs.bulkRechunk') }}</button>
<button class="btn-sm" @click="openPushModal">{{ t('docs.bulkPush') }}</button>
<button class="btn-sm btn-sm--danger" @click="bulkDelete">
{{ t('docs.bulkDelete') }}
</button>
<button class="btn-sm btn-sm--ghost" @click="clearSelection">
{{ t('docs.bulkCancel') }}
</button>
</div>
</div>
<!-- Push to store modal -->
<div
v-if="showPushModal"
class="modal-overlay"
role="dialog"
:aria-label="t('docs.pushTitle')"
@click.self="showPushModal = false"
>
<div class="modal">
<h3 class="modal-title">{{ t('docs.pushTitle') }}</h3>
<label class="modal-label" for="push-store-input">{{ t('docs.pushLabel') }}</label>
<input
id="push-store-input"
v-model="pushStoreName"
class="modal-input"
list="store-datalist"
:placeholder="t('docs.pushPlaceholder')"
@keyup.enter="confirmPush"
@keyup.escape="showPushModal = false"
/>
<datalist id="store-datalist">
<option v-for="s in availableStores" :key="s" :value="s" />
</datalist>
<div class="modal-footer">
<button class="btn-primary" :disabled="!pushStoreName.trim()" @click="confirmPush">
{{ t('docs.pushSubmit') }}
</button>
<button class="btn-secondary" @click="showPushModal = false">
{{ t('docs.pushCancel') }}
</button>
</div>
</div>
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
import { useRoute } from 'vue-router'
import { computed, onMounted, ref, watch } from 'vue'
import { RouterLink, useRoute, useRouter } from 'vue-router'
import { useDocumentStore } from '../features/document/store'
import StatusBadge from '../features/document/ui/StatusBadge.vue'
import { useI18n } from '../shared/i18n'
import ComingSoonShell from '../shared/ui/ComingSoonShell.vue'
import { ROUTES } from '../shared/routing/names'
import type { Document, DocumentLifecycleState } from '../shared/types'
import { formatRelativeTime } from '../shared/format'
import { appLocale } from '../shared/appConfig'
const { t } = useI18n()
const ALL_STATES: DocumentLifecycleState[] = [
'Uploaded',
'Parsed',
'Chunked',
'Ingested',
'Stale',
'Failed',
]
const docStore = useDocumentStore()
const route = useRoute()
const router = useRouter()
const { t } = useI18n()
// Surfaced when the router redirected here because every doc workspace
// mode is feature-flagged off (#210). #211 will replace this with a
// proper banner inside the library page.
// ---------------------------------------------------------------------------
// Flash for "no-mode-enabled" redirect (#210)
// ---------------------------------------------------------------------------
const showFlashAllModesDisabled = computed(() => route.query.reason === 'no-mode-enabled')
// ---------------------------------------------------------------------------
// Filters init from URL query params (#212)
// ---------------------------------------------------------------------------
function parseSetParam(raw: unknown): Set<string> {
const str = typeof raw === 'string' ? raw : ''
return new Set(str.split(',').filter(Boolean))
}
const statusFilter = ref<Set<DocumentLifecycleState>>(
parseSetParam(route.query.status) as Set<DocumentLifecycleState>,
)
const storeFilter = ref<Set<string>>(parseSetParam(route.query.store))
const searchInput = ref<string>(typeof route.query.q === 'string' ? route.query.q : '')
const debouncedSearch = ref<string>(searchInput.value)
let searchTimer: ReturnType<typeof setTimeout> | null = null
watch(searchInput, (val) => {
if (searchTimer) clearTimeout(searchTimer)
searchTimer = setTimeout(() => {
debouncedSearch.value = val
syncUrl()
}, 300)
})
function syncUrl(): void {
const query: Record<string, string> = {}
if (statusFilter.value.size) query.status = [...statusFilter.value].join(',')
if (storeFilter.value.size) query.store = [...storeFilter.value].join(',')
if (debouncedSearch.value) query.q = debouncedSearch.value
router.replace({ query })
}
function toggleStatus(state: DocumentLifecycleState): void {
const next = new Set(statusFilter.value)
if (next.has(state)) next.delete(state)
else next.add(state)
statusFilter.value = next
syncUrl()
}
function toggleStore(store: string): void {
const next = new Set(storeFilter.value)
if (next.has(store)) next.delete(store)
else next.add(store)
storeFilter.value = next
syncUrl()
}
const hasActiveFilters = computed(
() => statusFilter.value.size > 0 || storeFilter.value.size > 0 || !!debouncedSearch.value,
)
function clearFilters(): void {
statusFilter.value = new Set()
storeFilter.value = new Set()
searchInput.value = ''
debouncedSearch.value = ''
router.replace({ query: {} })
}
// ---------------------------------------------------------------------------
// Derived store list for store-filter chips and push modal datalist
// ---------------------------------------------------------------------------
const allStores = computed(() => {
const acc = new Set<string>()
docStore.documents.forEach((d) => d.stores?.forEach((s) => acc.add(s)))
return [...acc].sort()
})
const availableStores = allStores
// ---------------------------------------------------------------------------
// Filtered documents
// ---------------------------------------------------------------------------
const filteredDocs = computed(() => {
const q = debouncedSearch.value.toLowerCase()
return docStore.documents.filter((doc) => {
if (statusFilter.value.size && !statusFilter.value.has(doc.lifecycleState)) return false
if (storeFilter.value.size && !doc.stores?.some((s) => storeFilter.value.has(s))) return false
if (q && !doc.filename.toLowerCase().includes(q)) return false
return true
})
})
// ---------------------------------------------------------------------------
// Table helpers
// ---------------------------------------------------------------------------
function formatUpdated(doc: Document): string {
return formatRelativeTime(doc.lifecycleStateAt ?? doc.createdAt, appLocale.value)
}
function openDoc(id: string): void {
router.push({ name: ROUTES.DOC_WORKSPACE, params: { id } })
}
// ---------------------------------------------------------------------------
// Multi-select (#213)
// ---------------------------------------------------------------------------
const selectedIds = ref<Set<string>>(new Set())
const allSelected = computed(
() =>
filteredDocs.value.length > 0 && filteredDocs.value.every((d) => selectedIds.value.has(d.id)),
)
const someSelected = computed(
() => filteredDocs.value.some((d) => selectedIds.value.has(d.id)) && !allSelected.value,
)
function toggleDoc(id: string): void {
const next = new Set(selectedIds.value)
if (next.has(id)) next.delete(id)
else next.add(id)
selectedIds.value = next
}
function toggleAll(): void {
if (allSelected.value) {
const next = new Set(selectedIds.value)
filteredDocs.value.forEach((d) => next.delete(d.id))
selectedIds.value = next
} else {
const next = new Set(selectedIds.value)
filteredDocs.value.forEach((d) => next.add(d.id))
selectedIds.value = next
}
}
function clearSelection(): void {
selectedIds.value = new Set()
}
// ---------------------------------------------------------------------------
// Bulk actions
// ---------------------------------------------------------------------------
async function bulkRechunk(): Promise<void> {
const ids = [...selectedIds.value]
clearSelection()
const jobs = await Promise.all(ids.map((id) => docStore.rechunk(id)))
const dispatched = jobs.filter(Boolean)
if (dispatched.length) {
// Surface job ids as a brief toast via window.alert for now
// E9 (RunsPage) will provide proper job tracking
window.alert(t('docs.jobDispatched', { jobId: dispatched.join(', ') }))
}
}
const showPushModal = ref(false)
const pushStoreName = ref('')
function openPushModal(): void {
pushStoreName.value = availableStores.value[0] ?? ''
showPushModal.value = true
}
async function confirmPush(): Promise<void> {
const target = pushStoreName.value.trim()
if (!target) return
showPushModal.value = false
const ids = [...selectedIds.value]
clearSelection()
const jobs = await Promise.all(ids.map((id) => docStore.pushToStore(id, target)))
const dispatched = jobs.filter(Boolean)
if (dispatched.length) {
window.alert(t('docs.jobDispatched', { jobId: dispatched.join(', ') }))
}
}
async function bulkDelete(): Promise<void> {
const n = selectedIds.value.size
if (!window.confirm(t('docs.deleteConfirm', { n }))) return
const ids = [...selectedIds.value]
clearSelection()
await Promise.all(ids.map((id) => docStore.remove(id)))
}
// ---------------------------------------------------------------------------
// Lifecycle
// ---------------------------------------------------------------------------
onMounted(() => {
docStore.load()
})
</script>
<style scoped>
.library-page {
display: flex;
flex-direction: column;
height: 100%;
overflow: hidden;
position: relative;
}
/* Header */
.library-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20px 24px 16px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.library-title {
font-size: 20px;
font-weight: 600;
color: var(--text);
}
/* Flash */
.flash {
margin: 1rem;
padding: 0.75rem 1rem;
border-radius: 6px;
font-size: 0.875rem;
margin: 12px 24px 0;
padding: 10px 14px;
border-radius: var(--radius-sm);
font-size: 13px;
flex-shrink: 0;
}
.flash--warning {
color: #92400e;
background: #fef3c7;
border: 1px solid #fde68a;
}
/* Filter bar */
.filter-bar {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 8px;
padding: 12px 24px;
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.filter-group {
display: flex;
align-items: center;
gap: 4px;
flex-wrap: wrap;
}
.filter-pill {
display: inline-flex;
align-items: center;
gap: 5px;
padding: 4px 10px;
border-radius: 999px;
font-size: 12px;
font-weight: 500;
color: var(--text-secondary);
background: var(--bg-elevated);
border: 1px solid var(--border);
cursor: pointer;
transition: all var(--transition);
white-space: nowrap;
}
.filter-pill:hover {
border-color: var(--accent);
color: var(--text);
}
.filter-pill.active {
background: var(--accent-muted);
border-color: var(--accent);
color: var(--accent);
}
.filter-search {
flex: 1;
min-width: 180px;
max-width: 300px;
padding: 6px 10px;
border-radius: var(--radius-sm);
border: 1px solid var(--border);
background: var(--bg-elevated);
color: var(--text);
font-size: 13px;
outline: none;
transition: border-color var(--transition);
}
.filter-search:focus {
border-color: var(--accent);
}
.filter-clear {
padding: 4px 10px;
font-size: 12px;
color: var(--text-muted);
background: none;
border: none;
cursor: pointer;
transition: color var(--transition);
}
.filter-clear:hover {
color: var(--text);
}
/* Loading */
.loading-state {
display: flex;
justify-content: center;
padding: 60px;
}
.spinner {
width: 28px;
height: 28px;
border: 2px solid var(--border-light);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* Table */
.table-wrapper {
flex: 1;
overflow-y: auto;
padding: 0 24px 80px; /* 80px bottom pad for bulk bar */
}
.doc-table {
width: 100%;
border-collapse: collapse;
font-size: 13px;
}
.doc-table thead {
position: sticky;
top: 0;
background: var(--bg);
z-index: 1;
}
.doc-table th {
padding: 10px 12px;
text-align: left;
font-size: 11px;
font-weight: 600;
color: var(--text-muted);
text-transform: uppercase;
letter-spacing: 0.05em;
border-bottom: 1px solid var(--border);
}
.col-check {
width: 40px;
}
.col-updated {
width: 130px;
white-space: nowrap;
}
.doc-row {
cursor: pointer;
transition: background var(--transition);
border-bottom: 1px solid var(--border);
}
.doc-row:hover {
background: var(--bg-hover);
}
.doc-table td {
padding: 12px 12px;
vertical-align: middle;
}
.col-name {
display: flex;
align-items: center;
gap: 8px;
min-width: 0;
}
.doc-icon {
width: 14px;
height: 14px;
color: var(--accent);
flex-shrink: 0;
}
.doc-filename {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 500;
color: var(--text);
}
.store-chips {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.store-chip {
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-family: 'IBM Plex Mono', monospace;
background: var(--bg-elevated);
border: 1px solid var(--border-light);
color: var(--text-secondary);
white-space: nowrap;
}
.no-value {
color: var(--text-muted);
}
.updated-time {
color: var(--text-muted);
font-size: 12px;
font-family: 'IBM Plex Mono', monospace;
}
/* Empty states */
.empty-state {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 12px;
padding: 80px 24px;
text-align: center;
}
.empty-icon {
width: 48px;
height: 48px;
color: var(--text-muted);
}
.empty-title {
font-size: 16px;
font-weight: 600;
color: var(--text);
}
.empty-subtitle {
font-size: 13px;
color: var(--text-secondary);
}
.empty-state--filtered {
padding: 40px 24px;
}
/* Bulk action bar */
.bulk-bar {
position: absolute;
bottom: 0;
left: 0;
right: 0;
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 24px;
background: var(--bg-elevated);
border-top: 1px solid var(--border);
gap: 12px;
}
.bulk-count {
font-size: 13px;
font-weight: 600;
color: var(--text);
white-space: nowrap;
}
.bulk-actions {
display: flex;
gap: 8px;
}
/* Buttons */
.btn-primary {
display: inline-flex;
align-items: center;
gap: 6px;
padding: 7px 14px;
font-size: 13px;
font-weight: 500;
color: white;
background: var(--accent);
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
text-decoration: none;
transition: background var(--transition);
}
.btn-primary:hover {
background: var(--accent-hover);
}
.btn-primary:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.btn-secondary {
padding: 7px 14px;
font-size: 13px;
font-weight: 500;
color: var(--text-secondary);
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
cursor: pointer;
transition: all var(--transition);
}
.btn-secondary:hover {
background: var(--bg-hover);
color: var(--text);
}
.btn-sm {
padding: 5px 12px;
font-size: 12px;
font-weight: 500;
color: var(--text-secondary);
background: var(--bg-surface);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
cursor: pointer;
transition: all var(--transition);
white-space: nowrap;
}
.btn-sm:hover {
background: var(--bg-hover);
color: var(--text);
}
.btn-sm--danger {
color: var(--error);
border-color: rgba(239, 68, 68, 0.3);
}
.btn-sm--danger:hover {
background: rgba(239, 68, 68, 0.1);
}
.btn-sm--ghost {
border-color: transparent;
background: transparent;
}
/* Push modal */
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.6);
display: flex;
align-items: center;
justify-content: center;
z-index: 100;
}
.modal {
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 24px;
width: 360px;
display: flex;
flex-direction: column;
gap: 12px;
}
.modal-title {
font-size: 15px;
font-weight: 600;
color: var(--text);
}
.modal-label {
font-size: 12px;
font-weight: 500;
color: var(--text-secondary);
}
.modal-input {
padding: 8px 10px;
border-radius: var(--radius-sm);
border: 1px solid var(--border);
background: var(--bg-surface);
color: var(--text);
font-size: 13px;
outline: none;
width: 100%;
transition: border-color var(--transition);
}
.modal-input:focus {
border-color: var(--accent);
}
.modal-footer {
display: flex;
gap: 8px;
justify-content: flex-end;
margin-top: 4px;
}
</style>

View file

@ -1,11 +1,391 @@
<template>
<ComingSoonShell :title="t('comingSoon.title')" :subtitle="t('comingSoon.subtitle.docsNew')" />
<div class="docs-new-page">
<!-- Header -->
<div class="page-header">
<RouterLink :to="{ name: ROUTES.DOCS_LIBRARY }" class="back-link">
<svg viewBox="0 0 20 20" fill="currentColor" class="back-icon">
<path
fill-rule="evenodd"
d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z"
clip-rule="evenodd"
/>
</svg>
{{ t('docsNew.backToLibrary') }}
</RouterLink>
<h1 class="page-title">{{ t('docsNew.title') }}</h1>
</div>
<!-- Drop zone -->
<div
class="drop-zone"
:class="{ dragging, disabled: isUploading }"
data-e2e="drop-zone"
@dragover.prevent="onDragOver"
@dragleave.prevent="dragging = false"
@drop.prevent="onDrop"
@click="openPicker"
>
<input ref="fileInput" type="file" multiple accept=".pdf" hidden @change="onFileSelect" />
<svg
class="drop-icon"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
>
<path d="M12 16V4m0 0L8 8m4-4l4 4M4 17v2a1 1 0 001 1h14a1 1 0 001-1v-2" />
</svg>
<p class="drop-text">{{ t('docsNew.drop') }}</p>
<p class="drop-hint">{{ t('docsNew.dropHint') }}</p>
</div>
<!-- Per-file upload list -->
<ul v-if="uploads.length" class="upload-list" data-e2e="upload-list">
<li
v-for="(item, idx) in uploads"
:key="idx"
class="upload-item"
:class="`upload-item--${item.status}`"
data-e2e="upload-item"
>
<svg class="upload-item-icon" viewBox="0 0 20 20" fill="currentColor">
<path
fill-rule="evenodd"
d="M4 4a2 2 0 012-2h4.586A2 2 0 0112 2.586L15.414 6A2 2 0 0116 7.414V16a2 2 0 01-2 2H6a2 2 0 01-2-2V4z"
clip-rule="evenodd"
/>
</svg>
<span class="upload-item-name" :title="item.file.name">{{ item.file.name }}</span>
<span class="upload-item-status">{{ statusLabel(item.status) }}</span>
<span v-if="item.status === 'uploading'" class="upload-spinner" />
<RouterLink
v-if="item.status === 'done' && item.docId"
:to="{ name: ROUTES.DOC_WORKSPACE, params: { id: item.docId } }"
class="upload-item-link"
>
{{ t('docsNew.viewDoc') }}
</RouterLink>
<span v-if="item.status === 'failed'" class="upload-item-error">{{ item.error }}</span>
</li>
</ul>
<!-- All done state -->
<div v-if="allDone && uploads.length" class="done-state" data-e2e="done-state">
<p class="done-msg">{{ t('docsNew.allDone') }}</p>
<RouterLink :to="{ name: ROUTES.DOCS_LIBRARY }" class="btn-primary">
{{ t('docsNew.viewLibrary') }}
</RouterLink>
</div>
</div>
</template>
<script setup lang="ts">
import { useI18n } from '../shared/i18n'
import { computed, ref } from 'vue'
import { RouterLink } from 'vue-router'
import ComingSoonShell from '../shared/ui/ComingSoonShell.vue'
import { uploadDocument } from '../features/document/api'
import { useI18n } from '../shared/i18n'
import { ROUTES } from '../shared/routing/names'
import { appMaxFileSizeMb } from '../shared/appConfig'
type UploadStatus = 'queued' | 'uploading' | 'done' | 'failed'
interface UploadItem {
file: File
status: UploadStatus
docId?: string
error?: string
}
const { t } = useI18n()
const fileInput = ref<HTMLInputElement | null>(null)
const dragging = ref(false)
const uploads = ref<UploadItem[]>([])
const isUploading = computed(() => uploads.value.some((u) => u.status === 'uploading'))
const allDone = computed(
() =>
uploads.value.length > 0 &&
uploads.value.every((u) => u.status === 'done' || u.status === 'failed'),
)
function statusLabel(status: UploadStatus): string {
return t(`docsNew.${status}`)
}
function isPdf(file: File): boolean {
return file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf')
}
function openPicker(): void {
if (isUploading.value) return
fileInput.value?.click()
}
function onDragOver(): void {
if (!isUploading.value) dragging.value = true
}
function onFileSelect(e: Event): void {
dragging.value = false
const target = e.target as HTMLInputElement
const files = target.files ? [...target.files] : []
target.value = ''
enqueue(files)
}
function onDrop(e: DragEvent): void {
dragging.value = false
const files = e.dataTransfer?.files ? [...e.dataTransfer.files] : []
enqueue(files)
}
function enqueue(files: File[]): void {
const pdfs = files.filter(isPdf)
if (!pdfs.length) return
const newItems: UploadItem[] = pdfs.map((f) => ({ file: f, status: 'queued' }))
uploads.value = [...uploads.value, ...newItems]
// Upload sequentially to avoid overloading the backend
processQueue()
}
async function processQueue(): Promise<void> {
for (const item of uploads.value) {
if (item.status !== 'queued') continue
await uploadOne(item)
}
}
async function uploadOne(item: UploadItem): Promise<void> {
const maxMb = appMaxFileSizeMb.value
if (maxMb > 0 && item.file.size > maxMb * 1024 * 1024) {
item.status = 'failed'
item.error = t('upload.tooLarge').replace('{n}', String(maxMb))
return
}
item.status = 'uploading'
try {
const doc = await uploadDocument(item.file)
item.status = 'done'
item.docId = doc.id
} catch (e) {
item.status = 'failed'
item.error = (e as Error).message || 'Upload failed'
}
}
</script>
<style scoped>
.docs-new-page {
display: flex;
flex-direction: column;
gap: 24px;
padding: 24px;
overflow-y: auto;
height: 100%;
}
/* Header */
.page-header {
display: flex;
flex-direction: column;
gap: 8px;
}
.back-link {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 13px;
color: var(--text-secondary);
text-decoration: none;
transition: color var(--transition);
}
.back-link:hover {
color: var(--text);
}
.back-icon {
width: 14px;
height: 14px;
}
.page-title {
font-size: 20px;
font-weight: 600;
color: var(--text);
}
/* Drop zone */
.drop-zone {
border: 2px dashed var(--border-light);
border-radius: var(--radius);
padding: 48px 24px;
display: flex;
flex-direction: column;
align-items: center;
gap: 10px;
cursor: pointer;
transition: all var(--transition);
text-align: center;
}
.drop-zone:hover,
.drop-zone.dragging {
border-color: var(--accent);
background: var(--accent-muted);
}
.drop-zone.disabled {
pointer-events: none;
opacity: 0.5;
}
.drop-icon {
width: 40px;
height: 40px;
color: var(--text-muted);
}
.drop-text {
font-size: 15px;
font-weight: 500;
color: var(--text-secondary);
}
.drop-hint {
font-size: 12px;
color: var(--text-muted);
}
/* Upload list */
.upload-list {
list-style: none;
display: flex;
flex-direction: column;
gap: 4px;
}
.upload-item {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 14px;
border-radius: var(--radius-sm);
background: var(--bg-elevated);
border: 1px solid var(--border);
font-size: 13px;
}
.upload-item-icon {
width: 14px;
height: 14px;
color: var(--accent);
flex-shrink: 0;
}
.upload-item-name {
flex: 1;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-weight: 500;
color: var(--text);
}
.upload-item-status {
font-size: 12px;
color: var(--text-muted);
font-family: 'IBM Plex Mono', monospace;
flex-shrink: 0;
}
.upload-item--done .upload-item-status {
color: var(--success);
}
.upload-item--failed .upload-item-status {
color: var(--error);
}
.upload-spinner {
width: 14px;
height: 14px;
border: 2px solid var(--border-light);
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.6s linear infinite;
flex-shrink: 0;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
.upload-item-link {
font-size: 12px;
color: var(--accent);
text-decoration: none;
flex-shrink: 0;
}
.upload-item-link:hover {
text-decoration: underline;
}
.upload-item-error {
font-size: 11px;
color: var(--error);
flex-shrink: 0;
max-width: 200px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* Done state */
.done-state {
display: flex;
flex-direction: column;
align-items: center;
gap: 12px;
padding: 24px;
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius);
text-align: center;
}
.done-msg {
font-size: 14px;
color: var(--success);
font-weight: 500;
}
/* Shared button */
.btn-primary {
display: inline-flex;
align-items: center;
padding: 7px 16px;
font-size: 13px;
font-weight: 500;
color: white;
background: var(--accent);
border: none;
border-radius: var(--radius-sm);
cursor: pointer;
text-decoration: none;
transition: background var(--transition);
}
.btn-primary:hover {
background: var(--accent-hover);
}
</style>

View file

@ -0,0 +1,66 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { formatRelativeTime, formatSize } from './format'
describe('formatSize', () => {
it('returns empty string for falsy value', () => {
expect(formatSize(null)).toBe('')
expect(formatSize(undefined)).toBe('')
expect(formatSize(0)).toBe('')
})
it('formats bytes below 1MB as KB', () => {
expect(formatSize(512 * 1024)).toBe('512 KB')
})
it('formats bytes above 1MB as MB', () => {
expect(formatSize(2.5 * 1024 * 1024)).toBe('2.5 MB')
})
})
describe('formatRelativeTime', () => {
const now = new Date('2025-01-01T12:00:00Z').getTime()
beforeEach(() => {
vi.useFakeTimers()
vi.setSystemTime(now)
})
afterEach(() => {
vi.useRealTimers()
})
it('returns em-dash for null', () => {
expect(formatRelativeTime(null)).toBe('—')
expect(formatRelativeTime(undefined)).toBe('—')
})
it('uses seconds for recent timestamps', () => {
const iso = new Date(now - 30_000).toISOString()
const result = formatRelativeTime(iso, 'en')
expect(result).toMatch(/30 seconds ago/)
})
it('uses minutes for timestamps 259 min ago', () => {
const iso = new Date(now - 5 * 60_000).toISOString()
const result = formatRelativeTime(iso, 'en')
expect(result).toMatch(/5 minutes ago/)
})
it('uses hours for timestamps 123h ago', () => {
const iso = new Date(now - 3 * 3_600_000).toISOString()
const result = formatRelativeTime(iso, 'en')
expect(result).toMatch(/3 hours ago/)
})
it('uses days for timestamps < 30 days ago', () => {
const iso = new Date(now - 7 * 86_400_000).toISOString()
const result = formatRelativeTime(iso, 'en')
expect(result).toMatch(/7 days ago/)
})
it('uses months for older timestamps', () => {
const iso = new Date(now - 60 * 86_400_000).toISOString()
const result = formatRelativeTime(iso, 'en')
expect(result).toMatch(/2 months ago/)
})
})

View file

@ -3,3 +3,17 @@ export function formatSize(bytes: number | null | undefined): string {
const mb = bytes / (1024 * 1024)
return mb >= 1 ? `${mb.toFixed(1)} MB` : `${(bytes / 1024).toFixed(0)} KB`
}
export function formatRelativeTime(iso: string | null | undefined, locale = 'fr'): string {
if (!iso) return '—'
const diffMs = Date.now() - new Date(iso).getTime()
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' })
const abs = Math.abs(diffMs)
const dir = diffMs >= 0 ? -1 : 1
if (abs < 60_000) return rtf.format(dir * Math.round(abs / 1_000), 'second')
if (abs < 3_600_000) return rtf.format(dir * Math.round(abs / 60_000), 'minute')
if (abs < 86_400_000) return rtf.format(dir * Math.round(abs / 3_600_000), 'hour')
if (abs < 30 * 86_400_000) return rtf.format(dir * Math.round(abs / 86_400_000), 'day')
return rtf.format(dir * Math.round(abs / (30 * 86_400_000)), 'month')
}

View file

@ -37,6 +37,59 @@ const messages: Messages = {
'flags.allModesDisabled':
"Aucun mode (Ask / Inspect / Chunks) n'est activé pour ce déploiement. Contactez votre administrateur.",
// Lifecycle status badges (#215)
'status.Uploaded': 'Uploadé',
'status.Parsed': 'Parsé',
'status.Chunked': 'Chunké',
'status.Ingested': 'Ingéré',
'status.Stale': 'Obsolète',
'status.Failed': 'Échoué',
'status.tooltip.Uploaded': 'Fichier reçu, en attente de parsing.',
'status.tooltip.Parsed': 'Document parsé avec succès.',
'status.tooltip.Chunked': 'Chunks générés, prêts à être poussés vers un store.',
'status.tooltip.Ingested': 'Indexé dans au moins un store.',
'status.tooltip.Stale': 'Chunks modifiés depuis le dernier push — re-ingestion requise.',
'status.tooltip.Failed': 'Une étape du pipeline a échoué. Réessayez.',
// Document library (#211, #212, #213)
'docs.title': 'Documents',
'docs.import': 'Importer',
'docs.emptyTitle': 'Aucun document',
'docs.emptySubtitle': 'Importez votre premier document pour commencer.',
'docs.emptyAction': 'Importer un document',
'docs.emptyFiltered': 'Aucun document ne correspond aux filtres.',
'docs.colName': 'Nom',
'docs.colStatus': 'État',
'docs.colStores': 'Stores',
'docs.colUpdated': 'Mis à jour',
'docs.filterSearch': 'Rechercher…',
'docs.filterClear': 'Effacer les filtres',
'docs.selected': '{n} sélectionné(s)',
'docs.bulkRechunk': 'Re-chunker',
'docs.bulkPush': 'Pousser vers un store…',
'docs.bulkDelete': 'Supprimer',
'docs.bulkCancel': 'Annuler la sélection',
'docs.deleteConfirm': 'Supprimer {n} document(s) ? Cette action est irréversible.',
'docs.pushTitle': 'Pousser vers un store',
'docs.pushLabel': 'Store cible',
'docs.pushPlaceholder': 'Nom du store…',
'docs.pushSubmit': 'Pousser',
'docs.pushCancel': 'Annuler',
'docs.jobDispatched': 'Job lancé ({jobId})',
// Doc import (#214)
'docsNew.title': 'Importer des documents',
'docsNew.drop': 'Déposez des PDFs ici ou cliquez pour choisir',
'docsNew.dropHint': 'Plusieurs fichiers acceptés · PDF uniquement',
'docsNew.queued': 'En attente',
'docsNew.uploading': 'Import…',
'docsNew.done': 'Importé',
'docsNew.failed': 'Échec',
'docsNew.viewDoc': 'Voir le document',
'docsNew.backToLibrary': 'Retour à la bibliothèque',
'docsNew.viewLibrary': 'Voir la bibliothèque',
'docsNew.allDone': 'Tous les fichiers ont été importés.',
// Coming-soon placeholders (0.6.0 doc-centric routes — #207)
'comingSoon.title': 'Bientôt disponible',
'comingSoon.subtitle.docsLibrary':
@ -341,6 +394,59 @@ const messages: Messages = {
'flags.allModesDisabled':
'No doc workspace mode (Ask / Inspect / Chunks) is enabled for this deployment. Contact your administrator.',
// Lifecycle status badges (#215)
'status.Uploaded': 'Uploaded',
'status.Parsed': 'Parsed',
'status.Chunked': 'Chunked',
'status.Ingested': 'Ingested',
'status.Stale': 'Stale',
'status.Failed': 'Failed',
'status.tooltip.Uploaded': 'File received, awaiting parsing.',
'status.tooltip.Parsed': 'Document parsed successfully.',
'status.tooltip.Chunked': 'Chunks generated, ready to push to a store.',
'status.tooltip.Ingested': 'Indexed in at least one store.',
'status.tooltip.Stale': 'Chunks modified since last push — re-ingestion required.',
'status.tooltip.Failed': 'A pipeline step failed. Retry to recover.',
// Document library (#211, #212, #213)
'docs.title': 'Documents',
'docs.import': 'Import',
'docs.emptyTitle': 'No documents yet',
'docs.emptySubtitle': 'Import your first document to get started.',
'docs.emptyAction': 'Import a document',
'docs.emptyFiltered': 'No documents match the current filters.',
'docs.colName': 'Name',
'docs.colStatus': 'Status',
'docs.colStores': 'Stores',
'docs.colUpdated': 'Updated',
'docs.filterSearch': 'Search…',
'docs.filterClear': 'Clear filters',
'docs.selected': '{n} selected',
'docs.bulkRechunk': 'Re-chunk',
'docs.bulkPush': 'Push to store…',
'docs.bulkDelete': 'Delete',
'docs.bulkCancel': 'Cancel selection',
'docs.deleteConfirm': 'Delete {n} document(s)? This action cannot be undone.',
'docs.pushTitle': 'Push to store',
'docs.pushLabel': 'Target store',
'docs.pushPlaceholder': 'Store name…',
'docs.pushSubmit': 'Push',
'docs.pushCancel': 'Cancel',
'docs.jobDispatched': 'Job dispatched ({jobId})',
// Doc import (#214)
'docsNew.title': 'Import documents',
'docsNew.drop': 'Drop PDFs here or click to choose',
'docsNew.dropHint': 'Multiple files accepted · PDF only',
'docsNew.queued': 'Queued',
'docsNew.uploading': 'Uploading…',
'docsNew.done': 'Imported',
'docsNew.failed': 'Failed',
'docsNew.viewDoc': 'View document',
'docsNew.backToLibrary': 'Back to library',
'docsNew.viewLibrary': 'View library',
'docsNew.allDone': 'All files have been imported.',
// Coming-soon placeholders (0.6.0 doc-centric routes — #207)
'comingSoon.title': 'Coming soon',
'comingSoon.subtitle.docsLibrary':

View file

@ -28,6 +28,8 @@ export interface Document {
lifecycleState: DocumentLifecycleState
/** ISO timestamp of the last lifecycle transition (UTC). */
lifecycleStateAt: string | null
/** Stores this document has been pushed to (added in E1 #203). */
stores?: string[]
}
export interface PipelineOptions {