Замена wordpdf-cli на Spring Boot REST API: wordpdf-app, SPA wordpdf-web, docker-compose
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
node_modules
|
||||
dist
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
FROM node:24-alpine AS build
|
||||
# docker-прокси из ~/.docker/config.json BuildKit подмешивает в каждый RUN
|
||||
# (ENV не перебивает), а 127.0.0.1 внутри контейнера недостижим — npm ci падает
|
||||
# с ECONNREFUSED. Контейнер в сеть ходит напрямую, потому обнуляем прокси
|
||||
# на самой команде.
|
||||
WORKDIR /build
|
||||
COPY package.json package-lock.json ./
|
||||
RUN HTTP_PROXY= http_proxy= HTTPS_PROXY= https_proxy= ALL_PROXY= all_proxy= npm ci
|
||||
COPY . .
|
||||
RUN npm run build
|
||||
|
||||
FROM nginx:alpine
|
||||
COPY nginx.conf /etc/nginx/conf.d/default.conf
|
||||
COPY --from=build /build/dist /usr/share/nginx/html
|
||||
# прокси из docker-config подмешивается в HEALTHCHECK-шелл — обнуляем на команде
|
||||
HEALTHCHECK --interval=10s --timeout=3s --start-period=10s \
|
||||
CMD http_proxy= https_proxy= wget -qO /dev/null http://127.0.0.1/ || exit 1
|
||||
@@ -0,0 +1,22 @@
|
||||
# wordpdf-web
|
||||
|
||||
SPA-фронт конвертера Word → PDF: React 19 + TypeScript + Vite + Tailwind CSS v4.
|
||||
В Maven-сборку не входит; деплоится отдельным nginx-контейнером (см.
|
||||
`Dockerfile`/`nginx.conf` и корневой `docker-compose.yml`).
|
||||
|
||||
## Dev
|
||||
|
||||
```bash
|
||||
npm install
|
||||
npm run dev # http://localhost:5173, /api проксируется на :8080
|
||||
```
|
||||
|
||||
Бэкенд для dev: `java -jar ../wordpdf-app/target/wordpdf-app-1.0.0.jar`.
|
||||
|
||||
## Сборка
|
||||
|
||||
```bash
|
||||
npm run build # tsc -b && vite build → dist/
|
||||
```
|
||||
|
||||
UI-тестов нет; гейт — успешная сборка (`tsc -b` ловит типизацию).
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Word → PDF</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,11 @@
|
||||
server {
|
||||
listen 80;
|
||||
root /usr/share/nginx/html;
|
||||
index index.html;
|
||||
# без него upload >1MB режется HTML-413 от nginx до бэкенда
|
||||
client_max_body_size 6m;
|
||||
location /api/ { proxy_pass http://app:8080; }
|
||||
location /swagger-ui { proxy_pass http://app:8080; }
|
||||
location /v3/api-docs { proxy_pass http://app:8080; }
|
||||
location / { try_files $uri $uri/ /index.html; }
|
||||
}
|
||||
Generated
+1942
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"name": "wordpdf-web",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.18",
|
||||
"@types/react-dom": "^19.2.7",
|
||||
"@vitejs/plugin-react": "^6.1.1",
|
||||
"oxlint": "^1.81.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.3.0"
|
||||
}
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,32 @@
|
||||
/** Ошибка API: сервер ответил не 2xx — текст из JSON `{"error": …}`. */
|
||||
export class ApiError extends Error {}
|
||||
|
||||
export interface ConvertResult {
|
||||
blob: Blob
|
||||
filename: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Единственная сетевая точка приложения: POST /api/v1/convert (multipart,
|
||||
* поле `file`) → PDF-blob + имя файла из Content-Disposition.
|
||||
* Таймаут на фронте не ставим: конвертация долгая — это ожидаемо.
|
||||
*/
|
||||
export async function convertDocx(
|
||||
file: File,
|
||||
signal: AbortSignal,
|
||||
): Promise<ConvertResult> {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file, file.name)
|
||||
const resp = await fetch('/api/v1/convert', { method: 'POST', body: fd, signal })
|
||||
if (!resp.ok) {
|
||||
const json = (await resp.json().catch(() => null)) as { error?: string } | null
|
||||
throw new ApiError(json?.error ?? `HTTP ${resp.status}`)
|
||||
}
|
||||
// Framework 7 отдаёт `filename*=UTF-8''…` (charset в верхнем регистре) —
|
||||
// флаг i обязателен; фолбэк — имя исходника с заменой расширения
|
||||
const cd = resp.headers.get('Content-Disposition') ?? ''
|
||||
const m = /filename\*=utf-8''([^;]+)/i.exec(cd)
|
||||
const filename = m ? decodeURIComponent(m[1]) : file.name.replace(/\.docx$/i, '') + '.pdf'
|
||||
const blob = await resp.blob()
|
||||
return { blob, filename }
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ApiError, convertDocx } from '../api'
|
||||
import DropZone from './DropZone'
|
||||
import Logo from './Logo'
|
||||
import PdfPreview from './PdfPreview'
|
||||
import StatusMessage from './StatusMessage'
|
||||
|
||||
type Status = 'idle' | 'converting' | 'done' | 'error'
|
||||
|
||||
interface Result {
|
||||
url: string
|
||||
filename: string
|
||||
size: number
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
const [file, setFile] = useState<File | null>(null)
|
||||
const [status, setStatus] = useState<Status>('idle')
|
||||
const [result, setResult] = useState<Result | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const urlRef = useRef<string | null>(null)
|
||||
|
||||
// снимаем blob-URL предыдущего результата — иначе он течёт до закрытия вкладки
|
||||
const resetResult = () => {
|
||||
if (urlRef.current) {
|
||||
URL.revokeObjectURL(urlRef.current)
|
||||
urlRef.current = null
|
||||
}
|
||||
setResult(null)
|
||||
setError(null)
|
||||
}
|
||||
|
||||
const selectFile = (picked: File) => {
|
||||
resetResult()
|
||||
setStatus('idle')
|
||||
setFile(picked)
|
||||
}
|
||||
|
||||
const convert = () => {
|
||||
if (!file || status === 'converting') return
|
||||
resetResult()
|
||||
setStatus('converting')
|
||||
const ac = new AbortController()
|
||||
abortRef.current = ac
|
||||
convertDocx(file, ac.signal)
|
||||
.then(({ blob, filename }) => {
|
||||
const url = URL.createObjectURL(blob)
|
||||
urlRef.current = url
|
||||
setResult({ url, filename, size: blob.size })
|
||||
setStatus('done')
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return
|
||||
// ApiError — осмысленный текст из JSON; всё остальное — нет связи
|
||||
setError(e instanceof ApiError ? e.message : 'Сервер недоступен')
|
||||
setStatus('error')
|
||||
})
|
||||
.finally(() => {
|
||||
abortRef.current = null
|
||||
})
|
||||
}
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
abortRef.current?.abort()
|
||||
if (urlRef.current) URL.revokeObjectURL(urlRef.current)
|
||||
},
|
||||
[],
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-bg">
|
||||
<div className="mx-auto max-w-[760px] px-5 py-12">
|
||||
<header className="mb-8 flex items-center gap-3">
|
||||
<Logo className="h-10 w-10 shrink-0 text-accent" />
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold">Word → PDF</h1>
|
||||
<p className="mt-1 text-sm text-muted">
|
||||
docx → PDF на docx4j + Apache FOP. Лимиты: файл ≤ 5 МБ, документ ≤ 100
|
||||
страниц.
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
|
||||
<DropZone file={file} disabled={status === 'converting'} onSelect={selectFile} />
|
||||
|
||||
<div className="mt-5">
|
||||
<button
|
||||
type="button"
|
||||
onClick={convert}
|
||||
disabled={!file || status === 'converting'}
|
||||
className={`flex items-center gap-2 rounded-lg bg-accent px-6 py-3 font-medium text-white ${
|
||||
!file || status === 'converting' ? 'cursor-default opacity-60' : 'hover:bg-accent/90'
|
||||
}`}
|
||||
>
|
||||
{status === 'converting' ? (
|
||||
<>
|
||||
<span
|
||||
className="h-4 w-4 animate-spin rounded-full border-2 border-white/40 border-t-white"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
Конвертация…
|
||||
</>
|
||||
) : (
|
||||
'Конвертировать'
|
||||
)}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{status === 'done' && result && (
|
||||
<StatusMessage
|
||||
kind="success"
|
||||
text={`Готово · ${result.filename} · ${(result.size / 1024).toFixed(0)} КБ`}
|
||||
/>
|
||||
)}
|
||||
{status === 'error' && error && <StatusMessage kind="error" text={error} />}
|
||||
|
||||
{status === 'done' && result && (
|
||||
<PdfPreview url={result.url} filename={result.filename} />
|
||||
)}
|
||||
</section>
|
||||
|
||||
<footer className="mt-8 text-sm text-muted">
|
||||
<a href="/swagger-ui.html" className="underline-offset-2 hover:text-accent hover:underline">
|
||||
Swagger UI
|
||||
</a>
|
||||
{' · '}
|
||||
<a href="/v3/api-docs" className="underline-offset-2 hover:text-accent hover:underline">
|
||||
OpenAPI
|
||||
</a>
|
||||
</footer>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import { useRef, useState } from 'react'
|
||||
import type { DragEvent } from 'react'
|
||||
|
||||
interface Props {
|
||||
file: File | null
|
||||
disabled: boolean
|
||||
onSelect: (file: File) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Зона drag&drop + клик для выбора .docx. Скрытый input[type=file] —
|
||||
* единственный источник выбора; drop берёт первый файл.
|
||||
*/
|
||||
export default function DropZone({ file, disabled, onSelect }: Props) {
|
||||
const inputRef = useRef<HTMLInputElement>(null)
|
||||
const [dragging, setDragging] = useState(false)
|
||||
|
||||
const onDrop = (e: DragEvent<HTMLLabelElement>) => {
|
||||
e.preventDefault()
|
||||
setDragging(false)
|
||||
if (disabled) return
|
||||
const dropped = e.dataTransfer.files[0]
|
||||
if (dropped) onSelect(dropped)
|
||||
}
|
||||
|
||||
return (
|
||||
<label
|
||||
onDragOver={(e) => {
|
||||
e.preventDefault()
|
||||
if (!disabled) setDragging(true)
|
||||
}}
|
||||
onDragLeave={(e) => {
|
||||
e.preventDefault()
|
||||
setDragging(false)
|
||||
}}
|
||||
onDrop={onDrop}
|
||||
className={`flex cursor-pointer flex-col items-center gap-3 rounded-xl border-2 border-dashed p-9 text-center transition-colors ${
|
||||
dragging
|
||||
? 'border-accent bg-accent/6'
|
||||
: 'border-border hover:border-accent hover:bg-accent/6'
|
||||
}`}
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="1.8"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="h-9 w-9 text-accent"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path d="M12 16V4m0 0-4 4m4-4 4 4" />
|
||||
<path d="M4 16v3a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-3" />
|
||||
</svg>
|
||||
<span>Перетащите .docx сюда или нажмите для выбора</span>
|
||||
{file && (
|
||||
<span className="text-sm text-muted">
|
||||
{file.name} · {(file.size / 1024).toFixed(0)} КБ
|
||||
</span>
|
||||
)}
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="file"
|
||||
accept=".docx"
|
||||
className="sr-only"
|
||||
disabled={disabled}
|
||||
onChange={(e) => {
|
||||
const picked = e.target.files?.[0]
|
||||
if (picked) onSelect(picked)
|
||||
// сбрасываем value — иначе повторный выбор того же файла не событие
|
||||
e.target.value = ''
|
||||
}}
|
||||
/>
|
||||
</label>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/** Логотип: лист A4 → стрелка → лист PDF. Красится currentColor. */
|
||||
export default function Logo({ className }: { className?: string }) {
|
||||
return (
|
||||
<svg
|
||||
viewBox="0 0 40 40"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className={className}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<rect x="2.5" y="8" width="15" height="24" rx="2" />
|
||||
<path d="M6.5 14.5h7M6.5 19h7M6.5 23.5h4" />
|
||||
<path d="M20 20h7m0 0-2.5-2.5M27 20l-2.5 2.5" />
|
||||
<rect x="29.5" y="8" width="8" height="24" rx="2" />
|
||||
<path d="M31.5 26.5h4M31.5 14h4v5h-4z" />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
interface Props {
|
||||
url: string
|
||||
filename: string
|
||||
}
|
||||
|
||||
/** Предпросмотр PDF (blob-URL в iframe) + кнопки скачивания. */
|
||||
export default function PdfPreview({ url, filename }: Props) {
|
||||
return (
|
||||
<section className="mt-6">
|
||||
<iframe
|
||||
src={url}
|
||||
title="Предпросмотр PDF"
|
||||
className="h-[65vh] w-full rounded-xl border-0 shadow-sm"
|
||||
/>
|
||||
<div className="mt-4 flex gap-3">
|
||||
<a
|
||||
href={url}
|
||||
download={filename}
|
||||
className="rounded-lg bg-accent px-6 py-3 font-medium text-white hover:bg-accent/90"
|
||||
>
|
||||
Скачать PDF
|
||||
</a>
|
||||
<a
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener"
|
||||
className="rounded-lg border border-border px-6 py-3 font-medium hover:border-accent"
|
||||
>
|
||||
Открыть в новой вкладке
|
||||
</a>
|
||||
</div>
|
||||
</section>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
interface Props {
|
||||
kind: 'success' | 'error'
|
||||
/** Для success: «Готово · имя · КБ»; для error: текст ошибки. */
|
||||
text: string
|
||||
}
|
||||
|
||||
/** Строка результата над/под кнопкой: успех (зелёный) или ошибка (красный). */
|
||||
export default function StatusMessage({ kind, text }: Props) {
|
||||
const ok = kind === 'success'
|
||||
return (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={`mt-5 flex items-center gap-2 text-sm font-medium ${
|
||||
ok ? 'text-ok' : 'text-err'
|
||||
}`}
|
||||
>
|
||||
<svg
|
||||
viewBox="0 0 20 20"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
className="h-4.5 w-4.5 shrink-0"
|
||||
aria-hidden="true"
|
||||
>
|
||||
{ok ? <path d="M4 10.5l4 4 8-9" /> : <path d="M5 5l10 10M15 5 5 15" />}
|
||||
</svg>
|
||||
{text}
|
||||
</p>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
@theme {
|
||||
--color-bg: #f6f7f9;
|
||||
--color-surface: #ffffff;
|
||||
--color-border: #e3e6ea;
|
||||
--color-text: #1c2333;
|
||||
--color-muted: #667085;
|
||||
--color-accent: #2f6fed;
|
||||
--color-ok: #1a7f37;
|
||||
--color-err: #d1242f;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--color-bg: #0f1420;
|
||||
--color-surface: #171e2e;
|
||||
--color-border: #2a3348;
|
||||
--color-text: #e6e9f0;
|
||||
--color-muted: #98a2b3;
|
||||
--color-accent: #4f83f1;
|
||||
--color-ok: #3fb950;
|
||||
--color-err: #f85149;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
@apply bg-bg text-text antialiased;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './components/App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig } from 'vite'
|
||||
|
||||
// https://vite.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
// dev без CORS: запросы /api идут на бэкенд через прокси
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8080',
|
||||
},
|
||||
},
|
||||
})
|
||||
Reference in New Issue
Block a user