|
1 | 1 | import * as path from "path";
|
2 |
| -import { writeFile } from "fs"; |
| 2 | +import { promises } from "fs"; |
| 3 | +const { writeFile } = promises; |
3 | 4 | import { remote } from "electron";
|
4 | 5 | const { dialog } = remote;
|
5 | 6 |
|
6 | 7 | import { stringifyNotebook } from "@nteract/commutable";
|
7 | 8 |
|
8 | 9 | import store from "./store";
|
9 |
| -export default function exportNotebook() { |
10 |
| - // TODO: Refactor to use promises, this is a bit "nested". |
11 |
| - const saveNotebook = function (filename) { |
12 |
| - if (!filename) { |
13 |
| - return; |
14 |
| - } |
| 10 | +export async function exportNotebook() { |
| 11 | + const editor = atom.workspace.getActiveTextEditor(); |
| 12 | + const editorPath = editor.getPath(); |
| 13 | + const directory = path.dirname(editorPath); |
| 14 | + const rawFileName = path.basename(editorPath, path.extname(editorPath)); |
| 15 | + const noteBookPath = path.join(directory, `${rawFileName}.ipynb`); |
15 | 16 |
|
16 |
| - const ext = path.extname(filename) === "" ? ".ipynb" : ""; |
17 |
| - const fname = `${filename}${ext}`; |
18 |
| - writeFile(fname, stringifyNotebook(store.notebook), (err) => { |
19 |
| - if (err) { |
20 |
| - atom.notifications.addError("Error saving file", { |
21 |
| - detail: err.message, |
22 |
| - }); |
23 |
| - } else { |
24 |
| - atom.notifications.addSuccess("Save successful", { |
25 |
| - detail: `Saved notebook as ${fname}`, |
26 |
| - }); |
27 |
| - } |
| 17 | + const { canceled, filePath } = await dialog.showSaveDialog({ |
| 18 | + title: editor.getTitle(), |
| 19 | + defaultPath: noteBookPath, |
| 20 | + }); |
| 21 | + if (!canceled) { |
| 22 | + await saveNoteBook(filePath); |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +async function saveNoteBook(filePath: string) { |
| 27 | + if (filePath.length === 0) { |
| 28 | + return; |
| 29 | + } |
| 30 | + // add default extension |
| 31 | + const ext = path.extname(filePath) === "" ? ".ipynb" : ""; |
| 32 | + const fname = `${filePath}${ext}`; |
| 33 | + |
| 34 | + try { |
| 35 | + await writeFile(fname, stringifyNotebook(store.notebook)); |
| 36 | + atom.notifications.addSuccess("Save successful", { |
| 37 | + detail: `Saved notebook as ${fname}`, |
| 38 | + }); |
| 39 | + } catch (err) { |
| 40 | + atom.notifications.addError("Error saving file", { |
| 41 | + detail: err.message, |
28 | 42 | });
|
29 |
| - }; |
30 |
| - // TODO this API is promisified -> should be fixed |
31 |
| - dialog.showSaveDialog(saveNotebook); |
| 43 | + } |
32 | 44 | }
|
0 commit comments