81 lines
2.4 KiB
TypeScript
81 lines
2.4 KiB
TypeScript
import type { Editor } from "@tiptap/react"
|
|
import { exportTipTapToDocx, type TipTapJSON } from "@/lib/drive/richtext-import"
|
|
|
|
export type DocsDownloadFormat =
|
|
| "docx"
|
|
| "pdf"
|
|
| "odt"
|
|
| "txt"
|
|
| "rtf"
|
|
| "html"
|
|
| "html-zip"
|
|
| "epub"
|
|
| "md"
|
|
|
|
export const DOCS_DOWNLOAD_FORMATS: { id: DocsDownloadFormat; label: string }[] = [
|
|
{ id: "docx", label: "Microsoft Word (.docx)" },
|
|
{ id: "pdf", label: "Document PDF (.pdf)" },
|
|
{ id: "odt", label: "Format OpenDocument (.odt)" },
|
|
{ id: "txt", label: "Texte brut (.txt)" },
|
|
{ id: "rtf", label: "Format texte enrichi (.rtf)" },
|
|
{ id: "html-zip", label: "Page Web (.html, zippé)" },
|
|
{ id: "epub", label: "Publication EPUB (.epub)" },
|
|
{ id: "md", label: "Markdown (.md)" },
|
|
]
|
|
|
|
function downloadBlob(blob: Blob, fileName: string) {
|
|
const url = URL.createObjectURL(blob)
|
|
const anchor = document.createElement("a")
|
|
anchor.href = url
|
|
anchor.download = fileName
|
|
anchor.click()
|
|
URL.revokeObjectURL(url)
|
|
}
|
|
|
|
function baseNameWithoutExt(fileName: string): string {
|
|
const slash = fileName.lastIndexOf("/")
|
|
const base = slash >= 0 ? fileName.slice(slash + 1) : fileName
|
|
const dot = base.lastIndexOf(".")
|
|
return dot > 0 ? base.slice(0, dot) : base
|
|
}
|
|
|
|
export function exportFileName(sourceName: string, ext: string): string {
|
|
return `${baseNameWithoutExt(sourceName)}.${ext}`
|
|
}
|
|
|
|
export async function exportDocsContent(
|
|
format: DocsDownloadFormat,
|
|
editor: Editor | null,
|
|
sourceName: string
|
|
): Promise<"done" | "unsupported"> {
|
|
if (!editor) return "unsupported"
|
|
|
|
const content = editor.getJSON() as TipTapJSON
|
|
const base = baseNameWithoutExt(sourceName)
|
|
|
|
switch (format) {
|
|
case "docx": {
|
|
const blob = await exportTipTapToDocx(content)
|
|
downloadBlob(blob, exportFileName(sourceName, "docx"))
|
|
return "done"
|
|
}
|
|
case "txt": {
|
|
const text = editor.getText()
|
|
downloadBlob(new Blob([text], { type: "text/plain;charset=utf-8" }), `${base}.txt`)
|
|
return "done"
|
|
}
|
|
case "md": {
|
|
const text = editor.getText()
|
|
downloadBlob(new Blob([text], { type: "text/markdown;charset=utf-8" }), `${base}.md`)
|
|
return "done"
|
|
}
|
|
case "html": {
|
|
const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><title>${base}</title></head><body>${editor.getHTML()}</body></html>`
|
|
downloadBlob(new Blob([html], { type: "text/html;charset=utf-8" }), `${base}.html`)
|
|
return "done"
|
|
}
|
|
default:
|
|
return "unsupported"
|
|
}
|
|
}
|