diff --git a/src/lib/prompt-filename.ts b/src/lib/prompt-filename.ts new file mode 100644 index 0000000..5dcaee2 --- /dev/null +++ b/src/lib/prompt-filename.ts @@ -0,0 +1,17 @@ +/** + * Prompts the user for a filename before download. Returns the chosen base + * name (without extension) sanitized for filesystem use, or null if cancelled. + * + * @param defaultName Suggested base name (no extension) + * @param ext Extension shown to the user, e.g. "pdf", "docx", "csv" + */ +export function promptFilename(defaultName: string, ext: string): string | null { + const sanitize = (s: string) => s.replace(/[\\/:*?"<>|]+/g, "_").trim(); + const cleanDefault = sanitize(defaultName).replace(new RegExp(`\\.${ext}$`, "i"), "") || "Document"; + const input = typeof window !== "undefined" + ? window.prompt(`File name (.${ext})`, cleanDefault) + : cleanDefault; + if (input === null) return null; // user cancelled + const cleaned = sanitize(input).replace(new RegExp(`\\.${ext}$`, "i"), ""); + return cleaned || cleanDefault; +}