SPA: экран ввода ключа и сборка под префиксом /pdf-converter/
ApiKeyGate: ключ в localStorage (wordpdf.api.key), при 401 очищается и форма открывается заново; заголовок X-API-Key подставляет только api.ts. base сборки — env VITE_BASE (дефолт '/'); vite.local.config.ts — локальный прогон без прод-префикса.
This commit is contained in:
+39
-3
@@ -1,23 +1,59 @@
|
||||
/** Ошибка API: сервер ответил не 2xx — текст из JSON `{"error": …}`. */
|
||||
export class ApiError extends Error {}
|
||||
/** Ключ не принят сервером (401): сервер изменился/ключ отозван. */
|
||||
export class UnauthorizedError extends ApiError {}
|
||||
|
||||
const API_KEY_STORAGE = 'wordpdf.api.key'
|
||||
|
||||
export function getApiKey(): string | null {
|
||||
try { return localStorage.getItem(API_KEY_STORAGE) } catch { return null }
|
||||
}
|
||||
export function setApiKey(key: string): void {
|
||||
try { localStorage.setItem(API_KEY_STORAGE, key) } catch { /* приватный режим: ключ только на эту загрузку */ }
|
||||
}
|
||||
export function clearApiKey(): void {
|
||||
try { localStorage.removeItem(API_KEY_STORAGE) } catch { /* нечего чистить */ }
|
||||
}
|
||||
|
||||
export interface ConvertResult {
|
||||
blob: Blob
|
||||
filename: string
|
||||
}
|
||||
|
||||
/** Настройки на один вызов: поля соответствуют параметрам API. Лимиты
|
||||
* входа (размер/страницы) задаёт только сервер, параметрами не шлются. */
|
||||
export interface ConvertOptions {
|
||||
renderCharts: boolean
|
||||
renderSmartArt: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Единственная сетевая точка приложения: POST /api/v1/convert (multipart,
|
||||
* поле `file`) → PDF-blob + имя файла из Content-Disposition.
|
||||
* Таймаут на фронте не ставим: конвертация долгая — это ожидаемо.
|
||||
* поля `file`, `renderCharts`, `renderSmartArt`) → PDF-blob + имя файла из
|
||||
* Content-Disposition. Таймаут на фронте не ставим: конвертация долгая —
|
||||
* это ожидаемо.
|
||||
*/
|
||||
export async function convertDocx(
|
||||
file: File,
|
||||
signal: AbortSignal,
|
||||
options: ConvertOptions,
|
||||
): Promise<ConvertResult> {
|
||||
const fd = new FormData()
|
||||
fd.append('file', file, file.name)
|
||||
const resp = await fetch('/api/v1/convert', { method: 'POST', body: fd, signal })
|
||||
fd.append('renderCharts', String(options.renderCharts))
|
||||
fd.append('renderSmartArt', String(options.renderSmartArt))
|
||||
const key = getApiKey()
|
||||
const resp = await fetch(`${import.meta.env.BASE_URL}api/v1/convert`, {
|
||||
method: 'POST',
|
||||
body: fd,
|
||||
signal,
|
||||
headers: key ? { 'X-API-Key': key } : undefined,
|
||||
})
|
||||
// очистка до UI: после отзыва ключа форма откроется пустой
|
||||
if (resp.status === 401) {
|
||||
clearApiKey()
|
||||
throw new UnauthorizedError('Ключ доступа не принят')
|
||||
}
|
||||
if (!resp.ok) {
|
||||
const json = (await resp.json().catch(() => null)) as { error?: string } | null
|
||||
throw new ApiError(json?.error ?? `HTTP ${resp.status}`)
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useState } from 'react'
|
||||
import Logo from './Logo'
|
||||
import StatusMessage from './StatusMessage'
|
||||
|
||||
interface Props {
|
||||
error: string | null
|
||||
onSubmit: (key: string) => void
|
||||
}
|
||||
|
||||
/**
|
||||
* Экран доступа: ключ вводится один раз и хранится в localStorage (в бандл
|
||||
* SPA ключ зашивать нельзя — статика публичная). Ключ не проверяется на
|
||||
* клиенте — неверный всплывёт 401 на первой конвертации.
|
||||
*/
|
||||
export default function ApiKeyGate({ error, onSubmit }: Props) {
|
||||
const [value, setValue] = useState('')
|
||||
return (
|
||||
<div className="min-h-screen bg-bg">
|
||||
<div className="mx-auto max-w-[760px] px-5 pt-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">Доступ по ключу</p>
|
||||
</div>
|
||||
</header>
|
||||
<section className="rounded-2xl border border-border bg-surface p-6 shadow-sm">
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault()
|
||||
onSubmit(value.trim())
|
||||
}}
|
||||
>
|
||||
<input
|
||||
type="password"
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
placeholder="Ключ доступа"
|
||||
autoFocus
|
||||
className="w-full rounded-lg border border-border bg-bg px-4 py-3 text-sm outline-none focus:border-accent"
|
||||
/>
|
||||
<div className="mt-5">
|
||||
<button
|
||||
type="submit"
|
||||
disabled={!value.trim()}
|
||||
className={`rounded-lg bg-accent px-6 py-3 font-medium text-white ${
|
||||
!value.trim() ? 'cursor-default opacity-60' : 'hover:bg-accent/90'
|
||||
}`}
|
||||
>
|
||||
Продолжить
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
{error && <StatusMessage kind="error" text={error} />}
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ApiError, convertDocx } from '../api'
|
||||
import { ApiError, convertDocx, getApiKey, setApiKey, UnauthorizedError } from '../api'
|
||||
import ApiKeyGate from './ApiKeyGate'
|
||||
import DropZone from './DropZone'
|
||||
import Logo from './Logo'
|
||||
import PdfPreview from './PdfPreview'
|
||||
@@ -18,9 +19,16 @@ export default function App() {
|
||||
const [status, setStatus] = useState<Status>('idle')
|
||||
const [result, setResult] = useState<Result | null>(null)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
// дефолты = константы ядра (WordPdfSettings.RENDER_CHARTS/RENDER_SMARTART)
|
||||
const [renderCharts, setRenderCharts] = useState(true)
|
||||
const [renderSmartArt, setRenderSmartArt] = useState(true)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const urlRef = useRef<string | null>(null)
|
||||
|
||||
// ключ в localStorage: публичная статика, в бандл зашивать нельзя
|
||||
const [apiKey, setApiKeyValue] = useState<string | null>(() => getApiKey())
|
||||
const [keyError, setKeyError] = useState<string | null>(null)
|
||||
|
||||
// снимаем blob-URL предыдущего результата — иначе он течёт до закрытия вкладки
|
||||
const resetResult = () => {
|
||||
if (urlRef.current) {
|
||||
@@ -43,7 +51,10 @@ export default function App() {
|
||||
setStatus('converting')
|
||||
const ac = new AbortController()
|
||||
abortRef.current = ac
|
||||
convertDocx(file, ac.signal)
|
||||
convertDocx(file, ac.signal, {
|
||||
renderCharts,
|
||||
renderSmartArt,
|
||||
})
|
||||
.then(({ blob, filename }) => {
|
||||
const url = URL.createObjectURL(blob)
|
||||
urlRef.current = url
|
||||
@@ -52,6 +63,14 @@ export default function App() {
|
||||
})
|
||||
.catch((e: unknown) => {
|
||||
if (e instanceof DOMException && e.name === 'AbortError') return
|
||||
// UnauthorizedError раньше ApiError: он её наследник; ключ уже
|
||||
// очищен в api.ts — форма откроется пустой
|
||||
if (e instanceof UnauthorizedError) {
|
||||
setApiKeyValue(null)
|
||||
setKeyError('Ключ доступа не принят — введите заново')
|
||||
setStatus('idle')
|
||||
return
|
||||
}
|
||||
// ApiError — осмысленный текст из JSON; всё остальное — нет связи
|
||||
setError(e instanceof ApiError ? e.message : 'Сервер недоступен')
|
||||
setStatus('error')
|
||||
@@ -69,16 +88,36 @@ export default function App() {
|
||||
[],
|
||||
)
|
||||
|
||||
if (!apiKey)
|
||||
return (
|
||||
<ApiKeyGate
|
||||
error={keyError}
|
||||
onSubmit={(k) => {
|
||||
setApiKey(k)
|
||||
setApiKeyValue(k)
|
||||
setKeyError(null)
|
||||
// возврат после отзыва ключа не должен показать «Конвертация…»/старый результат
|
||||
setStatus('idle')
|
||||
setError(null)
|
||||
if (urlRef.current) {
|
||||
URL.revokeObjectURL(urlRef.current)
|
||||
urlRef.current = null
|
||||
}
|
||||
setResult(null)
|
||||
}}
|
||||
/>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="min-h-screen bg-bg">
|
||||
<div className="mx-auto max-w-[760px] px-5 py-12">
|
||||
<div className="mx-auto max-w-[760px] px-5 pt-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
|
||||
страниц.
|
||||
docx → PDF на docx4j + Apache FOP. Лимиты (файл ≤ 20 МБ,
|
||||
≤ 1000 страниц) задаёт сервер; переопределение из формы убрано.
|
||||
</p>
|
||||
</div>
|
||||
</header>
|
||||
@@ -86,6 +125,29 @@ export default function App() {
|
||||
<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 flex gap-6">
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 accent-accent"
|
||||
checked={renderCharts}
|
||||
onChange={(e) => setRenderCharts(e.target.checked)}
|
||||
disabled={status === 'converting'}
|
||||
/>
|
||||
Диаграммы
|
||||
</label>
|
||||
<label className="flex items-center gap-2 text-sm">
|
||||
<input
|
||||
type="checkbox"
|
||||
className="h-4 w-4 accent-accent"
|
||||
checked={renderSmartArt}
|
||||
onChange={(e) => setRenderSmartArt(e.target.checked)}
|
||||
disabled={status === 'converting'}
|
||||
/>
|
||||
SmartArt
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div className="mt-5">
|
||||
<button
|
||||
type="button"
|
||||
@@ -116,22 +178,24 @@ export default function App() {
|
||||
/>
|
||||
)}
|
||||
{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>
|
||||
|
||||
{status === 'done' && result && (
|
||||
<div className="px-6">
|
||||
<PdfPreview url={result.url} filename={result.filename} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<footer className="mx-auto max-w-[760px] px-5 pt-8 pb-12 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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,11 +6,11 @@ interface Props {
|
||||
/** Предпросмотр PDF (blob-URL в iframe) + кнопки скачивания. */
|
||||
export default function PdfPreview({ url, filename }: Props) {
|
||||
return (
|
||||
<section className="mt-6">
|
||||
<section className="mt-8">
|
||||
<iframe
|
||||
src={url}
|
||||
title="Предпросмотр PDF"
|
||||
className="h-[65vh] w-full rounded-xl border-0 shadow-sm"
|
||||
className="h-[85vh] w-full rounded-xl border-0 shadow-sm"
|
||||
/>
|
||||
<div className="mt-4 flex gap-3">
|
||||
<a
|
||||
|
||||
Reference in New Issue
Block a user