Files
docx-js/ts/export/formatter.ts

83 lines
2.0 KiB
TypeScript
Raw Normal View History

2016-03-28 00:53:24 +01:00
import * as _ from "lodash";
export class Formatter {
2016-03-31 04:33:06 +01:00
private xmlKeyDictionary = {
p: 'w:p',
t: 'w:t',
color: 'w:color',
space: 'w:space',
sz: 'w:sz',
val: 'w:val',
type: 'w:type',
ilvl: 'w:ilvl',
numId: 'w:numId',
pBdr: 'w:pBdr',
jc: 'w:jc',
r: 'w:r',
pPr: 'w:pPr',
pStyle: 'w:pStyle',
numPr: 'w:numPr',
b: 'w:b',
i: 'w:i',
u: 'w:u',
rPr: 'w:rPr'
2016-03-31 04:33:06 +01:00
};
format(input: any): Object {
var newJson = this.jsonify(input);
2016-03-28 00:53:24 +01:00
this.deepTraverseJson(newJson, (parent, value, key) => {
2016-03-31 04:33:06 +01:00
if (isNaN(key)) {
var newKey = this.getReplacementKey(key);
parent[newKey] = parent[key];
if (newKey !== key) {
delete parent[key];
} else {
console.error("Key is not in dictionary:" + key);
2016-03-31 04:33:06 +01:00
}
}
2016-03-28 00:53:24 +01:00
});
newJson = this.clenseProperties(newJson);
2016-03-28 00:53:24 +01:00
return newJson;
}
private clenseProperties(input: any): Object {
var newJson = this.jsonify(input);
this.deepTraverseJson(newJson, (parent, value, key) => {
if (key === "properties") {
delete parent[key];
}
});
return newJson
}
private jsonify(obj: Object): Object {
var stringifiedJson = JSON.stringify(obj);
return JSON.parse(stringifiedJson);
}
private deepTraverseJson(json: Object, lambda: (json: any, value: any, key: any) => void): void {
2016-03-31 04:33:06 +01:00
_.forOwn(json, (value, key) => {
2016-03-28 00:53:24 +01:00
if (_.isObject(value)) {
this.deepTraverseJson(value, lambda);
}
lambda(json, value, key);
});
2016-03-31 04:33:06 +01:00
}
private getReplacementKey(key: string): string {
var newKey = this.xmlKeyDictionary[key];
if (newKey !== undefined) {
return newKey;
} else {
return key;
}
}
2016-03-28 00:53:24 +01:00
}