forked from metawops/obsidian-table-to-csv-export
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
239 lines (195 loc) · 7.26 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// adapted from: https://github.com/metawops/obsidian-table-to-csv-export/blob/44a12b5f8c50fcb0ec15fb3ea578c81ea8ddb6d8/main.ts
// Original header:
//
// ----------------------------------------------------------------------------------------
// File : main.ts
// Author : Stefan Wolfrum (@metawops)
// Date : 2022-05-27
// Last Update: 2022-06-12
// Description: Implementation of my very first Obsidian plugin.
// It allows to export rendered HTML tables (i.e. from a pane in reading mode)
// to be exported to a CSV file and optionally to the clipboard, too.
// Purely based on the Obsidian sample plugin.
// ----------------------------------------------------------------------------------------
import { MarkdownView, Notice, Plugin, Modal, App, Setting } from 'obsidian';
import Table2CSVSettingTab, { formatCell, getSepChar } from 'settings';
import { parseMarkdownTable, formatCsv } from 'tableUtils';
export type RemoveCRLFOptions =
| 'removeCRLF-clear'
| 'removeCRLF-space'
| 'removeCRLF-string1';
export type QuoteCharOptions =
| 'quoteChar-doubleQuotes'
| 'quoteChar-singleQuotes'
| 'quoteChar-noQuote';
export type SepCharOptions =
| 'sepChar-semicolon'
| 'sepChar-comma'
| 'sepChar-tab'
| 'sepChar-pipe'
| 'sepChar-tilde'
| 'sepChar-caret'
| 'sepChar-colon';
export type Table2CSVSettings = {
exportPath: string;
baseFilename: string;
sepChar: SepCharOptions;
quoteDataChar: QuoteCharOptions;
saveToClipboardToo: boolean;
removeCRLF: RemoveCRLFOptions;
};
const DEFAULT_SETTINGS: Table2CSVSettings = {
exportPath: './',
baseFilename: 'table-export',
sepChar: 'sepChar-comma',
quoteDataChar: 'quoteChar-noQuote',
saveToClipboardToo: false,
removeCRLF: 'removeCRLF-space'
};
const convertTable = (
table: HTMLTableElement,
settings: Table2CSVSettings
): string => {
const sepChar = getSepChar(settings);
return Array.from(table.rows)
.map((row) => {
const cols = Array.from(row.querySelectorAll<HTMLTableCellElement>('td, th'));
const formattedCells = cols.map((col) => formatCell(col.innerText, settings));
console.log(formattedCells)
return formattedCells.join(sepChar);
})
.join('\n');
};
const htmlToCSV = (
html: HTMLElement,
settings: Table2CSVSettings,
idx: number,
): string => {
const table = html.querySelectorAll('table');
return table !== null ? convertTable(table[idx], settings) : '';
}
export class ExampleModal extends Modal {
result: string;
onSubmit: (result: string) => void;
constructor(app: App, onSubmit: (result: string) => void) {
super(app);
this.onSubmit = onSubmit;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl("h1", { text: "File name" });
// TODO: option to select folder
// TODO: xlsx option?
new Setting(contentEl)
.setName("Name")
.addText((text) =>
text.onChange((value) => {
this.result = value
}));
new Setting(contentEl)
.addButton((btn) =>
btn
.setButtonText("Submit")
.setCta()
.onClick(() => {
this.close();
this.onSubmit(this.result);
}));
}
onClose() {
let { contentEl } = this;
contentEl.empty();
}
}
export default class Table2CSVPlugin extends Plugin {
settings: Table2CSVSettings;
async onload(): Promise<void> {
await this.loadSettings();
this.addCommand({
id: 'obsidian-table-to-csv-exporter',
name: 'Export table to CSV file',
checkCallback: (checking) => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
return false;
}
if (checking) {
return true;
}
// Here we can actually start with our work
const viewMode = view.getMode();
if (viewMode !== 'preview') {
new Notice(
'This command only works on panes in edit mode! - No CSV files were written.'
);
// use previous functionality in preview mode:
//
// const csvString = htmlToCSV(
// view.previewMode.containerEl,
// this.settings
// );
// TODO: ask which table number to export
// > say that if you go in edit mode it will save the one at cursor position
}
const editorPosition = view.editor.getCursor();
let tableStartingLine = editorPosition.line;
let tableEndingLine = editorPosition.line;
if (view.editor.getLine(tableStartingLine)[0] !== '|') {
// exception
}
while (view.editor.getLine(tableStartingLine)[0] === '|') {
tableStartingLine--;
}
while (view.editor.getLine(tableEndingLine)[0] === '|') {
tableEndingLine++;
}
const mdTable = view.editor.getRange(
{ line: tableStartingLine, ch: 0 },
{ line: tableEndingLine, ch: 0 },
);
const table = parseMarkdownTable(mdTable);
const csvString = formatCsv(table);
// If csvString is not empty, create file:
if (csvString.length === 0) {
new Notice(`No table was found. No CSV file was written.`);
}
new ExampleModal(this.app, (result) => {
// todo: if doesn't already end in .csv:
const fileName = result + ".csv";
this.app.vault.create(fileName, csvString)
.then(() => {
if (!this.settings.saveToClipboardToo) {
new Notice(`The file ${fileName} was successfully created in your vault.`)
}
navigator.clipboard
.writeText(csvString)
.then(() => {
new Notice(
`The file ${fileName} was successfully created in your vault. The `
+ 'contents was also copied to the clipboard.'
);
})
.catch((err) => {
new Notice(
'There was an error with copying the contents to the clipboard.'
);
});
})
.catch((error) => {
const errorMessage = `Error: ${error.message}`;
new Notice(errorMessage);
});
}).open();
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new Table2CSVSettingTab(this.app, this));
console.log(`Table to CSV plugin: Version ${this.manifest.version} loaded.`);
}
async loadSettings(): Promise<void> {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings(): Promise<void> {
await this.saveData(this.settings);
}
};