-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTranslators.ts
72 lines (56 loc) · 2.05 KB
/
Translators.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
import { Note, Notepad, Section } from './index';
import { parse } from 'date-fns';
import { OptionsV2, parseString } from 'xml2js';
export namespace Translators {
export namespace Json {
export function toNotepad(json: string): Notepad {
const jsonObj: Notepad = JSON.parse(json);
let notepad = new Notepad(jsonObj.title, {
lastModified: parse(jsonObj.lastModified),
notepadAssets: jsonObj.notepadAssets || []
});
// Restore sections
jsonObj.sections.forEach(section => notepad = notepad.addSection(restoreSection(section)));
// TODO: Restore assets
return notepad;
}
function restoreSection(section: Section): Section {
let restored = new Section(section.title).clone({ internalRef: section.internalRef });
section.sections.forEach(s => restored = restored.addSection(restoreSection(s)));
section.notes.forEach(n => restored = restored.addNote(restoreNote(n)));
return restored;
}
function restoreNote(note: Note) {
return new Note(note.title, note.time, note.elements, note.bibliography, note.internalRef);
}
}
export namespace Xml {
export async function toNotepadFromNpx(xml: string): Promise<Notepad> {
const res = await parseXml(xml);
let notepad = new Notepad(res.notepad.$.title, { lastModified: res.notepad.$.lastModified });
// Parse sections/notes
if (res.notepad.section) {
res.notepad.section.forEach(s => notepad = notepad.addSection(parseSection(s)));
}
// TODO: Parse assets
return notepad;
function parseSection(sectionObj: any): Section {
let section = new Section(sectionObj.$.title);
// Insert sub-sections recursively because notepads are trees
(sectionObj.section || []).forEach(item => {
section = section.addSection(parseSection(item));
});
// TODO: Parse notes
return section;
}
}
function parseXml(xml: string, opts: OptionsV2 = {}): Promise<any> {
return new Promise<any>((resolve, reject) => {
parseString(xml, { trim: true, ...opts }, (err, res) => {
if (err) reject(err);
resolve(res);
});
});
}
}
}