feat(share) : viewer Word (docx-preview) et tableurs (SheetJS) + sanitisation DOMPurify

This commit is contained in:
Matthieu
2026-06-12 15:04:44 +02:00
parent 4ffa19e53f
commit 0f1eeeba1c
5 changed files with 328 additions and 49 deletions
+165 -2
View File
@@ -83,6 +83,68 @@
</div>
</div>
<!-- DOCX preview rendu HTML via docx-preview (lazy) -->
<div
v-else-if="isDocx"
class="flex max-h-[85vh] w-[85vw] max-w-4xl flex-col overflow-hidden rounded-xl bg-white"
>
<div class="flex items-center justify-between gap-2 border-b border-neutral-200 px-4 py-3">
<p class="truncate text-sm font-medium text-neutral-700">{{ entry.name }}</p>
<a
:href="downloadUrl"
class="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
>
{{ $t('sharedFiles.download') }}
</a>
</div>
<div class="overflow-auto bg-neutral-100 p-4">
<div v-if="loadingOffice" class="flex justify-center py-10">
<Icon name="heroicons:arrow-path" class="h-6 w-6 animate-spin text-neutral-400" />
</div>
<p v-else-if="officeError" class="py-10 text-center text-sm text-red-600">
{{ $t('sharedFiles.previewError') }}
</p>
<div v-show="!loadingOffice && !officeError" ref="docxContainer" class="mx-auto bg-white" />
</div>
</div>
<!-- Spreadsheet preview rendu table via SheetJS (lazy) -->
<div
v-else-if="isSpreadsheet"
class="flex max-h-[85vh] w-[88vw] max-w-5xl flex-col overflow-hidden rounded-xl bg-white"
>
<div class="flex items-center justify-between gap-2 border-b border-neutral-200 px-4 py-3">
<p class="truncate text-sm font-medium text-neutral-700">{{ entry.name }}</p>
<a
:href="downloadUrl"
class="inline-flex items-center gap-1.5 rounded-lg bg-blue-600 px-3 py-1.5 text-sm font-semibold text-white transition-colors hover:bg-blue-700"
>
{{ $t('sharedFiles.download') }}
</a>
</div>
<div v-if="sheetNames.length > 1" class="flex gap-1 overflow-x-auto border-b border-neutral-100 px-3 py-2">
<button
v-for="(name, i) in sheetNames"
:key="name"
class="whitespace-nowrap rounded px-2 py-1 text-xs"
:class="i === activeSheet ? 'bg-blue-600 text-white' : 'bg-neutral-100 text-neutral-600 hover:bg-neutral-200'"
@click="selectSheet(i)"
>
{{ name }}
</button>
</div>
<div class="overflow-auto p-4">
<div v-if="loadingOffice" class="flex justify-center py-10">
<Icon name="heroicons:arrow-path" class="h-6 w-6 animate-spin text-neutral-400" />
</div>
<p v-else-if="officeError" class="py-10 text-center text-sm text-red-600">
{{ $t('sharedFiles.previewError') }}
</p>
<!-- eslint-disable-next-line vue/no-v-html -- HTML généré par SheetJS, valeurs de cellule échappées -->
<div v-else class="xlsx-host" v-html="sheetHtml" />
</div>
</div>
<!-- Generic file download fallback -->
<div v-else class="flex flex-col items-center gap-4 rounded-xl bg-white p-10">
<Icon name="heroicons:document" class="h-16 w-16 text-neutral-400" />
@@ -96,8 +158,8 @@
</a>
</div>
<!-- File name footer (hors bloc texte car il a déjà le nom dans l'en-tête) -->
<p v-if="!isText" class="mt-3 text-sm text-white/70">{{ entry.name }}</p>
<!-- File name footer (masqué pour les vues qui affichent déjà le nom dans leur en-tête) -->
<p v-if="!isText && !isDocx && !isSpreadsheet" class="mt-3 text-sm text-white/70">{{ entry.name }}</p>
</div>
</div>
</Transition>
@@ -125,9 +187,21 @@ const overlayRef = ref<HTMLElement | null>(null)
const textContent = ref('')
const loadingText = ref(false)
// Office previews (rendus côté client, libs chargées à la demande)
const docxContainer = ref<HTMLElement | null>(null)
const loadingOffice = ref(false)
const officeError = ref(false)
const sheetNames = ref<string[]>([])
const activeSheet = ref(0)
const sheetHtml = ref('')
// Workbook SheetJS courant (type laissé libre : la lib est importée dynamiquement)
let workbook: { SheetNames: string[]; Sheets: Record<string, unknown> } | null = null
const { getDownloadUrl } = useShareService()
const TEXT_RE = /\.(md|markdown|txt|csv|json|xml|log)$/i
const DOCX_RE = /\.docx$/i
const SHEET_RE = /\.(xlsx|xlsm|xls)$/i
const inlineUrl = computed(() => props.entry ? getDownloadUrl(props.entry.path, 'inline') : '')
const downloadUrl = computed(() => props.entry ? getDownloadUrl(props.entry.path, 'attachment') : '')
@@ -138,9 +212,69 @@ const isText = computed(() =>
? (props.entry.mimeType.startsWith('text/') || TEXT_RE.test(props.entry.name))
: false
)
const isDocx = computed(() => props.entry ? DOCX_RE.test(props.entry.name) : false)
const isSpreadsheet = computed(() => props.entry ? SHEET_RE.test(props.entry.name) : false)
async function fetchBlob(): Promise<Blob> {
return $fetch<Blob>(downloadUrl.value, {
credentials: 'include',
responseType: 'blob' as never,
})
}
async function renderDocx(blob: Blob) {
const [{ renderAsync }, DOMPurify] = await Promise.all([
import('docx-preview'),
import('dompurify'),
])
loadingOffice.value = false
await nextTick()
if (docxContainer.value) {
docxContainer.value.innerHTML = ''
await renderAsync(blob, docxContainer.value, undefined, { inWrapper: true, ignoreLastRenderedPageBreak: true })
// Anti-XSS : neutralise tout script injecté via un .docx piégé, en gardant la mise en forme (style)
docxContainer.value.innerHTML = DOMPurify.default.sanitize(docxContainer.value.innerHTML, {
ADD_TAGS: ['style'],
FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form'],
})
}
}
async function renderSpreadsheet(blob: Blob) {
const [XLSX, DOMPurify] = await Promise.all([import('xlsx'), import('dompurify')])
const buf = await blob.arrayBuffer()
workbook = XLSX.read(buf, { type: 'array' }) as typeof workbook
sheetNames.value = workbook?.SheetNames ?? []
await selectSheet(0, XLSX, DOMPurify)
loadingOffice.value = false
}
async function selectSheet(
index: number,
xlsx?: typeof import('xlsx'),
purify?: typeof import('dompurify'),
) {
if (!workbook) return
activeSheet.value = index
const XLSX = xlsx ?? (await import('xlsx'))
const DOMPurify = purify ?? (await import('dompurify'))
const ws = workbook.Sheets[workbook.SheetNames[index]!]
const rawHtml = XLSX.utils.sheet_to_html(ws as never, { editable: false })
sheetHtml.value = DOMPurify.default.sanitize(rawHtml, { FORBID_TAGS: ['script', 'iframe', 'object', 'embed', 'form'] })
}
function resetOffice() {
loadingOffice.value = false
officeError.value = false
sheetHtml.value = ''
sheetNames.value = []
activeSheet.value = 0
workbook = null
}
watch(() => props.entry, async (entry) => {
textContent.value = ''
resetOffice()
if (!entry) return
nextTick(() => overlayRef.value?.focus())
@@ -157,6 +291,22 @@ watch(() => props.entry, async (entry) => {
} finally {
loadingText.value = false
}
return
}
if (isDocx.value || isSpreadsheet.value) {
loadingOffice.value = true
try {
const blob = await fetchBlob()
if (isDocx.value) {
await renderDocx(blob)
} else {
await renderSpreadsheet(blob)
}
} catch {
officeError.value = true
loadingOffice.value = false
}
}
}, { immediate: true })
</script>
@@ -170,4 +320,17 @@ watch(() => props.entry, async (entry) => {
.fade-leave-to {
opacity: 0;
}
/* Rendu des tableurs (HTML généré par SheetJS) */
.xlsx-host :deep(table) {
border-collapse: collapse;
font-size: 12px;
}
.xlsx-host :deep(td),
.xlsx-host :deep(th) {
border: 1px solid #e5e5e5;
padding: 2px 6px;
white-space: nowrap;
text-align: left;
}
</style>