feat: add local DICOM and canvas PDF previews

This commit is contained in:
SantaSpeen committed 2026-10-22 01:25:48 +03:00
1 parent b569f68300
commit dd29258828
18 files changed
+960 -6

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# Предпросмотр PDF и DICOM
PDF отображается локальным PDF.js в canvas, без плагинов браузера и внешних CDN. Страницы рисуются по одной; доступны переключение страницы и масштаб. CSP `object-src 'none'` сохраняется. Шрифты и таблицы символов входят в сборку.
Файлы `.dcm` и `.dicom` открываются локальным DICOM-декодером в отдельном Worker. Поддерживаются 8/16-битные монохромные изображения (MONOCHROME1/2), 8-битный RGB и сжатые данные, поддерживаемые декодером Daikon. Доступны выбор кадра, ширина/уровень окна и сброс настроек. Неподдерживаемый формат сообщает об ошибке; файл остаётся доступен для скачивания.
Для ограничения памяти DICOM-предпросмотр принимает файлы до 64 МиБ, изображения до 16 миллионов пикселей на кадр и до 128 МиБ распакованных пикселей. Первичное декодирование ограничено 30 секундами. Просмотр доступен в файловом менеджере и по публичным ссылкам с теми же проверками доступа, что и скачивание.
+2
View File
@@ -23,6 +23,7 @@
"@vueuse/integrations": "^14.4.0",
"ace-builds": "^1.45.2",
"csv-parse": "^6.2.1",
"daikon": "^1.2.46",
"dayjs": "^1.11.23",
"dompurify": "^3.4.17",
"epubjs": "^0.3.93",
@@ -34,6 +35,7 @@
"marked-katex-extension": "^5.1.13",
"material-icons": "^1.13.14",
"normalize.css": "^8.0.1",
"pdfjs-dist": "^6.4.299",
"pinia": "^3.0.4",
"pretty-bytes": "^7.2.0",
"qrcode.vue": "^3.11.0",
+184
View File
@@ -30,6 +30,9 @@ importers:
csv-parse:
specifier: ^7.0.2
version: 7.0.3
daikon:
specifier: ^1.2.46
version: 1.2.46
dayjs:
specifier: ^1.11.23
version: 1.11.23
@@ -63,6 +66,9 @@ importers:
normalize.css:
specifier: ^8.0.1
version: 8.0.1
pdfjs-dist:
specifier: ^6.4.299
version: 6.4.299
pinia:
specifier: ^3.0.4
version: 3.0.4(typescript@5.9.3)(vue@3.5.44(typescript@5.9.3))
@@ -1006,6 +1012,81 @@ packages:
'@keyv/serialize@1.1.1':
resolution: {integrity: sha512-dXn3FZhPv0US+7dtJsIi2R+c7qWYiReoEh5zUntWCf4oSpMNib8FDhSoed6m3QyZdx5hK7iLFkYk3rNxwt8vTA==}
'@napi-rs/canvas-android-arm64@1.0.13':
resolution: {integrity: sha512-trn7AaDzQ+yeeA0ezhkC7cB1ZDPtp4UYk0EvB5F8qtYL9jEVWtVrU30WOpI52DszoTxaTsCgf5PP4ZVaOlOIHQ==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [android]
'@napi-rs/canvas-darwin-arm64@1.0.13':
resolution: {integrity: sha512-6Y2djEetL8copxfNK6hg7oig/xqTwOchv19hBOm+zBNdKc/02Z3kjZN5wrLzv/l5O04/bAQS6I/AlQpwBlXgPg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [darwin]
'@napi-rs/canvas-darwin-x64@1.0.13':
resolution: {integrity: sha512-OZoPwwu4TMMg8GTCFBrg8UFExwQTU/55i3uTC/izDat6PHE+ro9dimyQoOboFf91+NY7Pnn70ScR8f8I8+eZXw==}
engines: {node: '>= 10'}
cpu: [x64]
os: [darwin]
'@napi-rs/canvas-linux-arm-gnueabihf@1.0.13':
resolution: {integrity: sha512-dZSYaKROuswU2eUWG5aBKndNVe68elo1YX93xtRax7q658tj8rYE+HwduovWJgs6qwv1r1/CLR60nDeBbyjvyg==}
engines: {node: '>= 10'}
cpu: [arm]
os: [linux]
'@napi-rs/canvas-linux-arm64-gnu@1.0.13':
resolution: {integrity: sha512-W6FzYE8ADHI93In1vi80KBL6btDtAMuj50Ch5ptkWS8xuntyzbR4h5JDUmXoakxZn2yMInksudTEqVSWoFqFGg==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [glibc]
'@napi-rs/canvas-linux-arm64-musl@1.0.13':
resolution: {integrity: sha512-+6fQ+rR49hkAa4voh2stLIwQ+4t+gmoseM8Bc53/DlMXb73IKymDPWK9A/NtWeqTW4ijWppYuyuxS2hPI8tzNA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [linux]
libc: [musl]
'@napi-rs/canvas-linux-riscv64-gnu@1.0.13':
resolution: {integrity: sha512-17XEMO3t9RW/TtHtSFf2AkaSWuCWdzbPeidz7zrOFawHxoLSJCnpTI1hN5aUvrZNnkNNmt/vZVJCh0ryUaik3A==}
engines: {node: '>= 10'}
cpu: [riscv64]
os: [linux]
libc: [glibc]
'@napi-rs/canvas-linux-x64-gnu@1.0.13':
resolution: {integrity: sha512-lc48IwknVHBsNzXn9Xs5OkUsRX38Ml3Z1aOybQ51mMEzZckm8+4A0qROlyYHEoBPzr1kL3IU8ZUAqDb7wtdX8w==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [glibc]
'@napi-rs/canvas-linux-x64-musl@1.0.13':
resolution: {integrity: sha512-bGY1r26S2bs8UNFJcPWcCSNdCFbKep5PATsvtgtC9A5u6SRgr2/jJE/RlhHL5m9ZpixNDhVkLY/5h16Kx5V9YA==}
engines: {node: '>= 10'}
cpu: [x64]
os: [linux]
libc: [musl]
'@napi-rs/canvas-win32-arm64-msvc@1.0.13':
resolution: {integrity: sha512-2vRPBZoaIvJrUkDhZTE2Hn0YrnpJRCWVM3EJACoBKjuWI6WgPxGtUoRMsxRviCsyks8bKTSFdyw14CellnG2qA==}
engines: {node: '>= 10'}
cpu: [arm64]
os: [win32]
'@napi-rs/canvas-win32-x64-msvc@1.0.13':
resolution: {integrity: sha512-DUlW3lZPz63kYsf8mxgyyZuevhlH0T3/BGP9l+NazhB0F1+gL6D4hqZdnhZpw24DlWmTpATDcyYSZlJOi+DdfQ==}
engines: {node: '>= 10'}
cpu: [x64]
os: [win32]
'@napi-rs/canvas@1.0.13':
resolution: {integrity: sha512-b87ugZpQ5ViwqVBkjervxpwa0GmJPsKHLBNoZN6GpjWeHzTbDUGryriq+2DYW2XbB+xCqSIINQysC0/I87nPbw==}
engines: {node: '>= 10'}
'@oxc-project/types@0.155.0':
resolution: {integrity: sha512-SeE8JPwW1xs1tHeNycjUtUBdhorRa8o4jlvjwk49R7/Z291i+4DQa7JJIgOm/TaYQZx+QrPQbVJ/9c8dMIZN8Q==}
@@ -1417,6 +1498,10 @@ packages:
peerDependencies:
vue: ^3.5.0
'@wearemothership/dicom-character-set@1.0.4-opt.1':
resolution: {integrity: sha512-stqhnpawYHY2UZKj4RHTF71ab3q3z8S1SO9ToQKjsHQwowUdFVo6YFea93psFux3yqNbRlQjwoCdPjHcD0YQzw==}
engines: {node: '>=10'}
'@xmldom/xmldom@0.8.15':
resolution: {integrity: sha512-/5NV/vDALVFDXgLmfsy9TRCBlKwO2LNBFzpzvb9iIj+jR+eSc6DLYYvVOdivT/jm7MtU6TebYuRmzEOI7w40UA==}
engines: {node: '>=10.0.0'}
@@ -1571,6 +1656,9 @@ packages:
engines: {node: '>=4'}
hasBin: true
cssfilter@0.0.10:
resolution: {integrity: sha512-FAaLDaplstoRsDR8XGYH51znUN0UY7nMc6Z9/fvE8EXGwvJE9hu7W2vHwx1+bd6gCYnln9nLbzxFTrcO9YQDZw==}
csstype@3.2.3:
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
@@ -1584,6 +1672,9 @@ packages:
resolution: {integrity: sha512-MOqHvMWF9/9MX6nza0KgvFH4HpMU0EF5uUDXqX/BtxtU8NfB0QzRtJ8Oe/6SuS4kbhyzVJwjd97EA4PKrzJ8bw==}
engines: {node: '>=0.12'}
daikon@1.2.46:
resolution: {integrity: sha512-S8dTTlsWYTH3LQztjTW9KnNvxDeL2mr2cau0auLdYMJe4TrocYP1PmidHizO3rXUs+gXpBWI1PQ2qvB4b21QFw==}
dayjs@1.11.23:
resolution: {integrity: sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ==}
@@ -1774,6 +1865,9 @@ packages:
picomatch:
optional: true
fflate@0.8.3:
resolution: {integrity: sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==}
file-entry-cache@11.1.5:
resolution: {integrity: sha512-+PFTHITI08JIGhnNpGNI8T8inUpgZfk3GNEqfT9R2zZV2iFXg3CvqzSl/uEhs7TSGujYRELEANyDvS8Fj7+S7Q==}
@@ -1879,6 +1973,9 @@ packages:
isexe@2.0.0:
resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==}
jpeg-lossless-decoder-js@2.0.7:
resolution: {integrity: sha512-tbZlhFkKmx+JaqVMkq47SKWGuXLkIaV8fTbnhO39dYEnQrSShLGuLCGb0n6ntXjtmk6oAWGiIriWOLwj9od0yQ==}
js-base64@3.9.4:
resolution: {integrity: sha512-PtOMXpEGuP0RRiRXsjzHzl44dMHxSu2CPvAhinupR1tBa88me+1DPqsobl7eupn5UukjLkln1ZnAOAOXOrYG0Q==}
@@ -2155,6 +2252,9 @@ packages:
pako@1.0.11:
resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==}
pako@2.2.0:
resolution: {integrity: sha512-zJq6RP/5q+TO2OpFV3FHzlPnFjmkb7Nc99a5SNjJE+uu/PkpChs+NIZSSzbBoD+6kjiISXjfYdwj1ZRQ81dz/w==}
path-browserify@1.0.1:
resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==}
@@ -2175,6 +2275,10 @@ packages:
pathe@2.0.3:
resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==}
pdfjs-dist@6.4.299:
resolution: {integrity: sha512-AVl138zALtfaAPvADulE0PZThbYzCBS79nL4pOSL/6Sm/4AH5A21BD9VHt97OlCuzJuCpmeZtAtkinisF4Vb1g==}
engines: {node: '>=22.13.0 || >=24'}
perfect-debounce@1.0.0:
resolution: {integrity: sha512-xCy9V055GLEqoFaHoC1SoLIaLmWctgCUaBaWxDZ7/Zx4CTyX7cJQLJOok/orfjZAh9kEYpjJa4d0KcJmCbctZA==}
@@ -2713,6 +2817,11 @@ packages:
resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==}
engines: {node: '>=18'}
xss@1.0.14:
resolution: {integrity: sha512-og7TEJhXvn1a7kzZGQ7ETjdQVS2UfZyTlsEdDOqvQF7GoxNfY+0YLCzBy1kPdsDDx4QuNAonQPddpsn6Xl/7sw==}
engines: {node: '>= 0.10.0'}
hasBin: true
yallist@3.1.1:
resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}
@@ -3643,6 +3752,54 @@ snapshots:
'@keyv/serialize@1.1.1': {}
'@napi-rs/canvas-android-arm64@1.0.13':
optional: true
'@napi-rs/canvas-darwin-arm64@1.0.13':
optional: true
'@napi-rs/canvas-darwin-x64@1.0.13':
optional: true
'@napi-rs/canvas-linux-arm-gnueabihf@1.0.13':
optional: true
'@napi-rs/canvas-linux-arm64-gnu@1.0.13':
optional: true
'@napi-rs/canvas-linux-arm64-musl@1.0.13':
optional: true
'@napi-rs/canvas-linux-riscv64-gnu@1.0.13':
optional: true
'@napi-rs/canvas-linux-x64-gnu@1.0.13':
optional: true
'@napi-rs/canvas-linux-x64-musl@1.0.13':
optional: true
'@napi-rs/canvas-win32-arm64-msvc@1.0.13':
optional: true
'@napi-rs/canvas-win32-x64-msvc@1.0.13':
optional: true
'@napi-rs/canvas@1.0.13':
optionalDependencies:
'@napi-rs/canvas-android-arm64': 1.0.13
'@napi-rs/canvas-darwin-arm64': 1.0.13
'@napi-rs/canvas-darwin-x64': 1.0.13
'@napi-rs/canvas-linux-arm-gnueabihf': 1.0.13
'@napi-rs/canvas-linux-arm64-gnu': 1.0.13
'@napi-rs/canvas-linux-arm64-musl': 1.0.13
'@napi-rs/canvas-linux-riscv64-gnu': 1.0.13
'@napi-rs/canvas-linux-x64-gnu': 1.0.13
'@napi-rs/canvas-linux-x64-musl': 1.0.13
'@napi-rs/canvas-win32-arm64-msvc': 1.0.13
'@napi-rs/canvas-win32-x64-msvc': 1.0.13
optional: true
'@oxc-project/types@0.155.0': {}
'@pkgr/core@0.3.6': {}
@@ -4070,6 +4227,8 @@ snapshots:
dependencies:
vue: 3.5.44(typescript@5.9.3)
'@wearemothership/dicom-character-set@1.0.4-opt.1': {}
'@xmldom/xmldom@0.8.15': {}
ace-builds@1.45.2: {}
@@ -4224,6 +4383,8 @@ snapshots:
cssesc@3.0.0: {}
cssfilter@0.0.10: {}
csstype@3.2.3: {}
csv-parse@7.0.3: {}
@@ -4235,6 +4396,14 @@ snapshots:
es5-ext: 0.10.64
type: 2.7.3
daikon@1.2.46:
dependencies:
'@wearemothership/dicom-character-set': 1.0.4-opt.1
fflate: 0.8.3
jpeg-lossless-decoder-js: 2.0.7
pako: 2.2.0
xss: 1.0.14
dayjs@1.11.23: {}
debug@4.4.3:
@@ -4456,6 +4625,8 @@ snapshots:
optionalDependencies:
picomatch: 4.0.7
fflate@0.8.3: {}
file-entry-cache@11.1.5:
dependencies:
flat-cache: 6.1.23
@@ -4542,6 +4713,8 @@ snapshots:
isexe@2.0.0: {}
jpeg-lossless-decoder-js@2.0.7: {}
js-base64@3.9.4: {}
js-tokens@4.0.0: {}
@@ -4792,6 +4965,8 @@ snapshots:
pako@1.0.11: {}
pako@2.2.0: {}
path-browserify@1.0.1: {}
path-exists@4.0.0: {}
@@ -4804,6 +4979,10 @@ snapshots:
pathe@2.0.3: {}
pdfjs-dist@6.4.299:
optionalDependencies:
'@napi-rs/canvas': 1.0.13
perfect-debounce@1.0.0: {}
perfect-debounce@2.1.0: {}
@@ -5293,6 +5472,11 @@ snapshots:
xml-name-validator@5.0.0: {}
xss@1.0.14:
dependencies:
commander: 2.20.3
cssfilter: 0.0.10
yallist@3.1.1: {}
yaml-eslint-parser@1.3.2:
@@ -0,0 +1,180 @@
<template>
<div class="document-viewer" @wheel.stop @touchmove.stop @keydown.stop>
<div class="document-tools">
<strong>DICOM</strong>
<template v-if="ready">
<label
>{{ t("documents.frame") }}
<input
v-model.number="frame"
type="number"
min="1"
:max="frames" /></label
><span>/ {{ frames }}</span>
<template v-if="!color"
><label
>{{ t("documents.window") }}
<input v-model.number="width" type="number" min="1" /></label
><label
>{{ t("documents.level") }}
<input v-model.number="center" type="number" /></label
></template>
<button class="button button--flat" @click="reset">
{{ t("documents.reset") }}
</button>
</template>
</div>
<p v-if="error" role="alert" class="document-error">{{ error }}</p>
<p v-else-if="!ready">{{ t("files.loading") }}</p>
<div class="document-stage">
<canvas
v-show="ready && !error"
ref="canvas"
:aria-label="t('documents.dicomImage')"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { nextTick, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import DicomWorker from "@/utils/dicom.worker?worker";
const props = defineProps<{ source: string }>();
const { t } = useI18n();
const canvas = ref<HTMLCanvasElement>();
const ready = ref(false),
error = ref(""),
frame = ref(1),
frames = ref(1),
color = ref(false);
const center = ref(0),
width = ref(1);
let worker: Worker | undefined, controller: AbortController | undefined;
let timer: ReturnType<typeof setTimeout> | undefined,
timeout: ReturnType<typeof setTimeout> | undefined;
let sequence = 0,
defaults = { center: 0, width: 1 };
function stop() {
controller?.abort();
worker?.terminate();
worker = undefined;
clearTimeout(timer);
clearTimeout(timeout);
}
function reset() {
center.value = defaults.center;
width.value = defaults.width;
frame.value = 1;
}
function render() {
if (
!worker ||
!ready.value ||
!Number.isInteger(frame.value) ||
frame.value < 1 ||
frame.value > frames.value ||
!Number.isFinite(center.value) ||
!Number.isFinite(width.value) ||
width.value < 1
)
return;
worker.postMessage({
id: ++sequence,
frame: frame.value - 1,
center: center.value,
width: width.value,
});
}
watch([frame, center, width], () => {
clearTimeout(timer);
timer = setTimeout(render, 100);
});
watch(
() => props.source,
async (source) => {
stop();
const id = ++sequence;
ready.value = false;
error.value = "";
frame.value = 1;
controller = new AbortController();
const signal = controller.signal;
try {
const response = await fetch(source, {
credentials: "same-origin",
signal,
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const limit = 64 * 1024 * 1024;
if (Number(response.headers.get("Content-Length")) > limit)
throw new Error(t("documents.tooLarge"));
const reader = response.body?.getReader();
if (!reader) throw new Error(t("documents.loadFailed"));
const chunks: Uint8Array[] = [];
let length = 0;
while (true) {
const chunk = await reader.read();
if (chunk.done) break;
length += chunk.value.length;
if (length > limit) {
await reader.cancel();
throw new Error(t("documents.tooLarge"));
}
chunks.push(chunk.value);
}
if (signal.aborted || id !== sequence) return;
const data = new Uint8Array(length);
let offset = 0;
for (const chunk of chunks) {
data.set(chunk, offset);
offset += chunk.length;
}
worker = new DicomWorker();
timeout = setTimeout(() => {
error.value = t("documents.loadFailed");
worker?.terminate();
}, 30000);
worker.onerror = () => {
clearTimeout(timeout);
error.value = t("documents.loadFailed");
worker?.terminate();
};
worker.onmessage = async ({ data: result }) => {
if (result.id !== sequence) return;
clearTimeout(timeout);
if (result.error) {
error.value = `${t("documents.loadFailed")}: ${result.error}`;
return;
}
if (!ready.value) {
defaults = { center: result.center, width: result.width };
center.value = result.center;
width.value = result.width;
frames.value = result.frames;
color.value = result.color;
ready.value = true;
}
await nextTick();
const target = canvas.value;
if (!target || result.id !== sequence) return;
target.width = result.cols;
target.height = result.rows;
target
.getContext("2d")
?.putImageData(
new ImageData(result.rgba, result.cols, result.rows),
0,
0
);
};
worker.postMessage({ id, buffer: data.buffer }, [data.buffer]);
} catch (e) {
if (!signal.aborted && id === sequence)
error.value =
e instanceof Error ? e.message : t("documents.loadFailed");
}
},
{ immediate: true }
);
onBeforeUnmount(stop);
</script>
+174
View File
@@ -0,0 +1,174 @@
<template>
<div class="document-viewer" @wheel.stop @touchmove.stop @keydown.stop>
<div class="document-tools">
<strong>PDF</strong>
<button
class="button button--flat"
:disabled="page <= 1 || busy"
@click="page--"
>
{{ t("buttons.previous") }}
</button>
<label
>{{ t("documents.page") }}
<input
v-model.number="page"
type="number"
min="1"
:max="pages" /></label
><span>/ {{ pages }}</span>
<button
class="button button--flat"
:disabled="page >= pages || busy"
@click="page++"
>
{{ t("buttons.next") }}
</button>
<select
v-model.number="zoom"
class="input"
:aria-label="t('documents.zoom')"
>
<option :value="0.75">75%</option>
<option :value="1">100%</option>
<option :value="1.5">150%</option>
<option :value="2">200%</option>
</select>
</div>
<p v-if="error" role="alert" class="document-error">{{ error }}</p>
<p v-else-if="busy">{{ t("files.loading") }}</p>
<div ref="stage" class="document-stage">
<canvas
v-show="!busy && !error"
ref="canvas"
:aria-label="t('documents.pdfPage')"
/>
</div>
</div>
</template>
<script setup lang="ts">
import { nextTick, onBeforeUnmount, ref, watch } from "vue";
import { useI18n } from "vue-i18n";
import {
getDocument,
GlobalWorkerOptions,
version,
type PDFDocumentProxy,
type PDFDocumentLoadingTask,
type RenderTask,
} from "pdfjs-dist/legacy/build/pdf.mjs";
import pdfWorker from "pdfjs-dist/legacy/build/pdf.worker.min.mjs?url";
import { baseURL } from "@/utils/constants";
GlobalWorkerOptions.workerSrc = pdfWorker;
const props = defineProps<{ source: string }>();
const { t } = useI18n();
const canvas = ref<HTMLCanvasElement>(),
stage = ref<HTMLElement>();
const page = ref(1),
pages = ref(0),
zoom = ref(1),
busy = ref(true),
error = ref("");
let pdf: PDFDocumentProxy | undefined,
loading: PDFDocumentLoadingTask | undefined,
rendering: RenderTask | undefined;
let generation = 0,
renderID = 0;
async function render() {
if (
!pdf ||
!Number.isInteger(page.value) ||
page.value < 1 ||
page.value > pages.value
)
return;
const id = ++renderID;
rendering?.cancel();
busy.value = true;
try {
const docPage = await pdf.getPage(page.value);
if (id !== renderID) return;
await nextTick();
const target = canvas.value;
if (!target) return;
const base = docPage.getViewport({ scale: 1 });
const desired =
(Math.min(1000, (stage.value?.clientWidth || 1000) - 32) / base.width) *
zoom.value;
const scale = Math.min(
Math.max(0.1, desired),
Math.sqrt(4_000_000 / (base.width * base.height))
);
const viewport = docPage.getViewport({ scale });
// Draw on a fresh canvas so cancelling a prior page cannot race its context.
const buffer = document.createElement("canvas");
buffer.width = Math.ceil(viewport.width);
buffer.height = Math.ceil(viewport.height);
rendering = docPage.render({ canvas: buffer, viewport });
await rendering.promise;
if (id !== renderID) return;
target.width = buffer.width;
target.height = buffer.height;
target.getContext("2d")?.drawImage(buffer, 0, 0);
docPage.cleanup();
} catch (e) {
if (
id === renderID &&
!(e instanceof Error && e.name === "RenderingCancelledException")
)
error.value = t("documents.loadFailed");
} finally {
if (id === renderID) busy.value = false;
}
}
watch([page, zoom], render);
watch(
() => props.source,
async (source) => {
const id = ++generation;
++renderID;
rendering?.cancel();
void loading?.destroy();
pdf = undefined;
error.value = "";
busy.value = true;
page.value = 1;
pages.value = 0;
try {
const task = getDocument({
url: source,
cMapUrl: `${baseURL}/static/pdfjs/${version}/cmaps/`,
cMapPacked: true,
standardFontDataUrl: `${baseURL}/static/pdfjs/${version}/standard_fonts/`,
withCredentials: true,
useWasm: false,
disableFontFace: true,
useSystemFonts: true,
isOffscreenCanvasSupported: false,
isImageDecoderSupported: false,
});
loading = task;
const document = await task.promise;
if (id !== generation) {
await task.destroy();
return;
}
pdf = document;
pages.value = document.numPages;
await render();
} catch {
if (id === generation) {
error.value = t("documents.loadFailed");
busy.value = false;
}
}
},
{ immediate: true }
);
onBeforeUnmount(() => {
++generation;
++renderID;
rendering?.cancel();
void loading?.destroy();
});
</script>
+57
View File
@@ -1,4 +1,61 @@
/* Lightweight workspace: system fonts, solid surfaces, no blur or filter layers. */
.document-viewer {
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
min-height: 320px;
color: var(--textSecondary);
background: var(--background);
overflow: hidden;
}
.document-tools {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
gap: 10px;
padding: 12px;
background: var(--surfacePrimary);
border-bottom: 1px solid var(--borderPrimary);
}
.document-tools label {
display: flex;
align-items: center;
gap: 6px;
font-size: 12px;
}
.document-tools input {
width: 82px;
padding: 6px;
background: var(--background);
color: var(--textSecondary);
border: 1px solid var(--borderPrimary);
border-radius: 6px;
}
.document-tools select {
width: auto;
margin: 0;
}
.document-stage {
flex: 1;
min-height: 0;
overflow: auto;
padding: 16px;
text-align: center;
}
.document-stage canvas {
max-width: 100%;
height: auto;
}
.document-error {
padding: 16px;
overflow-wrap: anywhere;
}
.public-document {
height: 75vh;
min-height: 420px;
}
#share.card.share-listing {
width: min(800px, calc(100vw - 32px));
}
+12
View File
@@ -342,5 +342,17 @@
"modify": "Edit files",
"rename": "Rename or move files and directories",
"share": "Share files (requires download permission)"
},
"documents": {
"frame": "Frame",
"window": "Window width",
"level": "Window center",
"reset": "Reset",
"page": "Page",
"zoom": "Zoom",
"dicomImage": "DICOM image",
"pdfPage": "PDF page",
"tooLarge": "File too large for preview (64 MiB maximum).",
"loadFailed": "Unable to display this file"
}
}
+12
View File
@@ -339,5 +339,17 @@
"modify": "Редактировать файлы",
"rename": "Переименовывать или перемещать файлы и каталоги",
"share": "Делиться файлами (требует разрешения на скачивание)"
},
"documents": {
"frame": "Кадр",
"window": "Ширина окна",
"level": "Уровень",
"reset": "Сбросить",
"page": "Страница",
"zoom": "Масштаб",
"dicomImage": "Изображение DICOM",
"pdfPage": "Страница PDF",
"tooLarge": "Файл слишком большой для предпросмотра (максимум 64 МиБ).",
"loadFailed": "Не удалось отобразить файл"
}
}
+25
View File
@@ -0,0 +1,25 @@
declare module "daikon" {
export interface Image {
littleEndian: boolean;
hasPixelData(): boolean;
isCompressed(): boolean;
getCols(): number;
getRows(): number;
getNumberOfFrames(): number;
getNumberOfSamplesPerPixel(): number;
getBitsAllocated(): number;
getBitsStored(): number;
getPixelRepresentation(): number;
getPhotometricInterpretation(): string;
getPlanarConfig(): number;
getWindowWidth(): number;
getWindowCenter(): number;
getDataScaleSlope(): number;
getDataScaleIntercept(): number;
getRawData(): ArrayBuffer;
}
export const Series: {
parseImage(data: DataView): Image | null;
parserError: unknown;
};
}
@@ -0,0 +1,77 @@
import { describe, expect, it, vi } from "vitest";
import { storedValue, windowPixel } from "../dicom-pixels";
function fixture() {
const data: number[] = [...new Uint8Array(128), 68, 73, 67, 77];
const add = (group: number, element: number, vr: string, bytes: number[]) => {
if (bytes.length % 2) bytes.push(vr === "UI" ? 0 : 32);
data.push(
group & 255,
group >> 8,
element & 255,
element >> 8,
vr.charCodeAt(0),
vr.charCodeAt(1)
);
if (["OB", "OW"].includes(vr))
data.push(0, 0, bytes.length & 255, bytes.length >> 8, 0, 0);
else data.push(bytes.length & 255, bytes.length >> 8);
data.push(...bytes);
};
const text = (s: string) => Array.from(new TextEncoder().encode(s));
add(2, 0x10, "UI", text("1.2.840.10008.1.2.1"));
add(0x28, 2, "US", [1, 0]);
add(0x28, 4, "CS", text("MONOCHROME2"));
add(0x28, 8, "IS", text("2"));
add(0x28, 0x10, "US", [2, 0]);
add(0x28, 0x11, "US", [2, 0]);
add(0x28, 0x100, "US", [16, 0]);
add(0x28, 0x101, "US", [12, 0]);
add(0x28, 0x102, "US", [11, 0]);
add(0x28, 0x103, "US", [1, 0]);
add(0x28, 0x1050, "DS", text("0"));
add(0x28, 0x1051, "DS", text("4096"));
add(
0x7fe0,
0x10,
"OW",
[0, 8, 255, 15, 0, 0, 255, 7, 255, 7, 0, 0, 255, 15, 0, 8]
);
return new Uint8Array(data).buffer;
}
describe("DICOM rendering", () => {
it("preserves signed 12-bit CT values", () => {
expect(storedValue(0x800, 12, true)).toBe(-2048);
expect(storedValue(0xfff, 12, true)).toBe(-1);
expect(storedValue(0xfff, 12, false)).toBe(4095);
});
it("applies DICOM window and MONOCHROME1 inversion", () => {
expect(windowPixel(-2048, 0, 4096, false)).toBe(0);
expect(windowPixel(2047, 0, 4096, false)).toBe(255);
expect(windowPixel(-2048, 0, 4096, true)).toBe(255);
expect(windowPixel(0, 0, 1, false)).toBe(255);
});
it("decodes a real two-frame DICOM and switches frames", async () => {
const postMessage = vi.fn();
const scope = {
postMessage,
onmessage: null as unknown as (e: { data: object }) => void,
};
vi.stubGlobal("self", scope);
try {
await import("../dicom.worker");
scope.onmessage({ data: { id: 1, buffer: fixture() } });
const first = postMessage.mock.calls[0][0];
expect(first.error).toBeUndefined();
expect(first.frames).toBe(2);
expect(first.cols).toBe(2);
expect(first.rgba[0]).toBe(0);
expect(first.rgba[12]).toBe(255);
scope.onmessage({ data: { id: 2, frame: 1 } });
expect(postMessage.mock.calls[1][0].rgba[0]).toBe(255);
} finally {
vi.unstubAllGlobals();
}
});
});
+27
View File
@@ -0,0 +1,27 @@
export function storedValue(
raw: number,
bits: number,
signed: boolean
): number {
const range = 2 ** bits;
const value = raw % range;
return signed && value >= range / 2 ? value - range : value;
}
export function windowPixel(
value: number,
center: number,
width: number,
invert: boolean
): number {
const normalized =
width <= 1
? value > center - 0.5
? 255
: 0
: Math.max(
0,
Math.min(255, ((value - (center - 0.5)) / (width - 1) + 0.5) * 255)
);
return Math.round(invert ? 255 - normalized : normalized);
}
+125
View File
@@ -0,0 +1,125 @@
import { Series, type Image } from "daikon";
import { storedValue, windowPixel } from "./dicom-pixels";
let image: Image;
let raw: DataView;
let rows = 0,
cols = 0,
frames = 1,
samples = 1,
bits = 16,
stored = 16;
let compressed = false;
let defaultCenter = 0,
defaultWidth = 1;
let slope = 1,
intercept = 0;
const pixel = (index: number) =>
storedValue(
bits === 8
? raw.getUint8(index)
: raw.getUint16(index * 2, image.littleEndian),
stored,
image.getPixelRepresentation() === 1
) *
slope +
intercept;
self.onmessage = (event: MessageEvent) => {
const { id, buffer, frame = 0, center, width } = event.data;
try {
if (buffer) {
const parsed = Series.parseImage(new DataView(buffer));
if (!parsed?.hasPixelData())
throw new Error("DICOM has no supported image data");
image = parsed;
cols = image.getCols();
rows = image.getRows();
frames = image.getNumberOfFrames() || 1;
samples = image.getNumberOfSamplesPerPixel() || 1;
bits = image.getBitsAllocated();
stored = image.getBitsStored() || bits;
compressed = image.isCompressed();
const photo = image.getPhotometricInterpretation().trim();
if (
![8, 16].includes(bits) ||
stored < 1 ||
stored > bits ||
![1, 3].includes(samples) ||
![cols, rows, frames].every((v) => Number.isSafeInteger(v) && v > 0) ||
cols * rows > 16_000_000 ||
(cols * rows * frames * samples * bits) / 8 > 128 * 1024 * 1024 ||
!(
photo === "MONOCHROME1" ||
photo === "MONOCHROME2" ||
(samples === 3 && (photo === "RGB" || compressed))
)
) {
throw new Error("Unsupported DICOM pixel format or image too large");
}
raw = new DataView(image.getRawData());
if (raw.byteLength < (cols * rows * frames * samples * bits) / 8)
throw new Error("Truncated DICOM pixel data");
slope = image.getDataScaleSlope() ?? 1;
intercept = image.getDataScaleIntercept() ?? 0;
let min = samples === 1 ? Infinity : 0,
max = samples === 1 ? -Infinity : 255;
if (samples === 1)
for (let i = 0; i < cols * rows; i++) {
const v = pixel(i);
min = Math.min(min, v);
max = Math.max(max, v);
}
defaultWidth =
image.getWindowWidth() > 0
? image.getWindowWidth()
: Math.max(1, max - min + 1);
defaultCenter =
image.getWindowWidth() > 0 ? image.getWindowCenter() : (min + max) / 2;
}
if (!raw || !Number.isInteger(frame) || frame < 0 || frame >= frames)
throw new Error("Invalid DICOM frame");
const rgba = new Uint8ClampedArray(cols * rows * 4);
const invert =
image.getPhotometricInterpretation().trim() === "MONOCHROME1";
const count = cols * rows,
base = frame * count * samples;
for (let i = 0; i < count; i++) {
if (samples === 1) {
const v = windowPixel(
pixel(base + i),
center ?? defaultCenter,
width ?? defaultWidth,
invert
);
rgba[i * 4] = rgba[i * 4 + 1] = rgba[i * 4 + 2] = v;
} else {
if (bits !== 8) throw new Error("Unsupported DICOM color depth");
const planar = !compressed && image.getPlanarConfig() === 1;
for (let c = 0; c < 3; c++)
rgba[i * 4 + c] = raw.getUint8(
base + (planar ? c * count + i : i * 3 + c)
);
}
rgba[i * 4 + 3] = 255;
}
self.postMessage(
{
id,
rgba,
cols,
rows,
frames,
center: defaultCenter,
width: defaultWidth,
color: samples === 3,
},
{ transfer: [rgba.buffer] }
);
} catch (error) {
self.postMessage({
id,
error: error instanceof Error ? error.message : "Cannot decode DICOM",
});
}
};
+4
View File
@@ -84,6 +84,10 @@ const currentView = computed(() => {
if (fileStore.req.isDir) {
return FileListing;
} else if (
[".dcm", ".dicom", ".pdf"].includes(fileStore.req.extension.toLowerCase())
) {
return Preview;
} else if (fileStore.req.extension.toLowerCase() === ".csv") {
// CSV files use Preview for table view, unless ?edit=true
if (route.query.edit === "true") {
+28 -1
View File
@@ -128,6 +128,19 @@
</a>
</div>
</div>
<div
v-if="
!req.isDir &&
['.pdf', '.dcm', '.dicom'].includes(req.extension.toLowerCase())
"
class="share__box share__box__items public-document"
>
<PdfViewer
v-if="req.extension.toLowerCase() === '.pdf'"
:source="inlineLink"
/>
<DicomViewer v-else :source="inlineLink" />
</div>
<div
id="shareList"
v-if="req.isDir && req.items.length > 0"
@@ -206,13 +219,27 @@ import Errors from "@/views/Errors.vue";
import Item from "@/components/files/ListingItem.vue";
import { useFileStore } from "@/stores/file";
import { useLayoutStore } from "@/stores/layout";
import { computed, inject, onMounted, onBeforeUnmount, ref, watch } from "vue";
import {
computed,
defineAsyncComponent,
inject,
onMounted,
onBeforeUnmount,
ref,
watch,
} from "vue";
import { useRoute } from "vue-router";
import { useI18n } from "vue-i18n";
import { StatusError } from "@/api/utils";
import { copy } from "@/utils/clipboard";
const error = ref<StatusError | null>(null);
const PdfViewer = defineAsyncComponent(
() => import("@/components/files/PdfViewer.vue")
);
const DicomViewer = defineAsyncComponent(
() => import("@/components/files/DicomViewer.vue")
);
const showLimit = ref<number>(100);
const password = ref<string>("");
const attemptedPasswordLogin = ref<boolean>(false);
+21 -3
View File
@@ -6,7 +6,7 @@
@mousemove="toggleNavigation"
@touchstart="toggleNavigation"
>
<header-bar v-if="isPdf || isEpub || isCsv || showNav">
<header-bar v-if="isPdf || isDicom || isEpub || isCsv || showNav">
<action icon="close" :label="$t('buttons.close')" @action="close()" />
<title>{{ name }}</title>
<action
@@ -124,7 +124,8 @@
:options="videoOptions"
>
</VideoPlayer>
<object v-else-if="isPdf" class="pdf" :data="previewUrl"></object>
<PdfViewer v-else-if="isPdf" :source="previewUrl" />
<DicomViewer v-else-if="isDicom" :source="previewUrl" />
<div v-else-if="fileStore.req?.type == 'blob'" class="info">
<div class="title">
<i class="material-icons">feedback</i>
@@ -195,7 +196,15 @@ import ExtendedImage from "@/components/files/ExtendedImage.vue";
import VideoPlayer from "@/components/files/VideoPlayer.vue";
import CsvViewer from "@/components/files/CsvViewer.vue";
import { VueReader } from "vue-reader";
import { computed, inject, onBeforeUnmount, onMounted, ref, watch } from "vue";
import {
computed,
defineAsyncComponent,
inject,
onBeforeUnmount,
onMounted,
ref,
watch,
} from "vue";
import { useRoute, useRouter } from "vue-router";
import type { Rendition } from "epubjs";
import { getTheme } from "@/utils/theme";
@@ -204,6 +213,12 @@ import { useI18n } from "vue-i18n";
// CSV file size limit for preview (5MB)
// Prevents browser memory issues with large files
const CSV_MAX_SIZE = 5 * 1024 * 1024;
const PdfViewer = defineAsyncComponent(
() => import("@/components/files/PdfViewer.vue")
);
const DicomViewer = defineAsyncComponent(
() => import("@/components/files/DicomViewer.vue")
);
const location = useStorage<string | number>("book-progress", 0, undefined, {
serializer: {
@@ -307,6 +322,9 @@ const previewUrl = computed(() => {
});
const isPdf = computed(() => fileStore.req?.extension.toLowerCase() == ".pdf");
const isDicom = computed(() =>
[".dcm", ".dicom"].includes(fileStore.req?.extension.toLowerCase() || "")
);
const isEpub = computed(
() => fileStore.req?.extension.toLowerCase() == ".epub"
);
+23
View File
@@ -42,7 +42,30 @@ function bundledAceAssets(): Plugin {
};
}
function bundledPdfAssets(): Plugin {
return {
name: "bundled-pdf-assets",
apply: "build",
generateBundle() {
const root = path.resolve(import.meta.dirname, "node_modules/pdfjs-dist");
const version = JSON.parse(
fs.readFileSync(path.join(root, "package.json"), "utf8")
).version;
for (const folder of ["cmaps", "standard_fonts"]) {
for (const name of fs.readdirSync(path.join(root, folder))) {
this.emitFile({
type: "asset",
fileName: `pdfjs/${version}/${folder}/${name}`,
source: fs.readFileSync(path.join(root, folder, name)),
});
}
}
},
};
}
const plugins = [
bundledPdfAssets(),
bundledAceAssets(),
vue(),
VueI18nPlugin({
+1 -1
View File
@@ -1,4 +1,4 @@
param([string]$Version = '3.0.0-sso.6')
param([string]$Version = '3.0.0-sso.7')
$ErrorActionPreference = 'Stop'
$repo = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
Push-Location $repo
+1 -1
View File
@@ -1,7 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
VERSION="${VERSION:-3.0.0-sso.6}"
VERSION="${VERSION:-3.0.0-sso.7}"
COMMIT=$(git rev-parse --short HEAD)
(cd frontend && pnpm install --frozen-lockfile && pnpm run build)
mkdir -p build/release/linux-amd64