mirror of
https://github.com/amitwh/markdown-converter.git
synced 2026-08-02 10:00:17 +05:30
feat(renderer): WordExportDialog (docx export with template picker)
This commit is contained in:
@@ -0,0 +1,114 @@
|
|||||||
|
import { useState, useEffect } from 'react';
|
||||||
|
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||||
|
import { useAppStore } from '@/stores/app-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
import { useExportSource } from '@/hooks/use-export-source';
|
||||||
|
import { generateDocx } from '@/lib/docx-export';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
|
||||||
|
export function WordExportDialog({ sourcePath }: { sourcePath: string }) {
|
||||||
|
const closeModal = useAppStore((s) => s.closeModal);
|
||||||
|
const setSetting = useSettingsStore((s) => s.setSetting);
|
||||||
|
const docxCustomTemplatePath = useSettingsStore((s) => s.docxCustomTemplatePath);
|
||||||
|
const source = useExportSource();
|
||||||
|
|
||||||
|
const [templateMode, setTemplateMode] = useState<'standard' | 'custom'>(docxCustomTemplatePath ? 'custom' : 'standard');
|
||||||
|
const [submitting, setSubmitting] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
setTemplateMode(docxCustomTemplatePath ? 'custom' : 'standard');
|
||||||
|
}, [docxCustomTemplatePath]);
|
||||||
|
|
||||||
|
const handleChooseTemplate = async () => {
|
||||||
|
const result = await ipc.app.showSaveDialog?.({ title: 'Choose template path' });
|
||||||
|
if (result?.ok && result.data) {
|
||||||
|
setSetting('docxCustomTemplatePath', result.data);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!source) { setError('No file open.'); return; }
|
||||||
|
setSubmitting(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const blob = await generateDocx({
|
||||||
|
source: source.source,
|
||||||
|
title: source.title,
|
||||||
|
customTemplatePath: templateMode === 'custom' ? docxCustomTemplatePath : null,
|
||||||
|
});
|
||||||
|
const saveResult = await ipc.app.showSaveDialog?.({ title: 'Save as Word document', defaultPath: source.path.replace(/\.md$/, '.docx') });
|
||||||
|
if (!saveResult?.ok || !saveResult.data) {
|
||||||
|
setSubmitting(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const buffer = new Uint8Array(await blob.arrayBuffer());
|
||||||
|
const writeResult = await ipc.file.writeBuffer({ path: saveResult.data, buffer });
|
||||||
|
if (!writeResult.ok) {
|
||||||
|
setError(writeResult.error.message);
|
||||||
|
setSubmitting(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
toast.success(`Exported ${source.title} to ${saveResult.data}`);
|
||||||
|
closeModal();
|
||||||
|
} catch (err) {
|
||||||
|
const msg = err instanceof Error ? err.message : String(err);
|
||||||
|
toast.error(`Export failed: ${msg}`);
|
||||||
|
setError(msg);
|
||||||
|
setSubmitting(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open onOpenChange={(o) => !o && closeModal()}>
|
||||||
|
<DialogContent aria-describedby="word-desc">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>Export to Word (.docx)</DialogTitle>
|
||||||
|
<DialogDescription id="word-desc">{sourcePath}</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
<div className="space-y-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<Label>Template</Label>
|
||||||
|
<RadioGroup value={templateMode} onValueChange={(v) => setTemplateMode(v as 'standard' | 'custom')}>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<RadioGroupItem value="standard" id="template-standard" />
|
||||||
|
<Label htmlFor="template-standard">Standard (bundled)</Label>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<RadioGroupItem value="custom" id="template-custom" />
|
||||||
|
<Label htmlFor="template-custom">Custom .dotx</Label>
|
||||||
|
</div>
|
||||||
|
</RadioGroup>
|
||||||
|
</div>
|
||||||
|
{templateMode === 'custom' && (
|
||||||
|
<div className="rounded border border-border bg-card/20 p-2 text-xs">
|
||||||
|
{docxCustomTemplatePath ? (
|
||||||
|
<span>Template path: <code>{docxCustomTemplatePath}</code></span>
|
||||||
|
) : (
|
||||||
|
<span className="text-muted-foreground">No template selected. Click "Choose template..." to pick a .dotx file.</span>
|
||||||
|
)}
|
||||||
|
<Button variant="ghost" size="sm" onClick={handleChooseTemplate} className="ml-2">
|
||||||
|
Choose template...
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<div role="alert" className="rounded border border-destructive/40 bg-destructive/5 p-2 text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<DialogFooter>
|
||||||
|
<Button variant="ghost" onClick={closeModal} disabled={submitting}>Cancel</Button>
|
||||||
|
<Button onClick={handleSubmit} disabled={submitting}>
|
||||||
|
{submitting ? 'Exporting…' : 'Export'}
|
||||||
|
</Button>
|
||||||
|
</DialogFooter>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -102,6 +102,8 @@ export const ipc = {
|
|||||||
safeCall('app', 'openExternal', url),
|
safeCall('app', 'openExternal', url),
|
||||||
showItemInFolder: (path: string): Promise<IpcResult<void | ChannelMissing>> =>
|
showItemInFolder: (path: string): Promise<IpcResult<void | ChannelMissing>> =>
|
||||||
safeCall('app', 'showItemInFolder', path),
|
safeCall('app', 'showItemInFolder', path),
|
||||||
|
showSaveDialog: (args?: { title?: string; defaultPath?: string }): Promise<IpcResult<string | null | ChannelMissing>> =>
|
||||||
|
safeCall('app', 'showSaveDialog', args),
|
||||||
},
|
},
|
||||||
menu: {
|
menu: {
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||||
|
import { render, screen } from '@testing-library/react';
|
||||||
|
import userEvent from '@testing-library/user-event';
|
||||||
|
import { WordExportDialog } from '@/components/modals/WordExportDialog';
|
||||||
|
import { useFileStore } from '@/stores/file-store';
|
||||||
|
import { useEditorStore } from '@/stores/editor-store';
|
||||||
|
import { useSettingsStore } from '@/stores/settings-store';
|
||||||
|
|
||||||
|
vi.mock('@/lib/docx-export', () => ({
|
||||||
|
generateDocx: vi.fn().mockResolvedValue(new Blob([new Uint8Array([1, 2, 3])], { type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' })),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/lib/toast', () => ({
|
||||||
|
toast: {
|
||||||
|
success: vi.fn(),
|
||||||
|
error: vi.fn(),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@/lib/ipc', () => ({
|
||||||
|
ipc: {
|
||||||
|
app: {
|
||||||
|
showSaveDialog: vi.fn(),
|
||||||
|
},
|
||||||
|
file: {
|
||||||
|
writeBuffer: vi.fn(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { generateDocx } from '@/lib/docx-export';
|
||||||
|
import { toast } from '@/lib/toast';
|
||||||
|
import { ipc } from '@/lib/ipc';
|
||||||
|
|
||||||
|
describe('WordExportDialog', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
localStorage.clear();
|
||||||
|
vi.clearAllMocks();
|
||||||
|
useSettingsStore.setState(useSettingsStore.getInitialState());
|
||||||
|
useFileStore.setState({ activeTabId: '/test.md', openTabs: [{ id: '/test.md', path: '/test.md', title: 'test.md', dirty: false }] } as any);
|
||||||
|
useEditorStore.setState({ buffers: new Map([['/test.md', { id: '/test.md', path: '/test.md', content: '# hi', dirty: false }]]) } as any);
|
||||||
|
(ipc.app.showSaveDialog as any).mockResolvedValue({ ok: true, data: '/out.docx' });
|
||||||
|
(ipc.file.writeBuffer as any).mockResolvedValue({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('renders with template selector (standard / custom)', () => {
|
||||||
|
render(<WordExportDialog sourcePath="/test.md" />);
|
||||||
|
expect(screen.getByText(/export to word/i)).toBeInTheDocument();
|
||||||
|
expect(screen.getByText(/test\.md/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('submitting calls generateDocx and writes the file', async () => {
|
||||||
|
render(<WordExportDialog sourcePath="/test.md" />);
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: /^export$/i }));
|
||||||
|
expect(generateDocx).toHaveBeenCalledTimes(1);
|
||||||
|
expect(ipc.file.writeBuffer).toHaveBeenCalledTimes(1);
|
||||||
|
expect(toast.success).toHaveBeenCalledWith(expect.stringContaining('Exported test.md'));
|
||||||
|
});
|
||||||
|
|
||||||
|
it('shows error message on write failure', async () => {
|
||||||
|
(ipc.file.writeBuffer as any).mockResolvedValue({ ok: false, error: { code: 'E', message: 'write failed' } });
|
||||||
|
render(<WordExportDialog sourcePath="/test.md" />);
|
||||||
|
await userEvent.click(screen.getByRole('button', { name: /^export$/i }));
|
||||||
|
expect(await screen.findByText(/write failed/i)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('switches to custom template path when "Custom" is selected', async () => {
|
||||||
|
useSettingsStore.setState({ ...useSettingsStore.getInitialState(), docxCustomTemplatePath: '/my.dotx' });
|
||||||
|
render(<WordExportDialog sourcePath="/test.md" />);
|
||||||
|
expect(screen.getByText(/\/my\.dotx/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user