|
| 1 | +import { useState } from 'react'; |
| 2 | +import saveAs from 'file-saver'; |
| 3 | +import { generateDocx } from '../services/docxGenerator'; |
| 4 | +import { ParsedBlock, DocumentMeta } from '../services/types'; |
| 5 | +import { PAGE_SIZES } from '../constants/meta'; |
| 6 | + |
| 7 | +interface UseDocxExportProps { |
| 8 | + content: string; |
| 9 | + parsedBlocks: ParsedBlock[]; |
| 10 | + documentMeta: DocumentMeta; |
| 11 | +} |
| 12 | + |
| 13 | +export const useDocxExport = ({ content, parsedBlocks, documentMeta }: UseDocxExportProps) => { |
| 14 | + const [isGenerating, setIsGenerating] = useState(false); |
| 15 | + const [selectedSizeIndex, setSelectedSizeIndex] = useState(0); |
| 16 | + |
| 17 | + // DOCX Download |
| 18 | + const handleDownload = async () => { |
| 19 | + if (parsedBlocks.length === 0) return; |
| 20 | + setIsGenerating(true); |
| 21 | + try { |
| 22 | + const sizeConfig = PAGE_SIZES[selectedSizeIndex]; |
| 23 | + const blob = await generateDocx(parsedBlocks, { |
| 24 | + widthCm: sizeConfig.width, |
| 25 | + heightCm: sizeConfig.height, |
| 26 | + showLineNumbers: true, // Default to true for technical books |
| 27 | + meta: documentMeta |
| 28 | + }); |
| 29 | + |
| 30 | + const safeTitle = documentMeta.title |
| 31 | + ? documentMeta.title.replace(/[\\/:*?"<>|]/g, '_') |
| 32 | + : "Professional_Manuscript"; |
| 33 | + |
| 34 | + saveAs(blob, `${safeTitle}.docx`); |
| 35 | + } catch (error) { |
| 36 | + console.error("Word Generation Failed:", error); |
| 37 | + alert("轉檔失敗,請確認內容格式是否正確。"); |
| 38 | + } finally { |
| 39 | + setIsGenerating(false); |
| 40 | + } |
| 41 | + }; |
| 42 | + |
| 43 | + // Markdown Export |
| 44 | + const handleExportMarkdown = () => { |
| 45 | + if (!content) return; |
| 46 | + try { |
| 47 | + const blob = new Blob([content], { type: "text/markdown;charset=utf-8" }); |
| 48 | + |
| 49 | + const safeTitle = documentMeta.title |
| 50 | + ? documentMeta.title.replace(/[\\/:*?"<>|]/g, '_') |
| 51 | + : "manuscript"; |
| 52 | + |
| 53 | + saveAs(blob, `${safeTitle}.md`); |
| 54 | + } catch (error) { |
| 55 | + console.error("Markdown Export Failed:", error); |
| 56 | + alert("匯出失敗"); |
| 57 | + } |
| 58 | + }; |
| 59 | + |
| 60 | + return { |
| 61 | + isGenerating, |
| 62 | + selectedSizeIndex, |
| 63 | + setSelectedSizeIndex, |
| 64 | + handleDownload, |
| 65 | + handleExportMarkdown, |
| 66 | + pageSizes: PAGE_SIZES |
| 67 | + }; |
| 68 | +}; |
0 commit comments